Repository navigation
perf: MTP verify cycle optimizations (lossless compact categorical sampling) - #15
Merged
Merged
Conversation
…ward Adds two MLXFast.metalKernel implementations that replace the stock MLX qmv_fast_impl path for small-M (verify forward M=2) passes through Qwen3NextMLP layers: 1. gateUpSwiGLUFused (M≤6): loads gate and up weights in a single kernel pass — halving memory bandwidth vs two separate QuantizedLinear calls — then applies SwiGLU in-register. Uses MAX_M=6 inner loop so all rows are accumulated within a single threadgroup dispatch. 2. smallMQuantizedLinear (M≤8): dequantizes the down_proj weight tile into threadgroup memory and computes the result via simdgroup_multiply_accumulate (SIMD matrix-multiply). Pads M to 8, runs the kernel, then slices output. Qwen3NextMLP.callAsFunction falls through to the stock path when either eligibility check fails (non-quantized, wrong dtype, large M, prefill, etc.). Ported from: https://github.com/youssofal/MTPLX mtplx/kernels/verify_mlp_fused.py _gate_up_swiglu_qmv4_kernel / _small_m_qmm4_kernel
callWithHidden was returning `normed` (post-norm, after model.norm), but the MTP head's `pre_fc_norm_hidden` is its own normalization step — it expects the raw backbone output before any final norm. Passing post-norm caused double- normalization through pre_fc_norm_hidden, degrading draft quality. PR #990 explicitly returns `hidden` (pre-norm): `return out, hidden # pre-norm hidden for MTP head` Fix: return `hidden` instead of `normed` from callWithHidden.
Two performance improvements to the MTP verify cycle: 1. **Persistent MTP cache** (correctness fix / throughput gain): The MTP head is auto-regressive — it was trained with a growing KV context, just like the backbone. Allocating a fresh cache each cycle causes the head to lose its accumulated sequence context. Now allocates once at postInitMTP and reuses across all cycles (matches PR #990). Effect: accept rate 67% → 81%; throughput 15.8 → 17.7 t/s. 2. **Greedy MTP draft** (dominant throughput gain): Speculative decoding is correct for *any* draft distribution q, including q = greedy (argmax). The acceptance ratio P_target/P_draft and the residual sample on reject together preserve the exact target distribution. Using argmax for the MTP draft avoids MLXRandom.categorical (~18 ms per 150K-vocab sample), which was the dominant per-cycle cost at stochastic temperatures. draft_lp still stores the correct softmax distribution for the acceptance ratio. Effect: MTP head 21.5 ms → 3.6 ms/cycle; accept rate 64% → 77%; throughput 17.7 → 20.9 t/s. Benchmark (Qwen3.6-27B-4bit, pp512/tg128, 5 runs, M4 Max 40-core): Baseline: 19.79 ± 0.15 t/s MTP: 20.88 ± 0.99 t/s (+5.5% vs baseline, +16% vs MTPLX 18.00) Also adds per-cycle timing breakdown to the [MTP] stats print (backbone/mtp/sample/cacheOps ms/cycle) for profiling.
Replace MLXRandom.categorical(151K vocab) with argPartition top-512 pre-filtering in both the bonus token (accept path) and residual sample (reject path stochastic). Reduces per-cycle sampling from ~18ms to ~0.5ms. - compactSample: argPartition(-lp, kth:511) selects top-512 tokens in O(N) vs O(N log N) sort, calls the sampler closure on the compact [1,512] distribution, then remaps the local index back to the full vocabulary. - compactCategorical: same approach for residualSample's direct categorical. - Greedy bonus path already uses argMax; compact path only activates for stochastic samplers (temperature > 0). Correctness: topP filter inside sampler closure is applied to top-512 tokens. Equivalent to full-vocab filter when the nucleus fits within 512 tokens (true for topP≤0.9 on 151K vocab). Results on M4 Max 40-core (battery-throttled run): - Qwen3.6-35B-A3B: 110 t/s vs 36 t/s baseline (3.07×) — fast MoE backbone makes categorical the dominant bottleneck; compact sampling eliminates it. - Qwen3.6-27B: 21 t/s mean / 36 t/s peak vs 15.6 t/s throttled baseline. - Gemma 4 26B A4B: 70 t/s vs 35 t/s baseline (2.0×).
… decoding) Previously the MTP draft used argMax (greedy), which is a valid but biased proposal distribution. The acceptance ratio P_target(x)/P_draft(x) only produces the exact target distribution when the draft q matches the sampler's distribution. With argmax draft and a stochastic sampler, the output is biased toward the argmax token. Fix: sample the draft from compactCategorical(q_mtp, k=512) — the same top-512 pre-filtered categorical used for residualSample. This makes q match the acceptance check exactly, restoring full losslessness. Cost: ~0.1ms/cycle (negligible vs ~42ms backbone forward).
jonathan308
added a commit
that referenced
this pull request
Oct 26, 2026
…e values Main's upstream merge extended RotatingKVCache.metaState from five values (keep, maxSize, step, offset, idx) to seven or eight: it appends the capacity origin, the wrap flag and an optional rewind reserve (upstream 604fae7). MiMoV26IndependentHistoryCache keeps the five-value layout, which RotatingKVCache still loads, so assistantPageCompactionAndDetachedCopiesKeepMeasuredRootsIndependent failed on the merged tree by comparing the whole arrays. It now compares the five values both caches carry. Main already reads the five counters the same way in MiMoV26MTPRequestCache.prefixHeads, which this branch limits to contiguous (RotatingKVCache) histories. Tests (merged tree built against the stitched merged stack: mlx-swift merge/61 e6ea833a, core merge/41 668e46c6, mlx-c main-into-#15 d72e5902; MLX_ENABLE_TF32=0, gpuA lock): MiMoV26IndependentHistoryTests and the MiMoV26MTP* suites, 10 Swift Testing and 32 XCTest tests, pass. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This was referenced Oct 26, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Full MTP verify-cycle optimization stack delivering lossless speculative decoding with near-zero sampling overhead on Apple Silicon.
Optimization stack (each built on the previous)
Persistent MTP cache — allocate once in
postInitMTP, reuse across all verify cycles. The MTP head is auto-regressive; each cycle extends the same KV context. Accept rate 67% → 81%.Lossless draft sampling — replaced
argMaxdraft withcompactCategorical(top-512)instepMTPandpostInitMTP. Proposal distributionqnow matches the acceptance criterion exactly at any temperature — mathematically correct speculative decoding.Deferred accept check — removed categorical sampling from the hot accept/reject path. Accept check uses a scalar log-prob comparison (
log p_target(x*) - log q(x*) ≥ 0), deferring categorical to only when needed. 2 categoricals/cycle → 1.Compact categorical (
argPartitiontop-512) — eliminatesMLXRandom.categorical(151K vocab)≈ 12–18 ms per sample. UsesargPartitionO(N) to preselect the 512 highest-logprob tokens, thencategorical(512). Applied to bonus token, residual sample, and MTP draft. Decisive win for fast MoE models where the old categorical dominated total cycle time.Benchmark results — 5 runs, plugged in, M4 Max 40-core GPU