Repository navigation
feat(speculative): wire the native MTP head and rollback for qwen4_exp - #2908
Conversation
Implementation Review SummaryIntent
Findings Addressed
Remaining Items
Verification
Long-context check on the real target (about 4000 prompt tokens, 128 tokens, temperature 0): classic, |
Security and performance reviewFindings addressed (HIGH, all in
|
Qwen3.8-Flash-Next (`qwen4_exp`) owned every piece of its per-sequence state, so a rejected speculative block could not be unwound: its native MTP head stayed unwired and prompt lookup declined the family. Rollback (`qwen4_exp_rollback`, separate from `Qwen4ExpCache` so #2885 can add prompt-cache snapshots): a speculative forward captures per layer, and the rollback trims the KV cache and QSA index (summaries of blocks no longer complete are dropped and recomputed lazily), replays the GatedDeltaNet recurrence and both convolution windows over the accepted prefix, and recomputes the PLE n-gram context from the accepted tokens so a drafted and rejected EOS never resets it. A per-sequence log of recent speculative forwards backs `rewind_decode_appends` for the engine's prompt-lookup rounds. The verify block runs in a decode-equivalent form (one query per QSA attention call, convolutions one row at a time, the fused GatedDeltaNet projection, dense gate projections row by row, unsorted expert gathers), so a `T = K` block is byte-identical to `K` single steps; the exactness probe gates MTP and, new here, prompt lookup for this family. The `qwen4_exp_mtp` drafter reuses the target's QSA layer, MoE block and mixer and consumes the pre-mixer `[1, L, hc_count * hidden]` streams; core registers its `model_type`, `drafter_loader` builds it, and the adapter is wired through the CLI, burst, slice, scheduler and bench. `LanguageModel::supports_speculative_verify_rewind` admits a model-owned family that rewinds its own verify tail. Validated on the tiny fixture (rollback per component, quantized block-versus-chain probe at widths 2, 4, 8, drafter parity against mlx-vlm) and on the real OptiQ 2-bit target with the `sh0wie/Qwen3.8-Flash-Next-MTP-Drafter-MLX-bf16` head. Closes #2880
The verify-rewind capability defaulted to the decode lookahead flag, which newly admitted Gemma 3 and Baichuan to prompt lookup. Their rewinds pop whole single-token forwards or overwritten rows, so they cannot stop inside a multi-token verify block and would restore the wrong state or fail. The capability now defaults to false and only qwen4_exp opts in. `mlxcel generate --prompt-lookup` skipped the qwen4_exp exactness gate on non-Metal backends, where block and chain arithmetic disagree. It now refuses by name, matching the server and the MTP path. Refs #2880. Narrow qwen4_exp, drafter loader, lookahead and prompt-lookup tests, clippy and fmt pass.
The MTP prefill forwarded the whole prompt in one call while classic decode forwards the 2048-token pieces of the prefill plan. On prompts past the chunk size the two reach different state, so temperature-0 MTP output drifted from classic within about 30 tokens on a 4000-token prompt. A one-shot classic run reproduced the MTP stream exactly, which isolated the cause to the prefill. The target now follows the classic plan and hands the drafter the concatenated streams. A long-prompt and a short-prompt MTP run match classic decode byte for byte on the OptiQ 2-bit target. Refs #2880.
The server's configured `prefill_chunk_size` never reached the MTP prefill, which used the process default, so a non-default setting reintroduced the long-prompt divergence from classic decode. The burst and slice paths now pass it through the adapter, and the prefill runs the plan classic decode builds for that chunk. `RollbackLog` kept four captures per sequence, about 450 MB of recurrent state, while every caller unwinds only inside the forward just before it: verify rounds, the width warm-up and the MTP finalize. Decode lookahead is the one cross-forward caller and this family stays out of it, so the depth is now 1 and a test pins that assumption. A wrong `hc_count` is now refused at bind. Past the bind it surfaced as a draft error, which the MTP loop treats as end of generation, cutting every reply to the seed token. Validated on the OptiQ 2-bit target at temperature 0: CLI MTP and prompt lookup match classic over 96 tokens, and `mlxcel-server --prefill-chunk-size 512` MTP matches classic on a 2028-token prompt. Refs #2880
Offline `mlxcel generate --draft-model` with a zero-token prompt reached the qwen4_exp prefill, whose "a prefill has at least one piece" expectation panics, and the other MTP adapters have no last position to sample from either. `run_offline_mtp` now declines it by name before any drafter IO, covered by a unit test. Docs: the MTP table row in docs/supported-models.md states the rollback depth (1) and that a drafter with a different hc_count is refused by the compatibility check before bind, and drops the single-run acceptance figures. docs/mtp-policy-api.md names how to obtain the drafter (split_qwen4_exp_mtp or sh0wie/Qwen3.8-Flash-Next-MTP-Drafter-MLX-bf16 at be6e2bc3). CHANGELOG gains an Unreleased entry. No Korean counterparts exist for these pages. Validation: - cargo test --profile test-fast --features metal,accelerate --bin mlxcel -- offline_mtp_declines: 1 passed - cargo fmt --check and cargo clippy --lib --tests --bins --features metal,accelerate -- -D warnings: clean Refs #2880
e215139 to
274dc16
Compare
## Summary Records the timing and memory measurements that #2908, #2906, #2912, #2909, #2911 and #2918 deferred to a quiet host, in `docs/benchmark_results/qwen4-exp-deferred-measurements-m3ultra-2026-11-10.md` (Mac Studio M3 Ultra, 512 GB, `main` @ `60a3270c`). - Native MTP (#2880, #2917): 1.30x / 1.10x / 1.76x (code / prose / enumeration) for the OptiQ 2-bit target with the bf16 split head, 1.38x / 1.00x / 1.74x for the 4-bit target with its embedded head. - SSD expert streaming (#2882): decode 42.8 tok/s resident, 23.0 at a 24 GB arena (89.8% hit), 18.3 at 8 GB (74.9% hit). Router sync costs 8.0 s per run at both sizes, more than the I/O wait. Output identical across arms. - External PLE (#2881): 31 GB less resident (78.5 to 47.3 GB), same TTFT at 4K and 32K, identical output in every mode. - Prompt-cache second turn (#2885): 0.51 to 0.60 s cached vs 15.1 s (16K) and 28.6 to 28.9 s (32K) after a reset, byte-identical in 10/10 repetitions. - macOS memory soak (#2883): 0 compressions and 0 swap-outs in every setting. A 512 GB host cannot show the eviction the issue targets. ## Script changes - `scripts/bench_speculative.sh`: new `flashnext` and `flashnext4` pairings. - `scripts/macos_memory_soak.sh`: send the `model` field (every request got HTTP 400 without it), and default `--out` gets a `-wire-weights` suffix under `--wire-weights` so it no longer overwrites the plain run. ## Not covered A Mac with less memory than the checkpoint, the `prepare-expert-stream` contiguous file, and streaming combined with the external PLE table. Refs #2880, #2881, #2882, #2883, #2885, #2917
…ilies (#2942) ## Summary #2920 reported that a classic `mlxcel-server` request on `Qwen3.8-Flash-Next-4bit-mtp` at temperature 0 diverges from `mlxcel generate`. The cause is the history-boundary prompt-cache snapshot (#1143). The batch scheduler prefills the 70-token chat prompt as `prefill[0..65)+prefill[65..70)` so it can snapshot the state at the boundary, while `mlxcel generate -p` has no history boundary and prefills `prefill[0..70)` in one forward. The two partitions reduce in different orders and flip a near-tie token. `CONTINUOUS_BATCHING.md` already states this partition rule, but it never said that it separates the server from `mlxcel generate`, and its "one prefill plan" sentence reads as if the two always match. This PR documents the case with the measurement and names the switch for byte-for-byte comparisons. There are no code changes. ## Evidence (M3 Ultra, `main` @ `0ba1b50b`, `MLXCEL_QMV_WIDE=0`, 256 tokens, temperature 0) | server run | prefill partition | vs `mlxcel generate` | |---|---|---| | defaults, and `--parallel 1` | `[0..65)+[65..70)` | diverges at completion token 98 | | `--no-cache-prompt --prefill-chunk-size 65` | `[0..65)+[65..70)` | byte-identical to the defaults run | | `--no-cache-prompt` | `[0..70)` | identical | | `MLXCEL_DISABLE_BOUNDARY_SNAPSHOT=1` (prompt cache on) | `[0..70)` | identical | | `--no-batch` | `[0..70)` | identical | - At token 98 the one-forward run ties " as" and " when" at logprob -0.875. The split run gives " when" -0.875 over " as" -1.0. - `MLXCEL_PREFILL_CHUNK=65 mlxcel generate` takes the server's partition and produces the server's answer, so the split alone explains the difference, and the snapshot restore plays no part. - The OptiQ 2-bit target behaves the same way: the defaults run diverges at answer character 205 (boundary 65), and `--no-cache-prompt` matches. #2908 compared it on a different setup and saw no difference. - The speculative server matched in the original report because its prefill logged no boundary split. ## Decision This is an expected numeric route difference (outcome (a) in the issue). Removing the split would cost snapshot families their multi-turn prompt-cache hit, and splitting `mlxcel generate` at a boundary it does not have would move the CLI away from upstream `mlx-lm`'s one-pass prefill. ## Changes - `docs/CONTINUOUS_BATCHING.md`: a paragraph and table under "One prefill plan" covering server vs `mlxcel generate` on snapshot families, with the measurement and the two ways to compare byte for byte. - `docs/environment-variables.md`: the `MLXCEL_DISABLE_BOUNDARY_SNAPSHOT` entry names this use and links to that section. Closes #2920
Summary
qwen4_exp(Qwen3.8-Flash-Next) owned every piece of its per-sequence state, so a rejected speculative block could not be unwound: the native MTP head stayed unwired and prompt lookup declined the family. This wires both, following the Qwen 3.5 MTP adapter and the GLM-4.7-Flash binary-crate drafter.src/models/qwen4_exp_rollback.rs, kept apart fromQwen4ExpCachefor feat(models): prompt-cache snapshots for qwen4_exp, then mid-prompt checkpoints for model-owned recurrent families #2885): KV cache and QSA index trimmed (summaries of blocks no longer complete are dropped and recomputed lazily), GatedDeltaNet recurrence and both convolution windows replayed over the accepted prefix, PLE n-gram context recomputed from the accepted tokens so a rejected EOS never resets it. A per-sequence log holding only the newest speculative forward (depth 1; a rewind past it returns an error and leaves state untouched) backsrewind_decode_appendsfor the engine's prompt-lookup rounds.qmv_wide, which the existing gate switches off; prompt lookup on this family now runs that gate too (CLI and server) atmax_draft + 1.qwen4_exp_mtpdrafter reusing the target's QSA layer, MoE block and mixer, fed the pre-mixer[1, L, hc_count * hidden]streams (the post-mixer hidden is refused by name), with upstreamsanitizeand the stateful prefill/draft/accept lifecycle. It lives in the binary crate like the GLM drafter because its layer is the target's own; core registers themodel_type,drafter_loaderbuilds it.Qwen4ExpMtpTargetAdapterand the CLI, burst, slice/scheduler and bench arms forLoadedModel::Qwen4ExpVLM, under the same exactness gate and Metal guard as Qwen 3.5. Block size stays on--draft-block-size(default 4; the drafter'sblock_sizeis the adaptive start depth); the adaptive policy remains the gate and the MTP default is unchanged.LanguageModel::supports_speculative_verify_rewind(defaultfalse, onlyqwen4_expopts in, so no other model-owned family is newly admitted) lets a family that rewinds its own verify tail throughprompt_lookup_unsupported_reasonandEngine::verify_rounds_unsupported; decode lookahead stays off.generate --prompt-lookuprefuses this family by name off Metal, matching the server and the MTP path.PrefillPlan(2048-token chunks by default, the server'sprefill_chunk_sizeon the server paths); a single-call prefill diverged from classic on long prompts. A drafter with a differenthc_countis refused before bind throughLanguageModel::residual_stream_count, andgenerate --draft-modeldeclines an empty prompt by name.supported-models.mdandmtp-policy-api.md, a CHANGELOG entry; the fixture generator gains the drafter case and per-case regeneration (tests/fixtures/qwen4_exp/mtp.json, mlx-vlmabd3b2d7, the local clone revision; the drafter files match the issue'sa54f1a0in substance).Acceptance criteria
Target
mlx-community/Qwen3.8-Flash-Next-OptiQ-2bit, draftersh0wie/Qwen3.8-Flash-Next-MTP-Drafter-MLX-bf16atbe6e2bc325d41ac7858b99269a96c495349b494d(standalone MLX split,model_type qwen4_exp_mtp,block_size 4, 32 bf16 tensors in the stackedswitch_mlplayout), M3 Ultra,target/test-fast/mlxcelbuilt from final commite2151399(test-fast profile,metal,accelerate), temperature 0, 256 tokens,--show-reasoningso the whole stream is compared. The CLI and server results below were rerun on that commit after the review fixes.src/models/qwen4_exp_rollback_tests.rs): QSA block boundary (39 + 5 tokens, keep 2: 11 summaries drop to 10), dense/sparse switch (17 + 5, keep 2, then probes into the sparse regime), rejected EOS (context ends[prompt[11], 5], not[9, 21]; keeping the EOS matches the reference too), every keep count, the engine path (verify,unwind_appends,verify_rounds_unsupportedisNone) and a rewind of the newest forward that refuses to go past it; each component has a control that fails without it (RollbackParts).Qwen4ExpMTPDraftModel:fuse_inputs, one 6-token forward (pre-mixer streams and LM-head logits) and one cached step match within 1e-5 relative ontests/fixtures/qwen4_exp/mtp.json; the post-mixer[1, S, hidden]hidden is refused by name.gate_up_projwith.scalesand.biasessplits along the row axis intoswitch_mlp.gate_proj/up_projwithdown_projmoved; the router stays float32 with no sidecars; the released already-split layout is left untouched.mlxcel generate -m <target> --draft-model <drafter> -p <prompt> -n 256 --temp 0 --show-reasoning. Acceptance 0.479 / 0.630 / 0.396 / 0.628 (mean accepted length 2.44 / 2.88 / 2.19 / 2.88, block 4,block=2..4where the controller shrank it). Decode 46.2 / 54.1 / 41.6 / 53.9 tok/s versus classic 42.8 / 42.9 / 42.8 / 41.8 on a host running sibling builds: single runs, not a benchmark. Additional long-prompt check during review (about 4000 prompt tokens, 128 generated, commitf1d15822): identical to classic with the drafter (acceptance 0.507) and with prompt lookup (0.110).mlxcel generate --prompt-lookupno longer declines and is byte-identical to classic on the same four prompts (acceptance 0.229 / 0.189 / 0.206 / 0.411). Server:mlxcel-server -m <target> --host 127.0.0.1 --port 18481 --draft-kind prompt-lookup, one/v1/chat/completionsrequest (English prompt,max_tokens 256,temperature 0) returns content and reasoning identical to a classicmlxcel-serverrun; the startup log shows the exactness probe failing underqmv_wideand passing without it. The same request against--model-draft <drafter>is identical as well, andGET /v1/internal/mtp-policyreports the pairing in itsprofilingstate (acceptance_rate 0.48,samples 1of 4,mtp_enabled true, no verdict yet). With--prefill-chunk-size 512and a 2028-token prompt (commit5f341e37,MLXCEL_ENABLE_MTP_B1=1, classic run underMLXCEL_QMV_WIDE=0) MTP is identical to classic too.docs/supported-models.mdrow and MTP table row, with how to obtain or split the drafter.Unverified or partial: the benchmark criterion above; the probe on the ops (CPU/CUDA) fallback was not run, the gate requires Metal for this family; drafter load-time quantization (issue part D) was not measured; the test binaries were run with narrow filters only, full-workspace verification is left to CI; B > 1 and image/video requests decline to classic decode by design.
Deferred benchmark commands (same host as
docs/benchmark_results/qwen4-exp-m3-ultra-2026-10-23.md, release build, five runs each, nothing else on the GPU):./target/release/mlxcel generate -m models/Qwen3.8-Flash-Next-OptiQ-2bit -p <prompt> -n 256 --temp 0(classic); the same with--draft-model models/Qwen3.8-Flash-Next-MTP --draft-block-size {2,3,4}; the same with--prompt-lookupon the file-rewrite prompt;./target/release/mlxcel-server -m models/Qwen3.8-Flash-Next-OptiQ-2bit --model-draft models/Qwen3.8-Flash-Next-MTP --port 8080followed by five chat completions andcurl http://127.0.0.1:8080/v1/internal/mtp-policyfor the verdict;./target/release/speculative_benchfor the per-round profile. Include a Korean or Chinese prompt in the acceptance set.Test plan
cargo test --profile test-fast --features metal,accelerate --lib -- --test-threads=1 models::qwen4_exp(93 passed at5f341e37; models unchanged since)cargo test --profile test-fast --features metal,accelerate --bin mlxcel -- offline_mtp_declines(1 passed)cargo test -p mlxcel-core --profile test-fast --features metal,accelerate --lib -- drafter::tests speculative::prompt_lookup_tests engine::verify_round(60 passed)cargo test --profile test-fast --features metal,accelerate --lib -- server::batch::speculative_burst_tests::mtp_ server::batch::speculative_burst_tests::every_mtp server::batch::scheduler(passed; the dispatch-site coverage test enforces the new arm everywhere)cargo clippy --lib --tests --bins --features metal,accelerate -- -D warnings,cargo fmt --checke2151399under the real-model lock)Closes #2880