Repository navigation
Description
Summary
Wire Qwen3.8-Flash-Next's native MTP head (mtp.*, one Qwen Sparse Attention decoder layer plus its own MoE) as a qwen4_exp_mtp drafter, and give qwen4_exp the speculative verify/rollback hooks it currently lacks. The same rollback hooks also unlock prompt lookup (--draft-kind prompt-lookup) for this family, which today declines because the model owns its sequence state and nothing in it can be trimmed.
This is the largest single decode lever measured for this model on Apple Silicon by another engine, and mlxcel already has every surrounding piece (the MtpTarget round loop, the Qwen 3.5 MTP adapter, the adaptive per-hardware MTP policy). What is missing is the family-specific drafter and the target adapter.
Motivation and evidence
mlxcel's own qualification (docs/benchmark_results/qwen4-exp-m3-ultra-2026-10-23.md, OptiQ 2-bit, M3 Ultra) measures 41.39 tok/s decode at 128 prompt tokens and 37.77 tok/s at 4,608, with MTP not wired.
Strata (MIT, https://github.com/Niko1221/Strata, read at commit 146df3c, v0.1.58) runs the same model on its own Metal engine. docs/MAC.md, M5 Max 128 GB, greedy, 200 tokens, decode tok/s for a short question / a story:
| Strata Metal engine | Q2_0 | IQ3_XXS | IQ3_S |
|---|---|---|---|
| No MTP (one token per step) | 87.4 / 87.3 | 78.7 / 78.6 | 74.5 / 74.3 |
--spec 2 with MTP |
114.0 / 107.9 | 103.5 / 96.9 | 98.2 / 94.1 |
--spec 2 with MTP + suffix (prompt-lookup) drafter |
119.5 / 108.2 | 108.9 / 97.0 | - |
That is +24% to +31% from MTP alone on that machine, with output identical token for token (the full model verifies every draft). Their CUDA engine reports 2.4-3.2 accepted tokens per verify pass with up to 3 drafts (docs/HOW_IT_WORKS.md).
These numbers are not a prediction for mlxcel: different chip, different quantization, different kernels. They are the reason to build the path and measure it. Note that mlxcel's Qwen 3.5 MTP measures 0.59-0.70x classic decode on M1 Ultra (docs/supported-models.md, MTP row), so the adaptive policy must stay the gate, not a default flip.
Upstream reference
- mlx-vlm drafter (read at
a54f1a0):mlx_vlm/speculative/drafters/qwen4_exp_mtp/(qwen4_exp_mtp.py,config.py,split.py), introduced in Add MTP support for Qwen3.8-Flash-Next Neywa-Labs/mlx-vlm#2040; adaptive policy in perf(qwen3.8): adapt MTP draft depth Neywa-Labs/mlx-vlm#2046. - Target side:
mlx_vlm/models/qwen4_exp/language.py,LanguageModel.__call__(return_hidden),_mtp_logits_hidden,speculative_draft_hidden, andQwen4ExpModel.__call__around thecapture_layer_ids == []branch.
Key contract details from the reference that differ from Qwen 3.5's MTP:
- The drafter consumes the full hyper-connection state, before the final mixer. The target hands over
[B, L, hc_count * hidden_size](hc_count = 4), captured beforehyper_connection_mixer. Qwen 3.5's adapter hands over the post-final-norm hidden (qwen3_5_mtp_target.rs, "Hidden-state semantics"). Reusing that path silently gives the drafter the wrong input. - Input fusion.
pre_fc_norm_embedding(zero-centered RMSNorm overhidden_size) on the token embedding,pre_fc_norm_hiddenas one global RMSNorm over allhc_count * hidden_sizevalues, thenfc_embeddingandfc_hidden(bothhidden_size -> hidden_size, no bias) applied per stream, summed with broadcasting over the stream axis, reshaped back to[B, L, hc_count * hidden_size]. - One decoder layer built from the target config with
num_hidden_layers = 1,layer_types = ["qwen_sparse_attention"],full_attention_interval = 1,ple_layer_ids = [](no n-gram embedding in the head), with its ownQSAKVCache. - Output. The layer output goes through the drafter's own
hyper_connection_mixer(no inject), then the target's final norm andlm_head.speculative_logits_from_hiddencollapses a 4-stream hidden through the target mixer when it receives one. - Sanitize. Strip
language_model.mtp./model.mtp./mtp.; split a fusedlayers.0.mlp.experts.gate_up_proj(and.scales/.biases) along axis -2 intoswitch_mlp.{gate,up}_projand movedown_projalongside.layers.0.mlp.gate.weight(the router) is not quantized. - Runtime block size.
default_runtime_block_size = 4(three drafts),prefer_requested_block_size = False. - Splitting.
split.py(Qwen4ExpMTPSplitter) extracts the head from a full checkpoint, including FP8 sources throughconvert_qwen4_exp_fp8_weights. MLX target conversions dropmtp.*, so the drafter is a separate directory, as for Qwen 3.5.
Current mlxcel state
src/models/qwen4_exp_sanitize.rslines 92-99 drop everymtp./model.mtp.key.src/models/qwen4_exp.rslines 31-33 list MTP as out of scope.docs/supported-models.mdline 114: "Not wired: MTP (mtp.*tensors are dropped), DFlash, ...".- MTP infrastructure that should be reused rather than duplicated:
MtpTargettrait:src/lib/mlxcel-core/src/speculative/mtp/target.rs:230.- Qwen 3.5 target adapter, the closest template:
src/models/qwen3_5_mtp_target.rs(B = 1, sequence-routed*_for_sequencewrappers so the adapter stays a stateless view, rebuilt every scheduler tick). - Qwen 3.5 drafter model:
src/lib/mlxcel-core/src/drafter/qwen3_5_mtp/(model.rs,layer.rs,config.rs); loader dispatch by draftermodel_typeinsrc/models/drafter_loader.rs. - Speculative hooks on the Qwen 3.5 model:
forward_speculative(src/models/qwen3_5.rs:2503),rollback_speculative_cache(:2756), and the sequence-routed variants (:3163,:3179). - Adaptive policy and its endpoint:
src/server/batch/mtp_policy.rs,docs/mtp-policy-api.md.
- Prompt lookup declines today:
Engine::verify_rounds_unsupported(src/lib/mlxcel-core/src/engine/verify_round.rs:110) requires trimmable pool caches, andqwen4_expisSequenceStateLayout::model_ownedwith no rollback.
Proposed solution
Part A: speculative rollback on the target (prerequisite for both MTP and prompt lookup)
A rejected draft has to be unwound from every piece of per-sequence state qwen4_exp owns (Qwen4ExpCache in src/models/qwen4_exp.rs:79):
| State | Can it be trimmed? | Rollback strategy |
|---|---|---|
Attention KVCache |
yes | trim by the rejected count, as Qwen 3.5 does |
QsaIndexCache.raw_keys, .positions |
yes (per token) | trim by the rejected count |
QsaIndexCache.block_keys (pooled 4-token blocks) |
only whole blocks | drop blocks that are no longer complete after the trim; recompute a block that became complete again from raw_keys |
| GatedDeltaNet recurrent and conv state | no | capture the verify block's q/k/v/a/b and initial state, then replay the accepted prefix, as Qwen 3.5's GdnRollbackSnapshot does (rollback_speculative_cache, qwen3_5.rs:2756) |
PleCache.conv_state (dilated depthwise conv window) |
no | keep the window from before the verify block and re-advance it over the accepted tokens (the window is small: ple_conv_kernel_size x dilation ngram_size) |
PleCache.contexts (last ngram_size - 1 tokens, EOS reset) |
yes (host-side) | truncate the token history and recompute the tail, including an EOS that was drafted and then rejected |
Port the Qwen 3.5 approach (forward_speculative returning what rollback_speculative_cache needs) and add the two extra pieces (index blocks, PLE). Expose *_for_sequence wrappers like qwen3_5.rs:3163/3179 so the adapter stays stateless.
Part B: qwen4_exp_mtp drafter
- New
src/lib/mlxcel-core/src/drafter/qwen4_exp_mtp/(config, layer, model), mirroringqwen3_5_mtp/. Reuse the qwen4_exp QSA layer, MoE block, zero-centered norm and hyper-connection mixer rather than reimplementing them. If they are crate-private tosrc/models, move the shared pieces where both sides can reach them instead of copying. - Config validation:
model_typemust beqwen4_exp_mtp;hc_countmust match the target (mlx-vlmvalidate_target_compatibility); rejectmtp_num_hidden_layers != 1with a named error until a multi-layer head exists. - Detection in
drafter_loader.rsbymodel_type, the same auto-detection path the Qwen 3.5 drafter uses (no--draft-kindneeded).
Part C: target adapter
src/models/qwen4_exp_mtp_target.rsimplementingMtpTargetforQwen4ExpModeland its VLM wrapper, followingqwen3_5_mtp_target.rs.- Hidden capture: capture the pre-mixer
[B, L, hc_count * hidden_size]state (contract item 1 above) for the seed, every round'snext_hiddenandverify_hidden_full. - B = 1, text-only requests first; image and video requests decline to classic decode with the existing named reason, as for Qwen 3.5.
Part D: Mac-specific choices to evaluate
From Strata's Metal engine (docs/MAC.md, "Defaults and options" and "Switches"):
- Window size.
--spec 2beat--spec 3on mixed text on M5 Max (Q2_0 story 106 vs 92 tok/s), while--spec 3won on code and JSON. Expose the block size through the existing flags and let the adaptive policy measure; do not hard-code 4 from the Python default. - Drafter weight width. Strata keeps the draft layer's matrices in Q8_0 by default (
STRATA_METAL_MTP_Q8). Check the published MLX drafter conversions (bf16, 8-bit, 4-bit) for acceptance rate against cost. - One submission per draft round. Strata runs a whole draft round in one command buffer (
STRATA_METAL_MTP_CHAIN). In MLX terms: build the K autoregressive draft steps lazily and evaluate once per round where the sampler allows it, instead of oneevalper draft token. - Memory-constrained Macs. On a 32 GB Mac that streams experts, Strata turns MTP off because the draft layer's memory is worth more as expert cache. If SSD expert streaming lands (feat(moe): SSD expert streaming arena for MoE checkpoints larger than unified memory #2882), the MTP default should account for it.
- CJK draft vocabulary. Strata v0.1.27 found its draft-vocabulary subset held 27 of the 55,328 Chinese-character tokens, so Chinese answers got almost no drafts. Adding all CJK tokens made Chinese answers 15-38% faster and cost English 1-2%. mlxcel's drafter uses the full
lm_head, so this does not apply as-is, but any future vocabulary pruning of the draft head must keep Korean, Japanese and Chinese tokens. Include a Korean or Chinese prompt in the acceptance benchmark.
Scope
In scope: rollback hooks on qwen4_exp; the qwen4_exp_mtp drafter; the target adapter; prompt lookup for this family; CLI and server, B = 1, text-only, Metal.
Out of scope (follow-ups): B > 1 MTP windows, MTP with image or video requests, DFlash for this family, a vocabulary-pruned draft head.
Acceptance criteria
- Rollback unit tests on a tiny
qwen4_expfixture (one PLE layer, one QSA layer, MoE): for every state in the table above, verify K tokens, roll back R, then decode, and match the logits of a run that never saw the rejected tokens. Cover a rejection that crosses a 4-token QSA block boundary, one that crosses the 2051/2052-token dense/sparse switch, and a rejected EOS that would have reset the n-gram context. - Drafter fixture parity against mlx-vlm's
Qwen4ExpMTPDraftModel(fuse_inputsoutput, one forward, logits) with tiny random weights, including the 4-stream hidden contract; a negative test shows that feeding the post-mixer hidden fails the comparison. - Sanitize test: fused
gate_up_projwith.scales/.biasessplits exactly as upstream; router stays unquantized. - Temperature 0:
mlxcel generatewith the drafter produces byte-identical output to classic decode on at least three prompts (English prose, code, a Korean or Chinese prompt), 256 tokens each, on the OptiQ 2-bit target. -
mlxcel generate --prompt-lookupandmlxcel-server --draft-kind prompt-lookupno longer decline forqwen4_exp, and are byte-identical to classic decode at temperature 0. - Paired five-run benchmark on the same machine as the 2026-10-23 report (decode tok/s and acceptance rate, classic vs MTP at block sizes 2, 3 and 4, plus prompt lookup on a file-rewrite prompt), recorded under
docs/benchmark_results/. The adaptive policy reports a verdict through/v1/internal/mtp-policy. -
docs/supported-models.mdrow and the MTP table row updated, with how to obtain or split the drafter.
Verification
cargo build --release --features metal,accelerate
cargo test --workspace --profile test-fast --features metal,accelerate
cargo clippy --workspace --all-targets -- -D warnings
cargo fmt --check
./target/release/mlxcel generate -m models/Qwen3.8-Flash-Next-OptiQ-2bit \
--draft-model models/Qwen3.8-Flash-Next-MTP -p "Write a quicksort in Rust." -n 256 --temp 0
./target/release/mlxcel generate -m models/Qwen3.8-Flash-Next-OptiQ-2bit --prompt-lookup \
-p "<file rewrite prompt>" -n 256 --temp 0
Activity
fix(speculative): keep verify rewind opt-in and gate CLI lookup on Metal
fix(qwen4_exp): prefill the MTP target in classic chunks
fix(qwen4_exp): honor the server chunk and bound MTP rollback state
fix(qwen4_exp): decline an empty offline MTP prompt and finish docs
feat(speculative): wire the native MTP head and rollback for qwen4_exp
fix(speculative): keep verify rewind opt-in and gate CLI lookup on Metal
fix(qwen4_exp): prefill the MTP target in classic chunks
fix(qwen4_exp): honor the server chunk and bound MTP rollback state
fix(qwen4_exp): decline an empty offline MTP prompt and finish docs
feat(speculative): wire the native MTP head and rollback for qwen4_exp (
docs(bench): record deferred qwen4_exp measurements on M3 Ultra (#2926)