Skip to content

feat(speculative): wire the native MTP head and rollback for qwen4_exp - #2908

Merged
inureyes merged 6 commits into
mainfrom
feature/issue-2880-qwen4-exp-mtp-rollback
Nov 9, 2026
Merged

inureyes merged 6 commits into
mainfrom
feature/issue-2880-qwen4-exp-mtp-rollback

Conversation

@inureyes

@inureyes inureyes commented Nov 9, 2026 •

Copy link
Copy Markdown
Member

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.

  • Rollback (src/models/qwen4_exp_rollback.rs, kept apart from Qwen4ExpCache for 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) backs rewind_decode_appends for the engine's prompt-lookup rounds.
  • Decode-equivalent verify block (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): without it the probe declined the real checkpoint at block 4 in about half of all logit bytes. The remaining source on GPU generation 15+ is qmv_wide, which the existing gate switches off; prompt lookup on this family now runs that gate too (CLI and server) at max_draft + 1.
  • qwen4_exp_mtp drafter 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 upstream sanitize and 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 the model_type, drafter_loader builds it.
  • Qwen4ExpMtpTargetAdapter and the CLI, burst, slice/scheduler and bench arms for LoadedModel::Qwen4ExpVLM, under the same exactness gate and Metal guard as Qwen 3.5. Block size stays on --draft-block-size (default 4; the drafter's block_size is the adaptive start depth); the adaptive policy remains the gate and the MTP default is unchanged.
  • LanguageModel::supports_speculative_verify_rewind (default false, only qwen4_exp opts in, so no other model-owned family is newly admitted) lets a family that rewinds its own verify tail through prompt_lookup_unsupported_reason and Engine::verify_rounds_unsupported; decode lookahead stays off. generate --prompt-lookup refuses this family by name off Metal, matching the server and the MTP path.
  • The MTP target prefill follows the classic PrefillPlan (2048-token chunks by default, the server's prefill_chunk_size on the server paths); a single-call prefill diverged from classic on long prompts. A drafter with a different hc_count is refused before bind through LanguageModel::residual_stream_count, and generate --draft-model declines an empty prompt by name.
  • Docs rows in supported-models.md and mtp-policy-api.md, a CHANGELOG entry; the fixture generator gains the drafter case and per-case regeneration (tests/fixtures/qwen4_exp/mtp.json, mlx-vlm abd3b2d7, the local clone revision; the drafter files match the issue's a54f1a0 in substance).

Acceptance criteria

Target mlx-community/Qwen3.8-Flash-Next-OptiQ-2bit, drafter sh0wie/Qwen3.8-Flash-Next-MTP-Drafter-MLX-bf16 at be6e2bc325d41ac7858b99269a96c495349b494d (standalone MLX split, model_type qwen4_exp_mtp, block_size 4, 32 bf16 tensors in the stacked switch_mlp layout), M3 Ultra, target/test-fast/mlxcel built from final commit e2151399 (test-fast profile, metal,accelerate), temperature 0, 256 tokens, --show-reasoning so the whole stream is compared. The CLI and server results below were rerun on that commit after the review fixes.

  • Rollback unit tests (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_unsupported is None) and a rewind of the newest forward that refuses to go past it; each component has a control that fails without it (RollbackParts).
  • Drafter parity against mlx-vlm's Qwen4ExpMTPDraftModel: fuse_inputs, one 6-token forward (pre-mixer streams and LM-head logits) and one cached step match within 1e-5 relative on tests/fixtures/qwen4_exp/mtp.json; the post-mixer [1, S, hidden] hidden is refused by name.
  • Sanitize test: fused gate_up_proj with .scales and .biases splits along the row axis into switch_mlp.gate_proj / up_proj with down_proj moved; the router stays float32 with no sidecars; the released already-split layout is left untouched.
  • Temperature 0 with the drafter, byte-identical to classic on four prompts (English essay, Rust quicksort, Korean seasons, English file rewrite): 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..4 where 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, commit f1d15822): identical to classic with the drafter (acceptance 0.507) and with prompt lookup (0.110).
  • mlxcel generate --prompt-lookup no 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/completions request (English prompt, max_tokens 256, temperature 0) returns content and reasoning identical to a classic mlxcel-server run; the startup log shows the exactness probe failing under qmv_wide and passing without it. The same request against --model-draft <drafter> is identical as well, and GET /v1/internal/mtp-policy reports the pairing in its profiling state (acceptance_rate 0.48, samples 1 of 4, mtp_enabled true, no verdict yet). With --prefill-chunk-size 512 and a 2028-token prompt (commit 5f341e37, MLXCEL_ENABLE_MTP_B1=1, classic run under MLXCEL_QMV_WIDE=0) MTP is identical to classic too.
  • Paired five-run benchmark and the adaptive policy verdict: not run (timed measurements are contaminated by the concurrent sibling builds on this host). Commands below.
  • docs/supported-models.md row 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-lookup on 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 8080 followed by five chat completions and curl http://127.0.0.1:8080/v1/internal/mtp-policy for the verdict; ./target/release/speculative_bench for 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 at 5f341e37; 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 --check
  • Real-model runs above (12 CLI and 3 server runs on e2151399 under the real-model lock)

Closes #2880

@inureyes inureyes added status:review Under review type:enhancement New features, capabilities, or significant additions type:performance Performance improvements priority:medium Medium priority area:models Model architectures, weights, loading, metadata area:inference Generation, sampling, decoding (incl. speculative, DRY) platform:macos macOS (Apple Silicon) specific modelsize:xlarge 4-bit checkpoint > 100GB; exceeds a 128GB dev box, needs bigger hardware modeltype:vlm Vision-language model arch:hybrid Hybrid attention stack (linear/sliding/full or attention+SSM interleave) labels Nov 9, 2026
@inureyes

inureyes commented Nov 9, 2026

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Wire the native qwen4_exp_mtp head and speculative rollback, so MTP and prompt lookup run byte-identically to classic decode for Qwen3.8-Flash-Next.

Findings Addressed

  • The verify-rewind capability defaulted to the lookahead flag and newly admitted Gemma 3 and Baichuan to prompt lookup, whose rewinds cannot stop inside a block (HIGH), 2044c724
  • generate --prompt-lookup skipped the exactness gate off Metal (HIGH), 2044c724
  • MTP prefill was one call while classic is chunked at 2048 tokens, so temperature-0 output diverged on long prompts (HIGH), f1d15822

Remaining Items

  • RollbackLog holds up to four blocks on prompt lookup, about 450 MB of recurrent state per sequence at worst; depth 2 looks sufficient (MEDIUM), reason: below the auto-fix threshold
  • hc_count is checked at the first hidden handoff rather than at bind (MEDIUM), reason: LanguageModel does not expose it
  • The server's configurable prefill_chunk_size is not read by the MTP prefill, which uses the process default (MEDIUM), reason: below the auto-fix threshold
  • Paired five-run benchmark, deferred as the PR body states

Verification

  • All stated requirements implemented, except the deferred benchmark
  • No placeholder/mock code remaining
  • Integrated into project code flow
  • Project conventions followed
  • Existing modules reused where applicable
  • No unintended structural changes
  • Tests pass: narrow qwen4_exp, drafter loader and prompt-lookup filters, clippy, fmt

Long-context check on the real target (about 4000 prompt tokens, 128 tokens, temperature 0): classic, --prompt-lookup and --draft-model outputs are identical after the fixes, MTP acceptance 0.507, prompt-lookup acceptance 0.110.

@inureyes

inureyes commented Nov 9, 2026

Copy link
Copy Markdown
Member Author

Security and performance review

Findings addressed (HIGH, all in 5f341e37)

  • Server prefill_chunk_size was ignored by the MTP prefill, which could reintroduce the long-prompt divergence from classic decode. The burst and slice paths now pass it through.
  • RollbackLog held four captures per sequence. Each caller unwinds only within the forward just before it, so the depth is 1. A test asserts decode lookahead stays off, the one caller that would need more.
  • A drafter with the wrong hc_count passed the bind and then cut every reply to the seed token. It is now refused at bind through a new LanguageModel::residual_stream_count.

Checked, no finding

Config division and i32 limits, tensor shapes and sanitize at the drafter load, oversized block_size (clamped to the requested width), n-gram context recomputation on rollback, and empty or fully cached prompts (declined before the adapter).

Remaining (MEDIUM or LOW, not fixed)

  • MTP prefill holds pre-mixer streams for the whole prompt, about 20 KB per token. Bounded by the context limit and MTP is opt-in.
  • verify_finalize logs a rollback failure rather than ending the request (MtpTarget returns no Result); it needs a broken internal invariant.
  • A drafter prefill failure degrades to an empty history and a draft error ends the generation silently in the shared MTP loop, across families.
  • Paired five-run benchmark, still deferred.

Verification

models::qwen4_exp 93 passed; clippy and fmt clean. On the OptiQ 2-bit target at temperature 0: CLI MTP (acceptance 0.541) and prompt lookup (0.414) match classic over 96 tokens, and mlxcel-server --prefill-chunk-size 512 MTP matches classic on a 2028-token prompt, 64 tokens (classic pinned with MLXCEL_QMV_WIDE=0).

@inureyes inureyes added status:done Completed and removed status:review Under review labels Nov 9, 2026
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
@inureyes
inureyes force-pushed the feature/issue-2880-qwen4-exp-mtp-rollback branch from e215139 to 274dc16 Compare November 9, 2026 17:04
@inureyes
inureyes marked this pull request as ready for review November 9, 2026 17:05
@inureyes
inureyes merged commit a75eb1c into main Nov 9, 2026
1 check passed
@inureyes
inureyes deleted the feature/issue-2880-qwen4-exp-mtp-rollback branch November 9, 2026 17:06
inureyes added a commit that referenced this pull request Nov 10, 2026
## 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
inureyes added a commit that referenced this pull request Nov 10, 2026
…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
@inureyes inureyes added this to the 0.9 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

arch:hybrid Hybrid attention stack (linear/sliding/full or attention+SSM interleave) area:inference Generation, sampling, decoding (incl. speculative, DRY) area:models Model architectures, weights, loading, metadata modelsize:xlarge 4-bit checkpoint > 100GB; exceeds a 128GB dev box, needs bigger hardware modeltype:vlm Vision-language model platform:macos macOS (Apple Silicon) specific priority:medium Medium priority status:done Completed type:enhancement New features, capabilities, or significant additions type:performance Performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

1 participant