Repository navigation
feat(models): Whisper ASR speech-to-text for /v1/audio endpoints - #371
Merged
Merged
Conversation
Port a Whisper-style encoder-decoder ASR model and wire it to the speech-to-text audio endpoints from #364. When the server's loaded checkpoint is detected as a Whisper model, the speech-to-text slot is populated so POST /v1/audio/transcriptions transcribes in place and POST /v1/audio/translations translates to English. Components: - Audio front-end (src/audio/whisper_mel.rs): Whisper log-mel (80/128 mel bins, n_fft 400, hop 160, 16 kHz, 30 s windows) with a Slaney-scale, Slaney-normalized filterbank and global-max log normalization. Reuses the shared real_fft_magnitude DSP primitive and adds 16 kHz linear resampling. - Model (src/models/whisper/): a convolutional plus transformer audio encoder and an autoregressive text decoder whose blocks add cross-attention to the encoder output, with tied logits. Greedy decode with a KV cache, language detection from the first decoder step, and Whisper token suppression (suppress_blank, non-speech symbols, the timestamp range under notimestamps). Loads both native MLX and HuggingFace key layouts and applies the bf16 to f16 conversion for non-quantized weights. - Tokenizer: byte-level BPE plus the Whisper special tokens (start-of-transcript, language tags, transcribe/translate, notimestamps, timestamps) resolved from the checkpoint tokenizer.json. - Detection and registry: model_type "whisper" maps to ModelType::Whisper in detection.rs, registered in the arch/list registry and the load-policy table. The chat loader fails clearly for a Whisper checkpoint since it is an ASR model, not a text generator. - STT provider (src/server/whisper_stt.rs): implements AudioModelProvider for speech-to-text and serializes MLX access behind a mutex. Wired in src/server/startup.rs via AppState::with_audio_model. Scope for this first port: greedy decoding, non-quantized (fp16/f32) checkpoints, single-model load (serving chat and speech-to-text on the same process is out of scope). Beam search, word-level and segment timestamps, quantized checkpoints, and streaming transcription are follow-ups.
Real-checkpoint end-to-end validation of the Whisper speech-to-text path aborted the server process on the first `POST /v1/audio/transcriptions` request with `libc++abi: terminating due to uncaught exception of type std::runtime_error: There is no Stream(cpu, 0) in current thread`. The audio routes dispatch the provider on tokio's blocking pool, and those pool threads have no MLX default stream installed, so the first array op in the Whisper encoder-decoder graph throws and the exception aborts the process across the cxx FFI boundary. Unit tests never evaluated the MLX graph, so they did not catch it. MLX work is thread-affine: every thread that touches MLX arrays must install a default stream first, exactly as the generation worker threads do. Add `mlxcel_core::streams::with_thread_local_default_stream`, which installs a per-thread stream as the default (created once per thread and cached, so a reused pool thread does not leak a stream per request), runs the closure, and synchronizes the stream before returning. Apply it at the shared audio dispatch seam in `audio.rs` so both the speech-to-text path and the future text-to-speech path inherit the fix. Defense in depth: add a `try_eval` FFI wrapper declared `-> Result<()>` so cxx catches any MLX exception at the boundary, and route the single graph-forcing eval in the Whisper decode loop through it. A stream, shape, or allocation failure now propagates as `AudioModelError::Inference` and a structured 500 instead of aborting the process. `WhisperModel::transcribe` and the decode helpers return `Result` accordingly. Validated with `cargo check --lib --tests`, `cargo clippy --lib --tests --features metal,accelerate -- -D warnings`, and the narrow mlxcel-core streams and Whisper module tests (the new `with_thread_local_default_stream_runs_and_reuses` test dispatches and evaluates a real op inside the guard).
Real-checkpoint validation of POST /v1/audio/transcriptions still failed after the prior stream-install fix, with "Whisper logits evaluation failed: There is no Stream(cpu, 0) in current thread". MLX work is thread-affine: loading a model initializes the full per-thread MLX scheduler context, including the CPU stream that decode-time ops and scalar readback resolve on. The previous attempt loaded the Whisper weights on the startup thread and evaluated the graph on tokio spawn_blocking pool threads, and installing only a GPU default stream on a pool thread does not create the CPU stream that loading on that thread would have. The generation path never hits this because BatchScheduler loads and runs every model on one owned thread after installing a thread-local default stream once. Restructure the audio path to mirror that ownership. A new AudioWorker (src/server/audio_worker.rs) spawns one dedicated thread that installs a thread-local default stream, loads an AudioEngine on itself so the weight arrays belong to that thread's MLX context, then serves transcribe and synthesize commands from a channel one at a time, synchronizing the stream after each. WhisperSttProvider now holds only the worker and forwards requests over the channel, so it carries no MLX handles and is plainly Send + Sync (the Mutex<WhisperModel> and unsafe Send/Sync impls are gone). The spawn_blocking closures in audio.rs no longer touch MLX; they only forward to the provider and block for the reply. A worker load failure is surfaced as an Err from spawn so the server boots with the audio slot empty rather than panicking, and Drop asks the loop to stop and joins the thread so the engine's handles are dropped on the thread that created them. The channel and engine trait are direction-agnostic so the text-to-speech provider can reuse the same single-thread pattern. The try_eval Result boundary in the Whisper decode loop and its AudioModelError::Inference mapping are kept, so any remaining MLX failure still surfaces as a structured 500 instead of aborting the process. The superseded with_thread_local_default_stream helper, its thread-local, and its test are removed since nothing depends on them now. Validated with cargo check --lib --tests, cargo clippy --lib --tests -- -D warnings, cargo fmt --check, and narrow cargo test --lib for the new server::audio_worker tests (including a worker round-trip that dispatches and evaluates a real MLX op on the dedicated thread) plus the mlxcel-core streams and server::routes::audio module tests.
resample_to_16k sized its output Vec at len * 16000 / src_rate. The shared WAV reader accepts any non-zero declared sample rate, so a well-formed upload claiming a tiny rate (for example 1 Hz) expands a few hundred thousand samples into hundreds of billions, and the Vec allocation aborts the whole server (panic = abort makes any allocation failure fatal). A single ~1 MiB request was enough to trigger it. Clamp the resampled length to MAX_RESAMPLED_SAMPLES (one hour of 16 kHz audio) via a small resampled_len helper, and add a regression test. The 25 MiB upload cap means a legitimate clip sampled at 8 kHz or higher never reaches the ceiling, so transcription output is unchanged; only pathological rates are truncated instead of crashing.
Remove stale Phase-1 language now that speech-to-text is functional. Clarify that /v1/audio/transcriptions and /v1/audio/translations work when a Whisper checkpoint is loaded via -m; /v1/audio/speech still returns 501. Specific changes: - Intro: replace Phase-1-only 501 description with current status - Source map: add audio_worker.rs and whisper_mel.rs entries - New section: Whisper STT setup (loading, WAV-only input, long audio windowing, current limits) - Transcriptions: tighten file field description to WAV-only - Phase-1-boundaries section: rename to Request validation order - docs/README.md: update audio-api.md description to match
Three narrow host-side tests for paths the HIGH-severity security fixes touch but that had no direct coverage: - reflect_pad_empty_returns_zeros: empty waveform yields 2*pad zeros without an out-of-bounds read, covering the n==0 early-return branch. - reflect_pad_shorter_than_pad_does_not_panic: input shorter than the pad width exercises the clamped-index prefix/suffix paths that prevent the unbounded-index panic the fix addressed. - very_short_audio_returns_empty_spectrogram: a single-sample clip returns (empty, 0) frames rather than panicking, confirming the early-return guard after reflect_pad works end to end.
Member
Author
PR Finalization CompleteTestsAdded 3 narrow unit tests to
Existing test counts: 12 whisper_mel, 15 models::whisper, 16 server::routes::audio, 3 server::audio_worker, 6 detection (including whisper detection). All pass. Documentation
Lint / Format
|
5 tasks done
inureyes
added a commit
that referenced
this pull request
Jun 20, 2026
Audio I/O on the OpenAI /v1/audio/* surface (Whisper speech-to-text #371, Kokoro-82M text-to-speech #374, endpoint plumbing #368), reasoning_content on non-streaming chat (#359), pre-M5 decode +8-12% via a hardware-gated op cap (#360), Turbo4Asym decode rerouted through dequant-SDPA (#369), batched sampling fixes (#339, #340, #344, #356), and the Turbo KV advisor/docs aligned to the measured sweep with ADR 0002 (#343, #376). README: consolidate the v0.3.0 and v0.3.1 highlights under a single v0.3 entry and add v0.3.2.
7 tasks done
inureyes
added a commit
that referenced
this pull request
Jun 21, 2026
…eout (#381) * perf(server): bound the audio request queue and add a per-request timeout The OpenAI audio endpoints dispatched work to one dedicated AudioWorker thread over an unbounded mpsc channel with no admission bound and no per-request timeout, so a burst could grow memory without bound (each queued command holds up to a 25 MiB STT payload) and a slow request could hang its caller. The PR #371 security review flagged both as MEDIUM availability risks. Bound the worker command channel with mpsc::sync_channel and dispatch via try_send: a full queue is rejected with the new AudioModelError::QueueFull, mapped to the shared 503 server_busy envelope. Add a per-request reply timeout (recv_timeout): a stuck request returns the new AudioModelError::Timeout, mapped to a structured 504 (server_timeout). The timeout frees the caller's blocking thread without cancelling the in-flight MLX work, which the worker can only process one at a time. Both changes live in the shared AudioWorker, so they cover the Whisper STT and Kokoro TTS paths together. Two new ServerConfig knobs, wired end to end like max_queue_depth: audio_queue_depth (default 8, flag --audio-queue-depth, env MLXCEL_AUDIO_QUEUE_DEPTH) and audio_request_timeout_secs (default 120, flag --audio-request-timeout-secs, env MLXCEL_AUDIO_REQUEST_TIMEOUT_SECS). A zero queue depth clamps to at least one queued command at the channel boundary; a zero timeout falls back to the default rather than timing out instantly. Tests: queue_full_returns_queuefull_error and request_timeout_returns_timeout_error at the worker level (no real model), plus route-level assertions that QueueFull maps to 503 and Timeout to 504. Docs: new admission/timeout section in docs/audio-api.md and env-var rows in docs/environment-variables.md. * fix(audio): guard Duration::ZERO in AudioWorker::spawn A Duration::ZERO passed to spawn would cause recv_timeout to return Err(Timeout) before the worker thread can reply, rejecting every request. Add a clamp symmetric with the existing queue_depth.max(1) guard: a zero timeout falls back to the documented default (120 s) so the worker behaves correctly regardless of what the caller passes. Add a focused unit test (zero_request_timeout_falls_back_to_default) that passes Duration::ZERO and verifies a fast request still completes.
be-free-snowboy
pushed a commit
to freestylejs/snowbrain-mlxcel
that referenced
this pull request
Oct 27, 2026
Closes lablup#365. Phase 2 of the OpenAI audio endpoints epic (lablup#363): a Whisper encoder-decoder ASR port wired to /v1/audio/transcriptions and /v1/audio/translations, with model load and inference on a dedicated MLX worker thread. Validated end-to-end against a real whisper-base checkpoint (accurate transcription and translation).
be-free-snowboy
pushed a commit
to freestylejs/snowbrain-mlxcel
that referenced
this pull request
Oct 27, 2026
Audio I/O on the OpenAI /v1/audio/* surface (Whisper speech-to-text lablup#371, Kokoro-82M text-to-speech lablup#374, endpoint plumbing lablup#368), reasoning_content on non-streaming chat (lablup#359), pre-M5 decode +8-12% via a hardware-gated op cap (lablup#360), Turbo4Asym decode rerouted through dequant-SDPA (lablup#369), batched sampling fixes (lablup#339, lablup#340, lablup#344, lablup#356), and the Turbo KV advisor/docs aligned to the measured sweep with ADR 0002 (lablup#343, lablup#376). README: consolidate the v0.3.0 and v0.3.1 highlights under a single v0.3 entry and add v0.3.2.
be-free-snowboy
pushed a commit
to freestylejs/snowbrain-mlxcel
that referenced
this pull request
Oct 27, 2026
…eout (lablup#381) * perf(server): bound the audio request queue and add a per-request timeout The OpenAI audio endpoints dispatched work to one dedicated AudioWorker thread over an unbounded mpsc channel with no admission bound and no per-request timeout, so a burst could grow memory without bound (each queued command holds up to a 25 MiB STT payload) and a slow request could hang its caller. The PR lablup#371 security review flagged both as MEDIUM availability risks. Bound the worker command channel with mpsc::sync_channel and dispatch via try_send: a full queue is rejected with the new AudioModelError::QueueFull, mapped to the shared 503 server_busy envelope. Add a per-request reply timeout (recv_timeout): a stuck request returns the new AudioModelError::Timeout, mapped to a structured 504 (server_timeout). The timeout frees the caller's blocking thread without cancelling the in-flight MLX work, which the worker can only process one at a time. Both changes live in the shared AudioWorker, so they cover the Whisper STT and Kokoro TTS paths together. Two new ServerConfig knobs, wired end to end like max_queue_depth: audio_queue_depth (default 8, flag --audio-queue-depth, env MLXCEL_AUDIO_QUEUE_DEPTH) and audio_request_timeout_secs (default 120, flag --audio-request-timeout-secs, env MLXCEL_AUDIO_REQUEST_TIMEOUT_SECS). A zero queue depth clamps to at least one queued command at the channel boundary; a zero timeout falls back to the default rather than timing out instantly. Tests: queue_full_returns_queuefull_error and request_timeout_returns_timeout_error at the worker level (no real model), plus route-level assertions that QueueFull maps to 503 and Timeout to 504. Docs: new admission/timeout section in docs/audio-api.md and env-var rows in docs/environment-variables.md. * fix(audio): guard Duration::ZERO in AudioWorker::spawn A Duration::ZERO passed to spawn would cause recv_timeout to return Err(Timeout) before the worker thread can reply, rejecting every request. Add a clamp symmetric with the existing queue_depth.max(1) guard: a zero timeout falls back to the documented default (120 s) so the worker behaves correctly regardless of what the caller passes. Add a focused unit test (zero_request_timeout_falls_back_to_default) that passes Duration::ZERO and verifies a fast request still completes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Port a Whisper-style encoder-decoder ASR model (Phase 2 of the audio-endpoints epic #363) and wire it to the speech-to-text endpoints from #364. When the loaded checkpoint is detected as Whisper, the server populates its speech-to-text slot so POST /v1/audio/transcriptions transcribes in place and POST /v1/audio/translations translates to English.
What changed
Validation
Unit-tested here (cargo test --lib whisper, cargo clippy --lib --tests -D warnings, cargo fmt --check, all clean):
Needs the real-checkpoint end-to-end run (release build, server, a real Whisper MLX checkpoint): the actual transcription and translation through POST /v1/audio/transcriptions and POST /v1/audio/translations, plus mlxcel list/arch output. These exercise the encoder/decoder MLX graph, which the unit tests do not run.
Deferred (follow-ups)
Closes #365