Skip to content

Improve Qwen3.5 recurrent cache handling - #323

Merged
davidkoski merged 1 commit into
ml-explore:mainfrom
aleroot:qwen3_5perf
Jun 16, 2026
Merged

davidkoski merged 1 commit into
ml-explore:mainfrom
aleroot:qwen3_5perf

Conversation

@aleroot

@aleroot aleroot commented May 30, 2026

Copy link
Copy Markdown
Contributor

Proposed changes

Qwen3.6 models using model_type: qwen3_5 rely heavily on hybrid linear-attention / GatedDelta layers. Keeping the convolution state contiguous avoids carrying strided slices through decode steps, which should reduce per-token cache overhead and better match upstream MLX Python behavior.

Advancing array-cache metadata and preserving left-padding masks also improves stability for padded or batched generation paths.

Checklist

Put an x in the boxes that apply.

  • I have read the CONTRIBUTING document
  • I have run pre-commit run --all-files to format my code / installed pre-commit prior to committing changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the necessary documentation (if needed)

Comment thread Libraries/MLXLMCommon/KVCache.swift Resolved
Comment thread Libraries/MLXLLM/Models/Qwen35.swift Resolved
@aleroot
aleroot force-pushed the qwen3_5perf branch 2 times, most recently from d2c2851 to c34d2d9 Compare June 1, 2026 19:53
@aleroot
aleroot force-pushed the qwen3_5perf branch 2 times, most recently from fd40a0e to 3eee371 Compare June 12, 2026 11:43
@aleroot

aleroot commented Jun 12, 2026

Copy link
Copy Markdown
Contributor Author

Updated rebasing on latest main , also fixed a MTP tail-budget issue by making speculative rounds budget-aware: the iterator now only drafts when the remaining output budget can hold both the accepted draft prefix and the verifier correction/bonus.

Comment thread Libraries/MLXLMCommon/KVCache.swift Resolved

@davidkoski davidkoski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Looks good. See what you think about my question on KVCache finalize.

@aleroot
aleroot force-pushed the qwen3_5perf branch 2 times, most recently from f082c5d to eb4408f Compare June 16, 2026 04:26
Store GatedDelta convolution state contiguously and advance array-cache metadata after each recurrent step, matching upstream mlx-lm behavior for Qwen3.5/Qwen3-Next style models.

Keep left-padding masks active after recurrent cache state initialization, add coverage for ArraysCache metadata advancement, and align Qwen3 RoPE setup with the shared rope initializer.
@aleroot

aleroot commented Jun 16, 2026

Copy link
Copy Markdown
Contributor Author

Had to fix the the CI failure which was coming from SpeculativeDecodingTests, specifically speculative generation diverging from normal generation.

There were two issues:

  1. The parameterized Swift Testing cases were running concurrently, while this suite uses shared MLX/model generation state. I marked the suite .serialized so the cases run one at a time.

  2. The repetition/presence penalty processors were mutating logits via indexed assignment. In the speculative verification path those logits can be views into a larger multi-token logits tensor, so that could affect later verification positions. I changed those processors to return out-of-place adjusted logits using takeAlong/putAlong.

@davidkoski davidkoski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Looks good, thank you!

@davidkoski
davidkoski merged commit f37305a into ml-explore:main Jun 16, 2026
2 checks passed
dkgv pushed a commit to dkgv/mlx-swift-lm that referenced this pull request Jul 30, 2026
Store GatedDelta convolution state contiguously and advance array-cache metadata after each recurrent step, matching upstream mlx-lm behavior for Qwen3.5/Qwen3-Next style models.

Keep left-padding masks active after recurrent cache state initialization, add coverage for ArraysCache metadata advancement, and align Qwen3 RoPE setup with the shared rope initializer.
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
… prefill kernels on M5 (onto main) (ml-explore#323)

* perf(nemotron-super): fuse the MTP verify window and draft head; submit the window in parts

Speculative decode rounds, with tokens and logits unchanged:

- The row-exact trunk (MTP verify windows, batched decode) is submitted to
  the GPU every 12 blocks (NemotronSuperMTPWindowSubmission.everyLayers;
  DARKBLOOM_NEMOTRON_SUPER_MTP_WINDOW_SUBMIT, 0 builds it whole), so the GPU
  runs while the rest of the graph is built. Evaluation order only.
- The trunk and the MTP head use Super's fused kernels exactly where the
  target's one-token decode uses them (residual-add + next-norm boundary,
  Mamba gated norm, one-token SSM step, expert combine, squared ReLU fused
  into the shared-expert products, the head's fused expert selection with
  in-range router indices). Each works row by row behind its supports guard,
  so every row reproduces one-token decode by construction
  (NemotronSuperMTPFusion.enabled; DARKBLOOM_NEMOTRON_SUPER_MTP_FUSION=0
  restores the op chains).

M5 Ultra, full checkpoint, 26 A/B prompts greedy: token-identical; realistic
decode (code, chat, math, reasoning) median 70.5 -> 79.4 tok/s, the counting
benchmark 87.7 -> 102.0 tok/s, the whole set 92.3 -> 82.8 s. Window
submission alone gives +10%, fusion +1-2%.

Tests compare fused and unfused trunks and heads bit for bit (logits, hidden,
committed state), including submission after every layer.

* perf(modelopt): use MLX's NAX expert products for NVFP4 prefill on NAX GPUs

The simdgroup grouped GEMM was tuned on an M3 Ultra; on NAX GPUs (M5 and
later) MLX's sorted NAX gather product is faster. Nemotron 3.5 Super prefill
on an M5 Ultra: 1,556 -> 2,100 tokens/s on a 12K prompt.

The two paths sum in different orders, so this is not bit-identical. Scored
teacher-forced against the true next token over 46,070 positions, the NAX
path is at least as accurate: top-1 78.16% vs 78.12%, perplexity 2.7238 vs
2.7294. Any change in summation order (TF32 on or off as well) agrees with
the other path on ~96% of positions; at the 1,789 positions where these two
disagree, the NAX path is right 388 times and the grouped GEMM 371.
Non-NAX GPUs keep the grouped GEMM.

* style(nemotron-super): swift-format NemotronH35MTPModule

* docs(nemotron-super): NAX expert prefill default and its accuracy check

* perf(modelopt): NAX NVFP4 expert kernels, fused expert route and NAX dense projections

Prefill on NAX GPUs (M5 and later), bit-identical to the MLX products they
replace:

- ModelOptNVFP4NAXExperts: a dedicated NVFP4 expert GEMM adapted from the
  GLM prefill kernel (double-buffered weight tiles decoded eight codes per
  word, one tile-scan launch, empty fragments skipped, expert scale and relu2
  in the epilogue), with the fastest measured plan per projection pinned.
  It issues MLX's sorted NAX gather's tensor ops in the same order.
- fusedRoute: one route launch replaces the argsorts, gathers and scans; fc1
  reads the latent rows through the sort order; fc1's epilogue does fc2's
  NVFP4 activation rounding; the combine reads through the inverse order.
- ModelOptNAXDenseLinear: FP8 and NVFP4 dense prefill projections decode
  their weights inside the NAX GEMM instead of writing a BF16 weight copy
  per call (FP8) or float32 sums and a separate scale pass (NVFP4); taken
  only where MLX runs its regular NAX kernel, never for decode rows.

M5 Ultra, full checkpoint: 12K-token prefill 2,094 -> 2,255 tokens/s with
the expert kernel, 2,471 with the fused route and dense projections; greedy
outputs identical on 26 A/B prompts and the teacher-forced score identical
at all 46,070 positions. Per MoE layer at a 2,048-token chunk the expert
block takes 6.47 instead of 8.85 ms.

* perf(nemotron-super): chunked NAX SSD and fused conv for Mamba prefill on M5

Mamba-2 prefill chunks on NAX GPUs run a chunked SSD kernel: one
threadgroup per head walks the prompt in 32-token chunks with the head's
float32 state resident in registers (as the GLM 5.3 recurrent prefill
kernels keep each core's state), and the intra-chunk C.B^T with the decay
mask, the intra-chunk and carried-state outputs and the state update run as
NAX tensor ops with float32 operands and accumulation. One kernel does the
conv-state concatenation, depthwise conv, bias, silu and retained state
(bit-identical to the op chain); dt is computed inside the SSD.
NemotronSuperMambaPrefill.enabled (on by default on NAX GPUs) restores the
previous path when cleared.

Not bit-identical. M5 Ultra, full checkpoint: one layer at 2,048 tokens
11.3 -> 8.0 ms (SSD 6.1 -> 1.9 ms); 12K-token prefill 2,471 -> 2,881
tokens/s. Teacher-forced over 46,070 positions: top-1 78.09%, perplexity
2.7275, against 78.12% / 2.7294 for the grouped GEMM build (the accuracy
gate's baseline) and 78.16% / 2.7238 for the bit-identical NAX expert
build; the perplexity difference is even across positions.

* fix(nemotron-super): use the runtime-compiled NAX kernels on macOS 27 only

The NAX expert kernels and fused route, the NAX dense projections and the
chunked SSD compile at first use with the OS's Metal compiler. macOS 26's
compiler rejects some of these tensor-op kernels ("unsupported
deferred-static-alloca-size" in the chunked SSD on the CI runner), which MLX
reports as a fatal error. They were validated on macOS 27 (M5 Ultra 27.0.1,
M5 Max 27.0, M3 Ultra 27.2): ModelOptNVFP4NAXExperts.runtimeCompilerSupported
gates their defaults and tests, so earlier systems keep MLX's prebuilt NAX
kernels and every decode change.

---------

Co-authored-by: Jonathan Spangler <5055076+jonathan308@users.noreply.github.com>
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