Skip to content

chore(mlx): bump fork to upstream bebd6422f (2026-10-14), 4 patches - #219

Merged
Brooooooklyn merged 8 commits into
ci/faster-build-testfrom
chore/mlx-bump-2026-10-14
Oct 15, 2026
Merged

Brooooooklyn merged 8 commits into
ci/faster-build-testfrom
chore/mlx-bump-2026-10-14

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #218 (base branch ci/faster-build-test, GitHub stack #220); retarget to main once that merges.

Summary

Rebases the fork patch stack onto ml-explore/mlx main bebd6422f (56 upstream commits). Also the first real exercise of the prebuilt-MLX bump flow from #218: pushing the gitlink published the release with no manual step, and crates/mlx-sys/mlx-prebuilt.json pins mlx-prebuilt-bcad393045a2-4610d72d.

ml-explore/mlx main  bebd6422f (2026-10-14)
        │  + 4 patches   (patch 5 dropped: upstream merged the same fix as 9503cb7e4 / #4623)
        ▼
mlx-node/mlx         bcad39304   fork branch mlx-node/rebase-2026-10-14  (fork main NOT yet moved — step 8)
  • mlx_paged_profile.cpp: array(Buffer, shape, dtype, Deleter) → array(allocator::Data(buffer, deleter), shape, dtype) (upstream #4634). Every other bridge call site audited; the D=256 SDPA predicate mirror still matches upstream.
  • paged_kv_cache_adapter.rs: upstream #4366 makes the [1,T,H,D] transpose + reshape a strided view; the raw write_kv path assumed a copy and swapped tokens/heads on multi-head sliding restore. Now deep_copys into a row-contiguous buffer (the only caller of the raw path).
  • mlx_qwen4_ops.cpp: upstream #4516 changed load_vector to sum activations in float before folding the affine bias (5-bit arm); the affine expert GEMV mirrors MLX's gather_qmv bit for bit and now carries that form (load_vector_fsum). The vendored kquant.h keeps the older sum on purpose (K-quant goldens must not move).
  • affine_mixed_golden_gate fixtures: 237 promoted lines re-captured per docs/mlx-fork.md (attribution 494c8a6c9 / #4641, route-back proof old==new off split-K on all 7 routes, f64 reference table in the commit message, native lines untouched).
  • metallib-select.ts: steel_gemm_thin_nax added to the NAX markers (new in this range).
  • docs/mlx-fork.md: 4 patches, new base, bump step 6 = push the gitlink.

Gate status on this pin (M5 Max, all captured arches)

gate / test status note
segmented_sdpa_golden_gate green —
affine_mixed_golden_gate green re-captured (promoted only), see commit 6edf0f6
affine_direct_experts_preserve_promoted_arithmetic_and_tail_rows green fixed, commit 767de22
kquant_golden_gate 15 cases, gen-17 only red, pre-existing identical failures on a pristine origin/main checkout with the old pin — not this bump; needs its own issue

Not yet done from the bump checklist: step 7 benches (ABBA), step 8 force-push of fork main (the rebased stack is on fork branch mlx-node/rebase-2026-10-14; the gitlink is reachable from it, so CI clones fine).

Test plan

  • patch stack rebases; standalone CMake configure clean at 26.2 (NAX kernels build)
  • cargo build --release -p mlx-core against the new pin; yarn build:native gates with the new metallib markers
  • restore_sliding_prefix_materializes_multi_head_layout and affine_direct_experts_preserve_promoted_arithmetic_and_tail_rows green locally
  • golden gates on M5 Max across the arch matrix (table above)
  • release mlx-prebuilt-bcad393045a2-4610d72d published by the workflow; digest pinned and cross-checked against its .sha256
  • CI green once retargeted to main

Generated with Devin

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-15T10:31:12.821457Z 322eb2a New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@coderabbitai

coderabbitai Bot commented Oct 15, 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: a210da8c-5c40-4c5d-9eaa-9022870daec0

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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ffdd046312

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread crates/mlx-sys/mlx-prebuilt.json Resolved
Comment thread crates/mlx-sys/mlx-prebuilt.json Resolved
@Brooooooklyn
Brooooooklyn added this pull request to stack #220 October 15, 2026 02:51
@Brooooooklyn
Brooooooklyn force-pushed the chore/mlx-bump-2026-10-14 branch from ffdd046 to f1b5fac Compare October 15, 2026 03:10

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f1b5fac372

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread crates/mlx-sys/mlx-prebuilt.json Resolved
@Brooooooklyn
Brooooooklyn force-pushed the chore/mlx-bump-2026-10-14 branch from d7b6a04 to 6edf0f6 Compare October 15, 2026 03:56

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6edf0f6e7c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@Brooooooklyn
Brooooooklyn force-pushed the chore/mlx-bump-2026-10-14 branch 3 times, most recently from e0a1d16 to 68dce55 Compare October 15, 2026 06:05

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 68dce552a8

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread packages/core/metallib-select.ts Resolved
Brooooooklyn and others added 8 commits October 15, 2026 18:27
Rebase the patch stack onto ml-explore/mlx main (56 upstream commits).
Patch 5 (residency-set NSError use-after-free) is dropped: upstream merged
the same fix as 9503cb7e4 (#4623). The only bridge drift is upstream #4634
(foreign buffer ownership): `array(Buffer, shape, dtype, Deleter)` became
`array(allocator::Data, shape, dtype)`, so the paged-profile view now wraps
its retained MTL::Buffer in the non-owning `allocator::Data(buffer, deleter)`.
Every other bridge call site was audited against the new signatures
(`force_fused`, `global_scale`, `CompileOptions`, dynamic copy offsets all
land in slots the bridge either stops before or fills explicitly); the
D=256 SDPA predicate mirror in mlx_stream.cpp still matches upstream.

`steel_gemm_thin_nax` (new in this range) joins the NAX metallib markers
so a metallib from the previous pin cannot pass the packaging gate.

The MLX Prebuilt workflow now runs on a gitlink push from any branch of
this repo (gated on github.repository), so a bump PR gets its release
before it pins it; dispatch only sees workflows on the default branch.

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

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

With ml-explore/mlx#4366 `collapse_contiguous_dims` skips unit dims, so the
[1,T,H,D] transpose + reshape to [T,H,D] is served as a strided view
instead of a copy. `write_kv` reads the raw buffer as contiguous [T,H,D]
and silently swapped tokens and heads for multi-head sliding groups
(restore_sliding_prefix_materializes_multi_head_layout). deep_copy into a
fresh row-contiguous buffer, which is what the reshape used to do.

Also pins mlx-prebuilt.json to release mlx-prebuilt-bcad393045a2
(published automatically by the gitlink push).

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

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Upstream ml-explore/mlx f8aaf49d4 (#4516) changed `load_vector` to add the
activations in `U` (float) before folding the affine bias, instead of adding
the half inputs first; the 8-bit arm is unchanged. The affine expert GEMV
mirrors MLX's gather_qmv bit for bit, and after the bump its 5-bit f16
(K=640, N=2560, rows=10) case was one f16 ulp off (unit test
affine_direct_experts_preserve_promoted_arithmetic_and_tail_rows).

The kernel now carries its own `load_vector_fsum` in the current upstream
form. The vendored kquant.h keeps the older sum on purpose: the K-quant
kernels and their goldens are built on it and must not move.

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

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Published by the workflow from the gitlink push; digest cross-checked
against the release's .sha256 sidecar.

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

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

Only `promoted` lines change: MLX's own F32 QuantizedMatmul graph, which
the bump moved through one upstream commit:

- 494c8a6c9 (#4641): `qmm_splitk` sums its float32 split-K partials with
  the `steel_gemm_splitk_accum` kernel instead of a strided "sum"
  reduction. Same partials, different summation order. For f32 x the
  `qmm_t_splitk` kernel itself is unchanged (its new `U` output type is
  `float` = `T`).

Every `native` line (our kernel) is byte-for-byte the pin-053e43fec line;
the re-capture script refused to touch one. With MLX_QMM_SPLITK_MIN_M=34
(M <= 33 routed off split-K, the only changed code) old and new pins give
byte-identical outputs on every case of every route. Re-captured per
route: g17s 23+0, g17d 29+2, g17g 23+0, g17p 23+0, g16s 35+0, g14s 67+4,
g14d 29+2 (matmul + shapeless), 237 in all. Every moved case has
M >= get_qmv_batch_limit for its route, i.e. runs qmm_splitk.

Accuracy of the 237 moved cases against an f64 reference computed on the
host from the same codes, scales, biases and BF16 inputs. "old" is pin
e091d6784, built and run in a separate worktree, where it reproduces every
old fixture line; "new" is this pin. 330 of 332 moved elements shift by
one BF16 step; the other 2 shift by two steps on values of ~1e-8 against
case scales of ~1e-2 and ~1e-1, both landing closer to f64. Moved
elements land closer to f64 151 times and farther 181 times:

family                         cases      elems moved closer/farther max|err| old=new             rel L2 old -> new
gs128 b4 N512 K5120               31      59 / 427520          22/37            1.987 1.669229e-03 -> 1.669229e-03
gs32 b4 N1000 K1024                2        2 / 34000            0/2            0.966 1.639417e-03 -> 1.639417e-03
gs32 b4 N136 K768                  9        9 / 36040            0/9            0.958 1.650661e-03 -> 1.650661e-03
gs32 b4 N512 K5120                21      22 / 207872           20/2            1.964 1.650230e-03 -> 1.650230e-03
gs32 b8 N1000 K1024                6      12 / 102000            4/8            7.994 1.664752e-03 -> 1.664752e-03
gs32 b8 N136 K768                 14       14 / 62832            7/7           0.2496 1.614269e-03 -> 1.614269e-03
gs32 b8 N512 K5120                43      58 / 458752          24/34            27.32 1.664340e-03 -> 1.664340e-03
gs64 b4 N1000 K1024                6      10 / 102000            4/6           0.9973 1.653433e-03 -> 1.653433e-03
gs64 b4 N136 K768                  2         2 / 4624            0/2         2.894e-5 1.678121e-03 -> 1.678121e-03
gs64 b4 N512 K5120                48      76 / 547328          40/36            1.991 1.667613e-03 -> 1.667613e-03
gs64 b8 N1000 K1024                4        8 / 68000            0/8            7.982 1.656618e-03 -> 1.656618e-03
gs64 b8 N136 K768                  9        9 / 36040            2/7            7.776 1.677706e-03 -> 1.677706e-03
gs64 b8 N512 K5120                34      37 / 358912          22/15               29 1.681386e-03 -> 1.681386e-03
shapeless gs32 b8 N512 K5120       8       14 / 45056            6/8           0.7926 1.630393e-03 -> 1.630393e-03
ALL                              237    332 / 2490976        151/181                  1.672573e-03 -> 1.672573e-03

max |err| is unchanged in every family, and rel L2 is unchanged to 7
digits in every family (largest relative move 1.1e-8). The gate passes on
all 7 routes.

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

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

Once `allocator::Data` holds the deleter, its destructor already releases
the retained reference when the `array` constructor throws; the catch block
released it again, which could consume the pool holder's own reference.
Track whether the deleter was handed over and release in the catch only
when it was not.

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

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Same fork commit, new build key after PREBUILT_BUILD_KEY_REVISION entered the
key. Verified: asset digest equals the release's .sha256 sidecar, and a fresh
cache links against it.

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

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

checkMetallibPair checked only that mlx.metallib carries some NAX kernels,
so a library left over from the previous pin (e091d6784: has
steel_attention_dsplit, lacks steel_gemm_thin_nax) passed and would ship
with this bump's fixes missing. It now runs the same assertMetallibIntegrity
gate as yarn build:native, which includes NAX_KERNEL_MARKERS; the size floor
stays in resolvePayload. Test added with the previous pin's name set;
verified against a real stale e091 metallib (rejected) and a fresh bcad
build (accepted).

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

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@Brooooooklyn
Brooooooklyn force-pushed the chore/mlx-bump-2026-10-14 branch from d689937 to 322eb2a Compare October 15, 2026 10:27
@Brooooooklyn
Brooooooklyn merged commit c0b6f82 into main Oct 15, 2026
11 checks passed
@Brooooooklyn
Brooooooklyn deleted the chore/mlx-bump-2026-10-14 branch October 15, 2026 11:42
Brooooooklyn added a commit that referenced this pull request Oct 15, 2026
…rallel pure-TS lane (#221)

## Summary

Stacked on #219. Makes the test suite cheaper without dropping the
regressions it guards. Research first (per-test timings from CI logs,
then code reading), then four scoped commits.

### Where the time went

```
rust-lib   4198 tests  921 s          rust-int   96 binaries  1160 s
├─ 1 test  int8_verify_routes   336 s  ├─ kquant_m8_nax              372 s   3 tests
├─ 4 tests qwen4_exp prefill    147 s  ├─ kquant_mode_guards         296 s  12 tests
├─ 2 tests int8 (others)         74 s  ├─ kquant_tiled               201 s  11 tests
├─ 5 tests retention_sim         56 s  ├─ kquant_affine_tiled         97 s   4 tests
└─ 4186 tests                   ~300 s ├─ kquant_metallib_names       93 s   2 tests
                                       ├─ bridge_metallib_names       51 s   4 tests
TS (vitest) 3775 tests          220 s  └─ 90 binaries                ~50 s
```

Root cause: `cargo test` ran at opt-level 0, and the slow tests are f64
CPU reference loops / host-side data generation (the test files
themselves say `cargo test --release` in their headers). The MLX C++
side is always Release.

### Commits

1. **`[profile.test] opt-level = 2`** — measured: `int8_verify_routes`
255 s → 34 s, `kquant_m8_nax` 253 s → 30 s; mlx-core compile 3m03s →
4m46s (18 cores). Full `--lib` suite 921 s (CI) → 317 s locally with no
test touched. Debug assertions / overflow checks stay on.
2. **K-quant integration trims** — build-every-pipeline tests
(`#[ignore]`, now run in the qwen3 model-test leg on main), determinism
sweeps 20–24 repeats × full grid → 3 × representative, bulk FFI readback
in `kquant_mode_guards`.
3. **Unit-test sweeps** — int8 prefixes chosen from the segmented-SDPA
plan boundaries (150 → 50 cases, every route still hit per layout),
qwen4_exp prefill parity on a table of distinct mechanisms (70 → 16
combos), `retention_sim` reports behind `#[ignore]`, asserted cells
kept.
4. **vitest two lanes** — `pure-ts` parallel, `addon` serial; membership
traced from the import graph at config load (`scripts/test-lanes.ts`).
TS tests pinned exactly by Rust unit tests removed; `expect(true)`
train() tests now assert the batch contract; the flaky `stdReward > 0`
test made deterministic (greedy); two never-run paged TS gates wired
into the qwen3 model leg.

### Measured locally (M5 Max), after all four

```
                         before (CI, debug)   after (local, opt 2)
mlx-core --lib           921 s                 90 s   (4053 passed, 153 ignored)
6 hot kquant binaries   1109 s                202 s   (142 s of it is one CPU-reference test, see below)
vp test                  220 s                127 s
```

### Left alone on purpose (product calls)

- `kquant_tiled::kquant_modes_take_no_row_tier_past_m8` — 115 s, 45
single-thread CPU reference matmuls at M=40 on Qwen3.8 shapes. Now the
single biggest Rust test; shrinking it is a coverage decision.
- `kquant_m8_nax::m8_nax_matches_cpu_on_every_mode_and_shape` (31 s) —
not a subset of the tiled test (outlier channels, signed sub-scales,
production dispatch), kept.
- `RUST_TEST_THREADS=1` — load-bearing (global RNG, default device,
route counters).
- 15 pre-existing K-quant golden failures on `main` — untouched.

#### Test plan
- [x] `cargo test -p mlx-core --lib` 4053 passed / 0 failed
- [x] the 6 touched integration binaries + their `--ignored` pipeline
tests pass
- [x] `vp test`: only environmental failures locally (gsm8k file, local
addon older than `index.cjs`)
- [x] fmt / clippy / typecheck / lint / actionlint clean
- [ ] CI on this PR (runs once #218 merges and the stack is retargeted)

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

---------

Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Brooooooklyn added a commit that referenced this pull request Oct 16, 2026
## 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 (#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](https://claude.com/claude-code)

---------

Co-authored-by: LongYinan <[email protected]>
Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Brooooooklyn added a commit that referenced this pull request Nov 29, 2026
…only test gates (#437)

## Summary

Fixes the concrete leftover bugs found while auditing #201 (no CI
changes, since CI already runs on M1; no `mlx` submodule bump needed):

1. **Keep `kquant_qmm_t_splitk` partials in `float32`**
(`crates/mlx-sys/src/metal/kquant/kquant.h`,
`crates/mlx-sys/src/metal/mlx_kquant_metal.cpp`):
- Mirrors upstream MLX PR #4641 (`494c8a6c9`, already in our pinned
`mlx` submodule) inside our K-quant / Tiled64 bridge.
- Previously, `qmm_splitk` allocated its partial-sum buffer in
`x.dtype()` (`bfloat16`/`float16`) and summed via
`strided_reduce_general_dispatch`, truncating every K-partition to 7-bit
BF16 before summing. On M1/M2 (`applegpu_g13s`/`g14s`, where
`qmv_vector_limit = 6`), DFlash2 merged-vs-separate projections at `T =
6..8` hit `qmm_t_splitk_t64` with different split counts (`4` vs `2`)
and flipped **47.7%** of elements (`11726/24576`).
- Now `kquant_qmm_t_splitk` writes `float32` partials and sums/casts
once via MLX's `steel_gemm_splitk_accum` kernel (`0.00%` drift on
`a4g64@t64` `split_k 32 vs 2`; `0.01%` on `q4k`).
2. **Version split-K Metal symbols (`_f32`) + packaging integrity gate**
(`crates/mlx-sys/src/metal/kquant/kquant.metal`,
`crates/mlx-sys/src/metal/mlx_kquant_metal.cpp`,
`packages/core/metallib-select.ts`,
`__test__/core/metallib-select.test.ts`):
- Adds an `_f32` suffix to both row-major and Tiled64 split-K Metal
symbol names so an older prebuilt `paged_attn.metallib` throws
`PrebuiltKernelMissing` instead of silently writing 16-bit partials into
a `float32` buffer.
- Adds `_f32` split-K markers across all three per-dtype `kquant` AIR
units (`float`, `float16_t`, `bfloat16_t`) and all three split-K forms
(row-major, Tiled64, affine Tiled64) with exact NUL-delimited matching
in `assertPagedMetallibIntegrity`.
3. **Relax strict `gpu_gen == 17` test gates**
(`crates/mlx-core/src/models/qwen3_5/dflash2/tests.rs`,
`crates/mlx-core/src/models/quantized_linear.rs`):
- `merged_draft_projections_match_separate_bits`: switches `gpu_gen ==
17` to `mlx_metal_is_nax_available()`, keeps `T > merged_rows()` (`T =
87`) exact on every GPU, checks `qmv_vector_limit`, and gates `T = 1`
exactness on `mlx_gpu_core_count() >= 33` (matching `tiled_qmv_rows`).
- `kquant_tiled_tests::same_kernel_for_m`: switches `gpu_gen() == 17` to
`gpu_gen() >= 17` so gen-18+ isn't dropped from the exact-bit arm.
4. **Regression tests**:
- `kquant_tiled::qmm_splitk_bf16_partials_stay_float32` (`q4k` row-major
& Tiled64, `split_k = 32` vs `2`).
- `kquant_affine_tiled::affine_qmm_splitk_bf16_partials_stay_float32`
(`a4g64@t64`, `split_k = 32` vs `2`).
- Stale / mixed-dtype pre-`_f32` split-K fixtures in
`__test__/core/metallib-select.test.ts`.

## Verification (Apple M5 Max, `MLX_METALLIB_STRICT=1`)

- `merged_draft_projections_match_separate_bits`: **PASS** across
`native`, `applegpu_g00g`, `g13s`, `g14s`, `g14d`, `g15s`, `g16s`,
`g17p`, `g18s`.
- `kquant_tiled_tests`: **PASS** across `native`, `g00g`, `g13s`,
`g16s`, `g17p`, `g18s`.
- `kquant_suite`: **87/87 PASS** (`native`); new split-K regressions
**PASS** across `native`, `g00g`, `g13s`, `g16s`, `g18s`.
- `kquant_metallib_names`: **5/5 PASS** (3,084 functions + JIT
preamble).
- Stale `paged_attn.metallib` rejected both at packaging
(`assertPagedMetallibIntegrity`) and at runtime (`Cannot load K-quant
kernel ..._f32`).
- `cargo fmt --all -- --check`, `cargo clippy --locked -p mlx-core -p
mlx-sys --all-targets -- -D warnings`, `vp fmt --check`, `vp lint`, and
Vitest (`metallib-select.test.ts`, `payload.test.ts` — 103 passed) all
green.

## Notes / Out-of-scope items from review

- **SSD persistent prefix identity** (`dflash2_state/disk.rs`):
intentionally left unchanged (consistent with PR #412's INT8 NAX
prefill) so upgrades don't invalidate users' existing SSD prefix caches.
- **`kquant_golden_gate` digests**: pre-existing stale since PR #219
(2026-10-14; gather/dequantize and non-split-K cases already differ on
`main`), left untouched to avoid mixing unrelated digest churn into this
PR.

Refs #201
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.

1 participant