Skip to content

add OpenAI-style ASR and TTS APIs - #215

Merged
Brooooooklyn merged 27 commits into
mlx-node:mainfrom
Saviio:feat/serve-audio
Oct 16, 2026
Merged

Brooooooklyn merged 27 commits into
mlx-node:mainfrom
Saviio:feat/serve-audio

Conversation

@Saviio

@Saviio Saviio commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Expose ASR and TTS through mlx serve, sharing the existing port, authentication, model coordinator and shutdown lifecycle. Add temporary reference voices for voice cloning with Base checkpoints.

Audio APIs

  • Extend /v1/models and add /v1/audio/voices capability discovery without loading model weights.
  • Add /v1/audio/transcriptions for multipart or raw WAV uploads, with JSON/text responses and SSE rolling transcript revisions.
  • Add /v1/audio/speech for complete WAV, streamed PCM16 and SSE audio output.
  • Add /v1/audio/speech/stream for NDJSON text input with concurrent PCM output.
  • Add reference voice creation, status lookup and release through /v1/audio/voices, with voice: { id } accepted by both speech endpoints.

Architecture and lifecycle

  • Reuse shared WAV/PCM processing in @mlx-node/core; no additional audio package.
  • Use typed ASR/TTS adapters, per-model serial queues and coordinated model loading/disposal.
  • Support separate chat/decision, ASR and TTS residency slots, plus an optional single-model policy.
  • Bound uploads, temporary storage, text input and output buffering; propagate network backpressure and cancellation through native completion.
  • Separate asynchronous voice metadata storage from runtime prepared-voice bindings, leaving room for future persistence.
  • Derive voice availability from native cache membership and model lifetime. Released or evicted handles cannot silently revive after model reload.

ASR inference performance

Profiling the native pipeline with MLX_METAL_COMMAND_TRACE=3 showed the whole Qwen3-ASR graph running in float32: Activations::gelu_exact built its constants as float32 scalar arrays, and MLX promotion widened the encoder output, the prefill, the KV cache and every decode step. Each token re-cast all 3.4 GB of bf16 decoder weights before every matmul.

  • gelu_exact now keeps the input dtype (same expression as the clef compiled builder; TTS is unaffected because its speech tokenizer is float32).
  • Greedy decode builds and async-submits step t+1 before reading token t, as the text engine does. Streaming revisions use the same fused C++ token step as one-shot transcription through a KV handoff that the next revision trims; the MLX_QWEN3_ASR_FUSED_DECODE switch and the per-layer Rust fallback are removed.
  • Mel extraction sums only each Slaney filter's non-zero span (same order, bit-identical) and skips reflection indexing for interior frames.

Qwen3-ASR-1.7B bf16 on M5 Max:

clip total before total after decode tok/s feature ms
3.4 s 622 ms 180 ms 30 → 116 5.8 → 0.8
29 s 4.1 s 1.05 s 29 → 117 51 → 6
58 s 8.5 s 1.95 s 28 → 112 177 → 13

Streaming (1 s chunks, 29 s clip): revision latency 137 → 117 ms median, decode 60 → 104 tok/s. scripts/server/asr-bench.ts and asr-stream-bench.ts reproduce the measurements on a converted checkpoint.

TTS inference performance

The same trace found no dtype promotion in TTS (the speech tokenizer is float32 by design). Profiling per component with the real checkpoint showed: the frame loop idled the GPU during every host-side graph build; the GPU then saturated on ~1,500 small dispatches per frame; and the speech codec cost ~12 ms per two-frame chunk for ~0.1 GB of weights because MLX's conv1d kernels are far off bandwidth on short, wide activations (transposed convolutions take the input-dilated fallback kernel).

  • Frame t+1 is built and submitted before frame t's token is read (lazy-token pipelining as in the text engine and ASR). The repetition-penalty history lives on the device (put_along_axis, bit-identical multipliers) so the next graph never waits on a host readback. The first PCM chunk of a segment is read back as soon as its frame retires.
  • Decoder layers hand their MLP delta to the following RMSNorm, which takes the existing fused add_rmsnorm dispatch (bit-identical); dense q/k/v and gate/up projections are stacked into one GEMV each; the predictor's codec-embedding gathers are reused for the next talker input.
  • Dense causal convolutions run as one GEMM over their K shifted taps; transposed convolutions with kernel == 2 × stride run one GEMM plus an overlap-add. Depthwise convolutions keep the conv kernels. The waveform moves at float32-GEMM tolerance (45 dB SNR vs the previous output); MLX_ENABLE_TF32=0 keeps the formulation at full float32 and is still faster than the convolution kernels.

Qwen3-TTS-12Hz-1.7B CustomVoice bf16, M5 Max, default sampling, seed 42 (scripts/server/tts-bench.ts):

utterance frames/s before → after RTF first PCM
2.5 s 43 → 49.5 0.29 → 0.25 75 → 42 ms
9.0 s 44.9 → 54.8 0.279 → 0.228 75 → 48 ms

Talker codec tokens are unchanged for every measured input (the talker/predictor changes are bit-identical); only the codec waveform differs, within the chunking parity tolerance.

Remaining budget per frame (~18 ms): talker 2.8 GB at ~385 GB/s and predictor 2.4 GB at ~360 GB/s against a measured MLX GEMV ceiling of ~450 GB/s; closing that needs custom fused GEMV kernels (norm/SwiGLU prologues, non-bit-identical), which this PR does not attempt.

Validation tooling

The Python SDK probes were removed; the OpenAI Node SDK suite (scripts/server/audio-sdk-smoke.ts, __test__/server/audio-sdk-retry.test.ts) is the single interoperability gate and the repo stays Python-free.

Protocol boundaries

  • Speech supports WAV and PCM16 only, with actual checkpoint sample rates exposed in response metadata.
  • ASR SSE events contain complete replacement snapshots, preserving the rolling model's revision semantics.
  • Reference voices are temporary and process-local. Reference audio and prepared state are not persisted.
  • Voice creation and NDJSON streaming are local extensions. WebSocket realtime sessions and VAD remain out of scope.
  • SSE completion events expose final audio statistics. Official SDKs do not expose PCM trailers; a PCM failure after streaming begins terminates the transport.
  • Pre-dispatch capacity errors remain retryable. Post-dispatch errors use the SDK-compatible X-Should-Retry: false hint where headers are still writable.

Performance port from sglang-omni (maintainer update)

This update rebases the PR onto main (ddabb67b5) and adds 21 commits. They port optimizations and behaviors from sglang-omni (2cfb3b6). Each commit was measured and gated alone. Commits that keep output keep ASR token ids and chat bytes equal.

Rebase

  • Only PR-owned files had conflicts:
    • package.json and yarn.lock: main removed openai, so the PR adds it back (7.19.0). The lock stays the same on a second install.
    • packages/cli/src/commands/agent/index.ts: main's version is kept.
    • packages/agent/__test__/provider-live.test.ts: main deleted it, so it stays deleted.
  • Main's MLX fork bump (chore(mlx): bump fork to upstream bebd6422f (2026-10-14), 4 patches #219) changes some outputs by itself. Before the port commits, main + this PR differs from the old fork on 2/200 ZH ASR clips and on 8/23 sampled TTS golden rows. The port commits are gated against this new baseline.

ASR

Token ids are equal for EN 200/200 and ZH 200/200. Streaming revisions are equal 574/574.

Change Measured (per request)
Resample through a per-phase weight table when the rate ratio is exact total −25 ms mean; feature 27.1 → 2.3 ms
Reply without waiting for the decode step queued past EOS −2 to −4 ms
Run encoder, prefill and first argmax as one lazy graph −9 to −10 ms
Run the one-token decode step unmasked, build step masks once −0.4 ms
Run decode-step SwiGLU and exact GELU as compiled kernels −1.3 to −2.2 ms
Default output budget max(128, ceil(10 × audio seconds)), as sglang-omni; an explicit max_tokens still wins behavior change; WER unchanged on EN1088 and ZH2020, 0 truncations

TTS

Change Measured
Draw each code with one fused Metal sampler kernel (tokens and RNG bit-identical) about −1 ms per frame (−5%)
Reuse prepared reference voices through a content-keyed LRU (256 entries / 64 MiB, as sglang-omni) repeat voice-create 275 → 0.5 ms
Run the codec conv stack on the reference tail only in voice prep (bytes equal) voice-create −83 to −179 ms
Decode non-stream TTS with 640 ms codec chunks −0.8 ms per frame (−4.7%); not byte-equal (min SNR 65 dB); +500 MiB peak
Emit the first PCM chunk of each segment after one codec frame stream first PCM 40 → 25 ms
Synthesize a string input as one sequence, as their JSON route. NDJSON, --file and stdin keep one segment per sentence, as their WS route. Default budget 2048 frames (163.84 s); the max_duration_seconds cap goes from 120 to 163.84 s behavior change
Drop the silent bootstrap frame from eligible streams, as their streaming vocoder first audible 113 → 49 ms; first PCM 29 → 43 ms

The bootstrap-frame drop works like this:

  • Which streams: streamed CustomVoice segments with preset ryan, language english, no instructions, and no sampling overrides.
  • What happens: the stream decodes frames 0 and 1 as its first chunk. If frame 0 is silent (RMS ≤ 0.001 and peak ≤ 0.0032), the stream drops it.
  • Opt-out: the new per-request field suppress_bootstrap_silence. It is accepted in the speech JSON body and the NDJSON config record. The SDK name is suppressBootstrapSilence.
  • Not dropped: WAV, synthesize() and CLI -o always keep frame 0.

Tests

  • A seeded TTS quality harness, scored like sglang-omni's TTS WER.
  • Per-request audio stage-time logs and a golden-output harness (scripts/server).
  • A batched decode step probe test (fused static vs paged).
  • A fix for main's qwen3-paged-zero-delta.test.ts. The test failed because the reply ended inside <think>, and it never hit the cache.
  • A fixed seed for the nemotron_h MTP test model. Its result depended on test order in a full run.

Compared with sglang-omni

M5 Max, bf16, SeedTTS, their benchmark client:

PR before This update sglang-omni
ASR c=1, req/s 5.45 6.90 6.04
ASR c=16, req/s 5.22 6.96 18.27
  • The "This update" ASR numbers come from the port head before the rebase, on the old MLX fork.
  • ASR at c=16 is still 0.38× theirs. Ours decodes one request at a time per model; theirs batches decode. This PR does not change that.
  • Their TTS runs on PyTorch MPS. There is no matched TTS comparison.

Validation on the rebased head

  • The full cargo test -p mlx-core and vp test ran once. The GSM8K dataset tests need the data file that CI downloads.
  • cargo clippy --all-targets -D warnings, cargo fmt, lint and typecheck are clean.
  • A Codex adversarial review ran 2 rounds. Round 1 found 1 defect, which is fixed: --play -o saved a WAV without frame 0. Round 2 found nothing.

🤖 Generated with Claude Code

@coderabbitai

coderabbitai Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: a57c9749-ace8-4924-bb55-74ca99534513

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@Saviio
Saviio force-pushed the feat/serve-audio branch 5 times, most recently from 8cbe7be to 864336e Compare October 13, 2026 12:05
Saviio and others added 24 commits October 16, 2026 15:27
Expose validated WAV and PCM primitives through core, retain the TTS audio API through thin wrappers, and add cancellable ASR tasks and stream disposal. Protect native prompt boundaries and expose checkpoint capabilities without loading weights.
Add audio model discovery and residency, WAV transcription with revision SSE, speech WAV/PCM/SSE output and NDJSON text input. Reuse authentication and model coordination with bounded queues, upload quotas, backpressure, cancellation and shutdown cleanup.

Include protocol and lifecycle regressions, HTTP language normalization, and official SDK retry tests covering admission failures and suppression after inference dispatch.
Document HTTP contracts, resource limits, metadata and retry boundaries, and provide a Node duplex streaming example. Add reproducible real-model benchmarks and official Node/Python SDK smoke tests.
… decode

`Activations::gelu_exact` built its constants as float32 scalar arrays. MLX
promotes bf16 * float32-array to float32, so the first encoder GELU widened
the audio tower, the audio embeddings, the multimodal prefill, the KV cache
and then every decode step to float32. Each token re-cast all 3.4 GB of bf16
decoder weights (AsType bf16->f32 before every matmul) and ran the lm_head as
a 1.2 GB float32 read. The scalar ops already build dtype-matched constants,
so the chain now matches the clef compiled builder and stays in bf16; TTS is
unaffected because its speech tokenizer weights are float32.

The decode loop now builds and async-submits step t+1 from the lazy argmax of
token t before the host reads token t (same pattern as the text engine), and
the streaming revision path uses the same fused C++ step as one-shot
transcription through a KV handoff that the next revision trims as before.
The MLX_QWEN3_ASR_FUSED_DECODE switch and the per-layer Rust fallback are
removed.

Mel extraction sums only each Slaney filter's non-zero span (same order, so
bit-identical) and skips reflection indexing for interior frames.

Qwen3-ASR-1.7B bf16, M5 Max, 58.5 s clip: total 8.49 s -> 1.95 s, decode
27.7 -> 112 tok/s, features 177 -> 13 ms, encoder 91 -> 49 ms. Streaming
revisions (1 s chunks) decode at 104 tok/s. Transcripts unchanged apart from
one bf16 greedy tie ("Enter" -> "enter"), which is also what the bf16 HF
reference produces.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…eout

The Python smoke/retry probes duplicated the Node OpenAI SDK suite check for
check (same generated client surface), so the TypeScript suite is now the
single interoperability gate and the repo stays Python-free at runtime.

Review follow-up: the multipart parser drain honors the configured input idle
timeout instead of a hardcoded 30 s.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
The talker/code-predictor frame loop built ~100 layer forwards, submitted
them with a blocking eval, then read the group-0 token back before the
next frame could start, so the GPU idled during every host-side graph
build. Frame t+1 is now built and submitted before frame t's token is read
(the same lazy-token pipelining the text engine and Qwen3-ASR use); the
in-flight frame is retired one iteration later and an EOS discards the
speculative successor.

That needed the repetition penalty off the host: the 64-token history is a
device array and the multipliers come from one put_along_axis into a
padding column that the slice drops, so an empty history yields exactly
one and the penalized logits are bit-identical to the CPU-built vector.
The sixteen codec-embedding gathers that fed the predictor are summed into
the next talker input instead of being gathered a second time, dense
q/k/v and gate/up projections are stacked into one GEMV each, and the first
PCM chunk of a segment is read back as soon as its frame retires instead
of being queued behind the next frame.

Qwen3-TTS-12Hz-1.7B CustomVoice bf16, M5 Max, seed 42, default sampling:
9 s utterance 44.9 -> 48.4 frames/s (RTF 0.279 -> 0.258), first PCM
75 -> 50-63 ms. Output PCM hashes are unchanged for every measured input.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
With the frame loop pipelined the GPU is saturated by ~1,500 small
dispatches per 80 ms frame, so the remaining time is kernel count and
kernel efficiency, not host readbacks.

Decoder layers now hand their MLP delta to the next layer's norm (and the
final norm), which takes the existing fused add_rmsnorm dispatch — the
kernel is bit-identical to the separate Add + fast::rms_norm pair, so the
talker, code predictor and codec transformer lose two dispatches per layer
without changing a byte of output.

The speech codec cost ~12 ms per two-frame chunk for ~0.1 GB of weights:
MLX's conv1d kernels are several times off bandwidth on its short, wide
activations and transposed convolutions take the input-dilated fallback
kernel. Dense causal convolutions now gather their K shifted taps and run
one GEMM; transposed convolutions with kernel == 2 * stride (every codec
upsampler) run one GEMM plus an overlap-add of the two half-kernel windows.
Depthwise convolutions and other geometries keep the convolution kernels.
The GEMMs reduce in a different order, so the waveform moves at float32
GEMM tolerance (45 dB SNR against the previous output on a 2.5 s clip;
MLX_ENABLE_TF32=0 keeps the same formulation at full float32 and is still
faster than the convolution kernels). Per-frame prefix preparation and
the chunking parity gate are unchanged.

Qwen3-TTS-12Hz-1.7B CustomVoice bf16, M5 Max, default sampling, seed 42,
9 s utterance: 50.5 -> 54.8 frames/s (RTF 0.250 -> 0.228), first PCM
52 -> 42 ms; 2.5 s utterance 44 -> 49.5 frames/s.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
CI runs clippy with --all-targets, which lints the test module and
rejects the over-long literal (excessive_precision).

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
… harness

Per-request audio metrics now carry the stage split the port needs:
ASR uploadMs, queueWaitMs, wavReadMs, featureMs, encoderMs, prefillMs,
decodeMs, totalMs and outputTokens; TTS pcmFrames next to firstPcmMs and
audioSeconds; voice creation wavReadMs and computeMs. The pretty session
log prints them as server()/perf()/audio() groups, like the chat lines.

New scripts (run with oxnode, no server):
- scripts/server/asr-golden-ids.ts: in-process Qwen3-ASR token ids over
  the bench client's SeedTTS sets (en200, zh200, en1088, zh2020), with
  the client's input fingerprint check and --concurrency N against one
  loaded model.
- scripts/server/tts-golden.ts: seeded CustomVoice (Ryan, 20 texts) and
  Base clone (3 references) PCM files with sha256. The TTS API exposes
  no codec codes, so none are recorded.
- scripts/server/compare-golden.ts: token-id and PCM comparison that
  re-hashes every PCM file, asserts counts, refuses self-comparison and
  exits non-zero on any mismatch.

Baselines on b6bf3c3: two fresh runs each of en200, zh200 and the TTS
set are equal; en200 at concurrency 4 and 8 also matches.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Ignored tests in qwen3_asr/batch_step_probe.rs, driven by
ASR_BATCH_MODEL and ASR_BATCH_CLIPS:
- decode_step_sweep: step time vs B for the fused dense step with [B,1]
  ids, per-row RoPE offsets and left padding, and for
  forward_paged_adapter_batched over a PagedKVCacheAdapter. Checks B=1
  fused-step logits bytes against decode_fused and per-row ids against
  the B=1 reference.
- decode_step_churn: steady B with rows joining and leaving every 5-15
  steps. Full rebuild, slot reuse with compaction, and paged admission,
  each against a control that skips the K/V copies.
- decode_step_trace: marked pipelined segments for the Metal command
  trace (dispatches and GPU time per step).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…tio is exact

resample_mono computed sin and cos for all 64 taps of every output sample.
When source/target reduces to p/q with q a power of two, out_idx * ratio is
exact in f64, so the tap distances repeat every q outputs. The weights and
their norm are now built once per phase, with the same expression and the
same tap order, so the output bytes do not change.

8k, 12k, 24k, 32k, 48k and 96k -> 16k, and 12k and 48k -> 24k use the
table. 44.1 kHz and every other pair keep the per-tap loop. Outputs whose
tap window is clipped at an input edge keep the per-tap expression.

Measured in one process with the old code behind a temporary per-call
toggle, interleaved A1/B/A2 per clip, en200 (all 24 kHz), 2 halves, 1200
requests:
  totalMs   B-A mean -25.4 / -24.6 ms per half (median -24.1 / -22.4)
  A-vs-A    largest |A2-A1| 2.0 ms
  featureMs mean 27.1 -> 2.3 ms
  log: /Volumes/P4510/.cache/bench/port/steps/A1/verify1/ab/en200-r1/analysis.txt

Exact gates vs b6bf3c3: token ids en200 + zh200 400/400, resampled
audio and mel of all 3108 SeedTTS clips equal, streaming revisions
574/574 rows, TTS PCM 23/23.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The one-shot transcribe synchronized after greedy_decode. On EOS that wait
only covered the step that was already queued past it, whose KV rows nobody
reads. The reply now goes out right after the last token read, and the
decode timer stops there.

Replying early is safe. Every input and sibling buffer of an encoded
primitive is retained until its command buffer completes, and the final
outputs are inputs of the async_eval synchronizer, so they are retained too.
The next request on the model thread uses the same thread-local queue and
lands behind the step. A one-shot request builds fresh KV caches. Dispose
only drops references the command buffer still holds. Streaming revisions
keep their own synchronize. The sglang-omni native transcriber does the same:
it breaks out of decode with the next token still queued and syncs only when
the worker is idle.

Measured in one process with the old wait behind a temporary per-call
toggle. en200 (all 24 kHz), 2 halves, same-arm pairs A1/B/A2 per clip,
1200 requests per half, paired per clip on the second request of each pair:
  25 ms gap after each request (reply latency):
    totalMs B-A mean -4.10 / -4.28 ms per half (median -4.26 / -4.47)
    A-vs-A  largest |A2-A1| 0.23 ms
    log: /Volumes/P4510/.cache/bench/port/steps/A2/verify1/ab/gap25-analysis.txt
  no gap, B after B (the leftover step lands in the next request):
    totalMs B-A mean -2.22 / -1.82 ms per half (median -2.33 / -1.75)
    A-vs-A  largest |A2-A1| 0.58 ms
    log: /Volumes/P4510/.cache/bench/port/steps/A2/verify1/ab/gap0-analysis.txt

Exact gates vs b6bf3c3: token ids en200 + zh200 400/400, streaming
revisions 574/574 rows. New opt-in test: back-to-back requests and a
dispose right after the reply.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
One-shot Qwen3-ASR transcribe no longer stops the GPU between the audio
encoder, the decoder prefill and the first token. sglang-omni's native
Qwen3-ASR transcriber does the same: it encodes, prefills and takes the
first argmax with one async_eval and no barrier in between
(sglang_omni_mlx/native/src/transcriber.cpp:257, :289-290).

Removed from the one-shot path:
- eval + synchronize after the audio encoder and after the prefill logits
- the every-8-layer eval in the audio tower and in the decoder prefill
- the per-layer SDPA eval in the decoder prefill. mlx_fused_attention_output
  gets an eval_attention argument; only the ASR prefill passes false.
  Attention::forward and TransformerBlock::forward pass true, so chat
  keeps the eval.
greedy_decode now async_evals the first argmax on its own, so the first
token read waits for the prefill only, not for decode step 1.

Stage times: Qwen3AsrResult.encoderMs is removed. prefillMs is the time
from the encoder start to the first token read. decodeMs runs from the
first token read to the last one. tokensPerSecond counts the tokens read
after the first. The server log and the scripts drop the encoder field.

Measured (in-process A/B, one process per half, toggle build read per
call, en200, 4 requests per clip in rotating ABBA/BAAB patterns, A-vs-A
arm, gap 25 ms), totalMs paired per clip, B minus mean(A1, A2):
  half 1: median -10.42 ms, mean -10.41 ms, B faster on 183/200 clips;
          A-vs-A median -0.85, mean -2.81 (foreign load spike mid-run)
  half 2: median -8.37 ms, mean -8.89 ms, B faster on 195/200 clips;
          A-vs-A median -0.21, mean -0.39
  Token ids equal to b6bf3c3 on all 1600 rows.
  Logs: /Volumes/P4510/.cache/bench/port/steps/A3/verify2/ab/
        analysis-h1.txt, analysis-h2.txt, h1/raw.jsonl, h2/raw.jsonl

MLX peak memory, b6bf3c3 -> this commit (MiB; weights 5231.3; same
token ids on both builds; runs base, final, final, base, equal per build):
  long20m.wav (1200 s, the server's maximum single call): 14248.9 -> 14248.9
  clip_58s: 5778.0 -> 5848.6 (+70.6)
  clip_29s: 5574.3 -> 5666.9 (+92.6)
  audio-ask-16k (3.35 s): 5279.7 -> 5318.4 (+38.7)
  The 20-minute clip ran with no GPU timeout, so no eval cadence is kept.
  The bounded transient on short and mid clips does not grow with length.
  Logs: /Volumes/P4510/.cache/bench/port/steps/A3/verify2/long/

Exact gates on this code: G-IDS en200 200/200 and zh200 200/200 equal to
b6bf3c3; G-STRM revision dump 574/574 equal; exact-check ASR 3 clips and
chat equal; G-CHAT cargo test -p mlx-core 0 failed, vitest 33/34 with the
same single zero-delta failure as b6bf3c3; G-SRV 116/116.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…s once

The ASR decode step passes no left_padding, so its one-token SDPA runs
with no mask. Every other fused Qwen3 step builds its causal mask once
per step instead of once per layer (all layers share one write
position). Qwen3 chat keeps passing its [0] padding array: unmasked
GQA 8/12/16 decode at 8192+ keys takes the fork's gqa 2-pass SDPA
kernel and would change its logits bytes. Qwen3-ASR is GQA 2.

Bytes: masked vs unmasked logits and KV bits are equal on every decode
step of en200 (3186), zh200 (2398) and a 20-min clip (3697 steps, keys
up to 19300). G-IDS 400/400 and G-STRM 574/574 equal to b6bf3c3;
chat tokens and logprobs equal to 2d4ddec14.

Perf, in process, one toggle build, en200, 1600 requests:
totalMs B - mean(A) = -0.365 ms mean, -0.424 ms median (B faster on
123/200 clips); A-vs-A -0.071 ms mean, -0.053 ms median.
Log: /Volumes/P4510/.cache/bench/port/steps/A4/verify2/ab/analysis-h1.txt
Chat decode (qwen3-0.6b, 128 tokens) vs 2d4ddec14: +5.57 tok/s mean,
+6.37 median (/Volumes/P4510/.cache/bench/port/steps/A4/verify2/chat/tps/analysis.txt).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The fused Qwen3 step (Qwen3-ASR decode and Qwen3 chat) now calls the
existing compiled_swiglu() instead of three separate ops.
Activations::gelu_exact (Qwen3-ASR encoder, Qwen3-TTS codec ConvNeXt
and Mimi MLP, clef eager fallback) now runs one compiled shapeless
kernel with the same ops, order and dtype constants as before.

Bytes: MLX's fused kernel rounds every intermediate to its array
dtype, so the outputs equal the separate ops. A probe on this machine
(M5 Max, macOS 27) checked every f32, bf16 and f16 GELU input and all
2^32 bf16 and f16 SwiGLU pairs: 0 differ. Old vs new in one process:
logits and KV bits equal on 3186 en200 + 2398 zh200 decode steps;
encoder output equal on 201 + 201 calls. G-IDS 400/400, G-STRM
574/574, G-PCM 23/23 equal to b6bf3c3; chat tokens and logprobs
equal to 12f1a951a. A new unit test checks fused vs separate bits for
all bf16 and f16 values and 2M f32 values.

Perf, in process, one toggle build, en200, 800 requests per half:
totalMs B - mean(A) = -2.243 ms mean, -1.311 ms median (B faster on
124/200 clips); A-vs-A +1.442 ms mean, -0.393 ms median. prefillMs
(encoder GELU) -0.734 ms mean, B faster on 151/200 clips.
Log: /Volumes/P4510/.cache/bench/port/steps/A7/verify1/ab/my-analysis-h1.txt
Earlier halves: -1.465 / -0.989 / -1.244 ms mean, -1.645 / -1.614 /
-1.201 ms median (/Volumes/P4510/.cache/bench/port/steps/A7/ab/analysis-h{1,2,3}.txt).
TTS frames/s: no change beyond the A-vs-A spread
(/Volumes/P4510/.cache/bench/port/steps/A7/tts-ab/r1/analysis.txt).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Without max_tokens, a one-shot transcription now gets
max(128, ceil(10 * audio seconds)) output tokens, as sglang-omni does
(native transcriber.cpp:276-283, request_builders.py:285-291). An
explicit max_tokens still wins and is never capped. Like their request
builder, the scaled budget is capped at the remaining context only while
that cap still allows 128. The fixed 256 SDK default and the server's
4096 one-shot default are removed. Streaming revisions keep 32 tokens
each: ours decodes only the continuation of about 2 s of new audio,
theirs re-decodes the whole segment.

No speed change is expected or claimed: on the bench sets the budget
never binds (at most 30 tokens with EOS, against a floor of 128).

Gates, logs under /Volumes/P4510/.cache/bench/port/steps/A9/verify1:
- G-IDS: en200 200/200 and zh200 200/200 token ids equal to b6bf3c3,
  no maxTokens sent (gids/compare-en200.txt, gids/compare-zh200.txt).
- G-WER via the server and the sglang-omni client: EN1088 corpus WER
  0.01187953995157385, ZH2020 0.005993407252022775, both equal to the
  PR mlx-node#215 server runs with the old 4096 default (dWER 0). Per-clip text
  diff: 0 lines. Every response finished with stop: 0 truncations
  (wer/diff.txt, wer/d_en_c16_serverlog, wer/e_zh_c16_serverlog).
- G-STRM: stream dump 574/574 rows equal to b6bf3c3 (strm/compare.txt);
  models::qwen3_asr 21 passed, 6 ignored; real-checkpoint prompt test
  passed (cargo/qwen3_asr.log, cargo/real-ckpt.log).
- G-SRV: 7 files, 117 tests passed (srv/vptest.log).
- The integer ceiling equals their float expression for every sample
  count up to 80 minutes (unit/formula_check.txt).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
… TTS WER

scripts/server/tts-quality.ts synthesizes 100 SeedTTS EN and 50 ZH texts
(the first distinct target_text rows of the bench client's en200/zh200,
id list in <out>/texts.json) with CustomVoice ryan and 3 Base references,
transcribes each output in process with Qwen3-ASR (native resampler to
16 kHz), and scores it with a port of their normalize_text, jiwer
process_words and calculate_wer_metrics. `report --baseline` fails when a
candidate's 3-seed mean is above the baseline max or a row failed.
Speaker similarity is not reported: the native TTS API exposes no speaker
embedding (prepare_voice returns only an id).

Measured, seeds 42/43/44, b6bf3c3 math:
- baseline/b6bf3c316/tts-quality/report.txt: wer cv-en 0.011894..0.013724,
  base-en 0.005489..0.009759; wer excl >50% cv-zh 0.022556..0.042303,
  base-zh 0.017193..0.026316
- determinism: seed 43 rerun in fresh processes on this tree's build:
  PCM 600/600 and ASR text 600/600 equal, all group values equal
  (steps/TQ/verify-r3/logs/rerun43-report.txt)
- scorer parity vs their Python code: 1800 baseline rows and 6000 fuzz
  rows, 0 mismatches (steps/TQ/verify-r3/logs/parity-baseline.txt,
  parity-fuzz3.txt)
Paths are under /Volumes/P4510/.cache/bench/port.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…U cache

A prepared voice condition is now keyed by sha256 of the sample rate, the
transcript and the mono f32 reference PCM, per model. Preparing the same
reference again returns a new id with no GPU work. Voice ids stay bounded
FIFO 8. Conditions stay in an LRU of 256 entries / 64 MiB of allocated state,
the same caps as sglang-omni (qwen3_tts/request_builders.py:1334-1344).
DELETE drops the id only; the condition leaves by LRU eviction, and a live id
keeps its condition after eviction. Two concurrent creates of one reference
prepare once: the per-model serial lane runs the second after the first, and
it hits the cache.

Measured, in-process interleaved A/B on one Base model (toggle build, 30
rounds x 3 references, arms rotated, load 2.5-3.1, 0 foreign builds):
voice-create median 275.3 ms (old path) -> 0.53 ms (hit). Paired hit minus
old: median -274.0 ms; -273.9 ms in the first half and -274.1 ms in the
second; all 90 pairs below -164 ms. A-vs-A spread: median -0.42 ms, range
-7.9 .. +11.8 ms. A miss on the new path vs the old path: median -0.83 ms,
inside the A-vs-A spread.
Log: /Volumes/P4510/.cache/bench/port/steps/T7a/verify/ab-r1/summary.txt

Gates: PCM of a hit equals PCM of a miss on the 3 Base references, seed 42
(verify/pcm/pcm.jsonl). G-PCM 23/23 equal to b6bf3c3 tts-r1 and tts-r2
(verify/compare-tts-r1.txt, compare-tts-r2.txt).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…ce prep

Voice prep ran the whole codec decoder on every reference frame and threw
the PCM away; only the retained state is kept. prepare_prefix still runs
the quantizer, pre-conv and transformer on every frame (their KV and
history need all of them). It now runs the conv stack (upsamplers, DAC
blocks, final conv) only on the last conv_stack_frames() frames. The conv
stack starts there from an empty state and ends with the same history
bits, because every step keeps the 1-frame shape.

conv_stack_frames() walks back from the final conv through each layer: a
causal conv adds (kernel - 1) * dilation, a transposed conv maps n samples
to (n + kernel - 1) / stride inputs. On the 1.7B codec this gives 10
frames. sglang-omni does the same walk in
Qwen3TTSIncrementalDecoder.tail_frames
(sglang_omni/models/qwen3_tts/incremental_codec.py:904-929) and decodes
only that tail in decode_tail (:931-958).

Measured, in-process interleaved A/B on one Base model (toggle build, 32
rounds x 3 references, blocks of A1 B B A2 in 4 rotated orders, every call
a cache miss; idle gate passed, load 3.4-4.8, 0 foreign builds):
voice-create median per reference (49/82/96 code frames)
A1 155/253/294 ms, A2 153/254/294 ms -> B 71/99/115 ms.
Per-block B minus A, median: -82.7/-153.5/-178.8 ms; first half
-83.9/-152.4/-178.6, second half -82.2/-154.6/-179.2. In all 96 blocks
both B calls were below both A calls. A-vs-A: arm median A2 - A1 is
-2.7 .. +1.9 ms per reference and half.
Log: /Volumes/P4510/.cache/bench/port/steps/T7b/verify1/ab2/analysis.txt

Gates: G-PCM 23/23 bytes equal to b6bf3c3 tts-r1 and tts-r2, the 3 Base
items included (steps/T7b/verify1/logs/compare-tts-r1.txt,
compare-tts-r2.txt). prepare_prefix_matches_per_frame is bit-equal on the
Base and CustomVoice checkpoints and fails when the tail is one frame
shorter (steps/T7b/verify1/mut/m1.log).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Each TTS draw (1 talker + 15 predictor codes per frame) ran about 13
dispatches: astype, divide, argsort, gather, compare, select, softmax,
random bits, 3 compiled kernels, argmax and any. It now runs one custom
Metal kernel: divide by temperature, exact top-k threshold (radix select),
softmax in block_softmax's reduction order, then the same keyed Gumbel-max
draw. It takes one u64 key per draw from the same RNG, so tokens and RNG
state are bit-identical to the old chain. Rows wider than 4096, other
dtypes and non-Metal devices run the same ops unfused.

Measured: one process, per-call toggle build, CustomVoice Ryan, seed 42,
texts cv-00..05, ABBA per text with an A-vs-A arm, 6 rounds, 144 calls,
all PCM equal to baseline. ms per frame:
  A1 median 19.69 / mean 20.06, A2 19.82 / 20.00, B 18.78 / 19.41
  B - mean A: -0.97 median, -0.62 mean (about -5%)
  A-vs-A |A2 - A1|: 0.13 median, 0.06 mean; both halves faster
  log: /Volumes/P4510/.cache/bench/port/steps/T4/verify/ab-v1/
       (raw.jsonl, analysis.txt, block.txt; load 10.8-13.9)
Implementer block: steps/T4/ab-r3, B - mean A median -0.83.

Gates: G-PCM 23/23 equal vs b6bf3c3 tts-r1 and tts-r2
(steps/T4/verify/gpcm). New parity test: fused token and RNG state equal
the composed sampler on widths 1..4099, f32/bf16, 4 temperatures, 7 top_k,
8 seeds. Scoped mlx-core lib tests 606 passed, 21 ignored. G-TTS 14/14.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
synthesize() and the server WAV path now default chunkDurationMs to
640 ms (8 codec frames). Streaming output (synthesizeStream, pcm, SSE)
keeps 160 ms. An explicit chunkDurationMs still wins.

Speed: one process, interleaved A/B with an A-vs-A arm. CustomVoice
ryan, seed 42, 20 SeedTTS texts plus one multi-sentence text, 3 rounds,
63 blocks. synthesisMs per frame:
  A1 160 ms: median 17.654, mean 17.665
  A2 160 ms: median 17.754, mean 17.780
  B  640 ms: median 16.821, mean 16.961
Gain -0.83 ms/frame median (-4.7%), -0.70 mean. A-vs-A spread 0.10
median, 0.11 mean. B is below both A arms in 60/63 blocks. Both halves
pass. Log: /Volumes/P4510/.cache/bench/port/steps/T2/verify2/ab/run1/analysis.txt

Output: wider codec steps are not byte-equal. Against the b6bf3c3
baseline: 23/23 items, equal sample counts, min SNR 65.00 dB (base-2).
Log: /Volumes/P4510/.cache/bench/port/steps/T2/verify2/logs/gsnr-tts-r1.txt

Memory: MLX peak minus active per call, median 415 -> 915 MiB
(+500 MiB, about 83 MiB per extra frame). Non-stream first PCM
42 -> 139 ms; a WAV is sent only after synthesis ends.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…rame

The first codec chunk of every generate() segment is now one frame
(80 ms). Later chunks keep the requested width (stream 160 ms, WAV and
synthesize() 640 ms). The one-frame chunk is still retired before the
next frame is built, so first PCM waits on frame 0 only.

Speed, in process, one interleaved A/B with an A-vs-A arm (toggle read
per call), CustomVoice ryan, seed 42, 20 SeedTTS texts, 40 blocks of
stream and WAV quads in 4 rotated orders. Stream first PCM
(TtsStats.firstPcmMs):
  A1 median 40.40, mean 41.48
  A2 median 39.85, mean 41.23
  B  median 24.86, mean 26.38
Gain 14.99 ms median, 14.85 mean; A-vs-A spread 0.55 / 0.25.
B is below both A arms in 40/40 blocks. ms/frame (synthesisMs/frames)
shows no regression beyond the A-vs-A spread: stream B 17.10 vs A
16.95/17.14 median, WAV B 16.35 vs A 16.19/16.27.
Log: /Volumes/P4510/.cache/bench/port/steps/T3/verify/ab-v1/analysis.txt
Implementer's two halves (same sign, 47.1 -> 29.4 ms median):
/Volumes/P4510/.cache/bench/port/steps/T3/ab-merged/analysis.txt

Output: codec codes are identical (A vs B on 40/40 text x mode pairs).
PCM is not byte-equal. Stream vs b6bf3c3 tts-r1 (20 CustomVoice
texts): 20/20 equal length, min SNR 61.60 dB. synthesize() (23 items
incl. 3 Base voices): min SNR 56.50 dB vs tts-r1, 56.48 dB vs the
previous commit.
Logs: /Volumes/P4510/.cache/bench/port/steps/T3/verify/codes.txt
      /Volumes/P4510/.cache/bench/port/steps/T3/verify/gate/gsnr-stream-vs-r1cv20.txt
      /Volumes/P4510/.cache/bench/port/steps/T3/verify/gate/gsnr-wav-vs-r1.txt

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
A string input (JSON speech route, CLI --text, SDK synthesize) is now
one segment instead of one restart per sentence, as sglang-omni does
(serve/openai_api.py:1506-1522, serve/speech_service.py:1124-1136).
Incremental input (NDJSON text stream, CLI --file and stdin) keeps one
segment per sentence, like their WS route (serve/speech_ws.py:514-534).

The default output budget is now their 2048 frames (163.84 s,
models/qwen3_tts/request_builders.py:68 and :755-757), cut with
finish_reason length. It replaces 120 s per segment. The server cap for
max_duration_seconds goes from 120 to 163.84 s.

Measured (CustomVoice ryan, seed 42 unless noted). Logs are under
/Volumes/P4510/.cache/bench/port/steps/T12A/verify:
- G-QUAL, 30 texts of 3-5 joined SeedTTS sentences, seeds 42/43/44.
  CV WER mean 0.008634, per-sentence baseline max 0.028257.
  Base WER mean 0.003401, baseline max 0.007849. 0 failed, 0 length.
  (logs/gqual-cv.txt, logs/gqual-base.txt)
- G-PCM: single-sentence golden wav 23/23 and stream 20/20 equal to
  the parent. (gpcm/cmp-wav.txt, gpcm/cmp-stream.txt)
- Fixed 10-sentence text, one process, interleaved A B B A, 4 rounds.
  RTF median, old -> new: wav 0.1980 -> 0.1928 (A-vs-A spread 0.0001),
  stream 0.2102 -> 0.2060 (spread 0.0011). The old path paid 9 segment
  restarts per call, p50 25 ms each, 233 ms per call. Audio is 35.84 s
  instead of 47.68 s. (ab-v1/analysis.txt)
- Same text, seeds 42/43/44, wav and stream: 0 word errors in our ASR
  transcript; the old path had 0-5. (content/final.log, content/head.log)
- A 2,533-char input now ends at 2048 frames with length; the old path
  finished it in 212.96 s over 41 segments. (logs/long-final.txt)

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Brooooooklyn and others added 2 commits October 16, 2026 15:57
The test sent an 11-token prompt with maxNewTokens 8 and thinkingTokenBudget 8.
Turn 1 ended inside an unclosed <think> block, so `text` was empty and the test
failed at the first assertion. The prompt also never filled one 16-token block,
so turn 2 could not hit the cache and the zero-delta cap never ran.

Use a prompt that spans several blocks, reasoningEffort 'none' and 16 new
tokens, and assert 0 < cachedTokens < promptTokens on turn 2 so the
max_cache_hit_tokens cap path is proven to run.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
… test order

mtp_ready_inner() builds the tiny model from random weights drawn from the
process-wide MLX key. Its value depends on how many draws earlier tests in the
same process made. In a full `cargo test -p mlx-core` run the draws gave
max |diff| = 0.0445 for the unshifted pairing in
mtp_prompt_seed_shifts_ids_by_one, below its 5e-2 margin, while the test passed
when run alone. Over seeds 1..20 the value ranges from 0.10 to 1.50.

Seed the key at the start of mtp_ready_inner(), as other tests here do.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
As sglang-omni does (models/qwen3_tts/streaming_vocoder.py:2310-2337,
request_builders.py:677-726), a streamed CustomVoice segment with preset
ryan, language english, no instructions and no temperature, top_k, top_p
or repetition_penalty decodes its first two codec frames as one chunk
(their bump, streaming_vocoder.py:1316-1321). When the first 1920 samples
are silent (RMS <= 0.001 and peak <= 0.0032) they are dropped and only
frame 1 is sent; frame 0 stays in the codec state. A first chunk of one
frame is sent unchanged. The check runs in emit_pcm, so every path that
completes the first chunk is covered, including max_frames 2 on the
tail. A NaN in frame 0 keeps it, as their docstring intends
(streaming_vocoder.py:2317-2318).

Every streamed segment is checked: their WS stream_audio:true runs one
request per sentence (serve/speech_ws.py:310-334). Per-request opt-out
suppress_bootstrap_silence (serve/protocol.py:401): top level of the
speech JSON and of the NDJSON config record, SDK suppressBootstrapSilence.
false keeps the frame, true does not force it, any other value is a 400.
WAV, synthesize() and any CLI -o (with --play too, where playback gets
the same full PCM) keep the frame, like their non-stream output (request_builders.py:1949-1954).

Measured, CustomVoice 1.7B ryan, seed 42. Logs are under
/Volumes/P4510/.cache/bench/port/steps/TSILv2:
- First audible, in process, one half, 16 texts, A = opt-out (A1, A2),
  B = default, 32 streams per arm (ab/h1.block/analysis.txt):
    audibleMs median A1 112.99, A2 112.06, B 48.98; paired B-A -64.68;
    A-vs-A 0.93 median, 0.47 mean; B earlier on 16/16 texts.
    firstPcmMs median A1 28.82, A2 27.93, B 43.20; paired B-A +15.32
    (two-frame first chunk); A-vs-A 0.90 / 0.47.
  Load 6-8 during the run; the idle gate timed out and is recorded.
- G-PCM wav 23/23 and stream 20/20 byte-equal to the pre-TSIL build
  9923267 (gpcm/cmp-wav.txt, gpcm/cmp-stream.txt).
- Eligible streams, 20 texts (en/check.txt): opt-out output byte-equal
  to the pre-TSIL build 20/20; frame 0 silent 20/20; default output
  exactly 1920 samples shorter 20/20, the rest at SNR min 63.28 dB,
  median 65.70 dB.
- Real server (srv/check.txt): pcm 3840 bytes shorter, SSE equal to pcm,
  wav equal for absent/true/false, NDJSON with 2 segments 7680 bytes
  shorter, the string "false" gives 400.

Not ported: their deployment switch and 24-stream cap, and the
initial_codec_chunk_frames and stream_codec_output fields. This server
runs one synthesis per model and exposes neither field.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@Brooooooklyn
Brooooooklyn merged commit 38c1b42 into mlx-node:main Oct 16, 2026
10 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants