Skip to content

feat(models): Whisper ASR speech-to-text for /v1/audio endpoints - #371

Merged
inureyes merged 7 commits into
mainfrom
feature/issue-365-whisper-stt
Jun 19, 2026
Merged

inureyes merged 7 commits into
mainfrom
feature/issue-365-whisper-stt

Conversation

@inureyes

Copy link
Copy Markdown
Member

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

  • src/audio/whisper_mel.rs (new): Whisper log-mel front-end (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 primitive and adds 16 kHz linear resampling.
  • src/models/whisper/ (new module: mod, layers, encoder, decoder, tokenizer, decoding): convolutional plus transformer audio encoder, autoregressive text decoder with cross-attention to the encoder output and tied logits, greedy decode with a KV cache, first-step language detection, and Whisper token suppression (suppress_blank, non-speech symbols, timestamp range). Accepts native MLX and HuggingFace key layouts; applies the bf16 to f16 conversion for non-quantized weights.
  • src/models/detection.rs, src/models/mod.rs, src/model_metadata.rs: register model_type "whisper" as ModelType::Whisper in detection, the arch/list registry, metadata, and the load-policy table.
  • src/loading/mod.rs, src/distributed/tensor_parallel/inference.rs: the text loader fails clearly for a Whisper checkpoint (ASR, not a generator) and the tensor-parallel dispatch table stays total.
  • src/server/whisper_stt.rs (new): WhisperSttProvider implements AudioModelProvider for speech-to-text, serializing MLX access behind a mutex (matching the existing unsafe Send/Sync holder pattern).
  • src/server/startup.rs: detect Whisper at startup and attach the provider via AppState::with_audio_model.
  • docs/supported-models.md: add a Speech-to-text (ASR) section and update the variant count.

Validation

Unit-tested here (cargo test --lib whisper, cargo clippy --lib --tests -D warnings, cargo fmt --check, all clean):

  • mel front-end: frame counts (100 frames per 1 s, 3000 per 30 s), filterbank shape, periodic Hann window, normalization band, tone energy in low mel bins, resampling.
  • tokenizer: special-token and language-tag resolution, sot-sequence ordering, suppression-set union, text decode dropping specials and timestamps.
  • decoding: suppression, first-step, and language masks (keep eot, block specials and the timestamp range).
  • model config: native and HuggingFace dimension parsing, padded-window zero-padding.
  • detection and registry: model_type "whisper" resolves to ModelType::Whisper, arch-registry completeness.

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)

  • Beam search and temperature fallback.
  • Word-level and segment timestamps.
  • Quantized (4-bit/8-bit) checkpoints.
  • Streaming transcription.
  • Higher-quality (sinc/polyphase) resampling.
  • FFT-based front-end (the current path reuses the shared naive DFT).

Closes #365

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.
@inureyes inureyes added status:review Under review type:enhancement New features, capabilities, or significant additions priority:medium Medium priority area:models Model architectures, weights, loading, metadata area:inference Generation, sampling, decoding (incl. speculative, DRY) labels Jun 19, 2026
inureyes added 6 commits June 19, 2026 15:48
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.
@inureyes

Copy link
Copy Markdown
Member Author

PR Finalization Complete

Tests

Added 3 narrow unit tests to src/audio/whisper_mel.rs:

  • reflect_pad_empty_returns_zeros: empty waveform takes the n==0 early-return branch; output is 2*pad zeros with no out-of-bounds read.
  • reflect_pad_shorter_than_pad_does_not_panic: input shorter than the pad width exercises the clamped-index prefix/suffix paths that the HIGH-severity padding fix corrects.
  • very_short_audio_returns_empty_spectrogram: single-sample clip returns (empty, 0) frames, confirming the early-return guard after reflect_pad works end to end.

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

docs/audio-api.md:

  • Replaced the stale Phase-1-only 501 description with an accurate current-status paragraph: STT works when a Whisper checkpoint is loaded; TTS still returns 501.
  • Expanded the source map to include audio_worker.rs and whisper_mel.rs.
  • Added a Whisper STT setup section covering checkpoint loading, WAV-only audio input, long-audio windowing, and current limitations (no quantized checkpoints, greedy-only).
  • Tightened the file field description in the transcriptions table to WAV-only.
  • Renamed the Phase 1 boundaries section to Request validation order.

docs/README.md: updated the audio-api.md entry description to match.

docs/supported-models.md: already accurate; no changes needed.

Lint / Format

cargo fmt --check: clean. cargo clippy --lib --tests --features metal,accelerate -- -D warnings: clean.

@inureyes inureyes added status:done Completed and removed status:review Under review labels Jun 19, 2026
@inureyes
inureyes merged commit f58df39 into main Jun 19, 2026
4 checks passed
@inureyes
inureyes deleted the feature/issue-365-whisper-stt branch June 19, 2026 08:19
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.
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.
@inureyes inureyes added this to the 0.3 milestone Jun 21, 2026
@inureyes inureyes self-assigned this Aug 31, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:inference Generation, sampling, decoding (incl. speculative, DRY) area:models Model architectures, weights, loading, metadata priority:medium Medium priority status:done Completed type:enhancement New features, capabilities, or significant additions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(models): Whisper ASR port for speech-to-text (/v1/audio/transcriptions)

1 participant