Skip to content

feat(speculative): wire the native MTP head and speculative rollback for qwen4_exp (Qwen3.8-Flash-Next) #2880

Closed

Description

@inureyes

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

Key contract details from the reference that differ from Qwen 3.5's MTP:

  1. 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 before hyper_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.
  2. Input fusion. pre_fc_norm_embedding (zero-centered RMSNorm over hidden_size) on the token embedding, pre_fc_norm_hidden as one global RMSNorm over all hc_count * hidden_size values, then fc_embedding and fc_hidden (both hidden_size -> hidden_size, no bias) applied per stream, summed with broadcasting over the stream axis, reshaped back to [B, L, hc_count * hidden_size].
  3. 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 own QSAKVCache.
  4. Output. The layer output goes through the drafter's own hyper_connection_mixer (no inject), then the target's final norm and lm_head. speculative_logits_from_hidden collapses a 4-stream hidden through the target mixer when it receives one.
  5. Sanitize. Strip language_model.mtp. / model.mtp. / mtp.; split a fused layers.0.mlp.experts.gate_up_proj (and .scales / .biases) along axis -2 into switch_mlp.{gate,up}_proj and move down_proj alongside. layers.0.mlp.gate.weight (the router) is not quantized.
  6. Runtime block size. default_runtime_block_size = 4 (three drafts), prefer_requested_block_size = False.
  7. Splitting. split.py (Qwen4ExpMTPSplitter) extracts the head from a full checkpoint, including FP8 sources through convert_qwen4_exp_fp8_weights. MLX target conversions drop mtp.*, so the drafter is a separate directory, as for Qwen 3.5.

Current mlxcel state

  • src/models/qwen4_exp_sanitize.rs lines 92-99 drop every mtp. / model.mtp. key. src/models/qwen4_exp.rs lines 31-33 list MTP as out of scope.
  • docs/supported-models.md line 114: "Not wired: MTP (mtp.* tensors are dropped), DFlash, ...".
  • MTP infrastructure that should be reused rather than duplicated:
    • MtpTarget trait: 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_sequence wrappers 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 drafter model_type in src/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, and qwen4_exp is SequenceStateLayout::model_owned with 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), mirroring qwen3_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 to src/models, move the shared pieces where both sides can reach them instead of copying.
  • Config validation: model_type must be qwen4_exp_mtp; hc_count must match the target (mlx-vlm validate_target_compatibility); reject mtp_num_hidden_layers != 1 with a named error until a multi-layer head exists.
  • Detection in drafter_loader.rs by model_type, the same auto-detection path the Qwen 3.5 drafter uses (no --draft-kind needed).

Part C: target adapter

  • src/models/qwen4_exp_mtp_target.rs implementing MtpTarget for Qwen4ExpModel and its VLM wrapper, following qwen3_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's next_hidden and verify_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 2 beat --spec 3 on mixed text on M5 Max (Q2_0 story 106 vs 92 tok/s), while --spec 3 won 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 one eval per 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_exp fixture (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_inputs output, 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_proj with .scales / .biases splits exactly as upstream; router stays unquantized.
  • Temperature 0: mlxcel generate with 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-lookup and mlxcel-server --draft-kind prompt-lookup no longer decline for qwen4_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.md row 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

  1. added
    status:ready
    type:enhancement
    type:performance
    priority:medium
    area:models
    area:inference
    platform:macos
    modelsize:xlarge
    modeltype:vlm
    arch:hybrid
    status:in-progress
    status:review
    and removed
    status:ready
    status:in-progress
    on Nov 8, 2026
  2. added
    status:done
    and removed
    status:review
    on Nov 9, 2026
  3. added 5 commits that reference this issue on Nov 9, 2026
    97c970d
    0bf48ac
    396770d
    fd5c888
    274dc16
  4. added 2 commits that reference this issue on Nov 9, 2026
    a75eb1c
    69cb500
  5. added this to the 0.9 milestone on Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    arch:hybridarea:inferencearea:modelsmodelsize:xlargemodeltype:vlmplatform:macospriority:mediumstatus:donetype:enhancementtype:performance

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions