Skip to content

feat(qwen3.5): MTP speculative decoding for Qwen3.5/3.6 dense + MoE - #65

Merged
Brooooooklyn merged 99 commits into
mainfrom
worktree-research+qwen-mtp
Jun 3, 2026
Merged

Brooooooklyn merged 99 commits into
mainfrom
worktree-research+qwen-mtp

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

Overview

Adds the Multi-Token Prediction (MTP) speculative-decoding stack for
Qwen3.5/3.6 dense + MoE (Metal/Apple-Silicon), plus the supporting
checkpoint-conversion, server, and benchmarking changes accumulated over
~80 commits. Draft→verify→accept is lossless (Leviathan–Chen); T=0 greedy
output is byte-identical to autoregressive.

What's in here

  • MTP draft/verify loop (flat + paged compiled C++ forward paths),
    GDN linear-attention state snapshot/restore on partial-accept, chained
    cycles (Step-A elimination; M5 gen-gated ON, byte-parity verified).
  • MTP norm handling — convert-time +1.0 RMSNorm shift + load-time
    raw-checkpoint shift, with double-shift guards.
  • Quantized MTP checkpoints — convert retains the bf16 MTP head
    (--q-mtp off default), splits fused MoE MTP experts to switch_mlp.*;
    validated qwen3.6-27b-nvfp4-mtp (dense) and
    qwen3.6-35b-a3b-mxfp8-mtp (MoE).
  • extra_body.generation_mode / mtp_depth plumbed through the
    Anthropic /v1/messages mapper.
  • Server fix (this session): /v1/messages no longer returns
    400 Unsupported message role: "system" — Claude Code SessionStart
    hook messages are folded into the leading system prompt
    (position-agnostic, documented contract). Adversarially reviewed; the
    warm-slot cache key is intentionally left coarse (native token-prefix
    verifier is the correctness authority; folding hook text into the key
    would churn it and force cold prefills with no correctness gain).
  • Bench harness: examples/qwen35-mtp-controlled-verdict.ts gains a
    --prompt flag (essay/counting/code presets + raw string).

Performance (MTP vs AR, self-normalized, M5 Max, T=0)

MTP speed is prompt-gated (acceptance ∝ prompt predictability). Dense
breaks even at lower acceptance than MoE (MoE cycle ≈ 2× an AR step).

prompt 27b dense (d1) 35b MoE (d1) notes
essay (abstract prose) ~1.03× 0.82× (loss) MoE worst case
"summarize architecture" 1.09× 1.09× (CV 1.6%) realistic agentic prose
counting (predictable) 1.58× (d2 1.95×) 1.26–1.33× MTP best case

Optimal depth: dense → 2, MoE → 1 (MoE d2 acc ~1.7 < the ~1.9–2.0
needed to beat d1).

Known issues (NOT merge-ready as-is)

From the whole-branch adversarial review:

  • BLOCKING: compiled graph caches bake the first model's weights and
    are never invalidated on reload (mlx_clear_weights lacks a
    compile_clear_cache()), so loading a second same-arch model in one
    process silently reuses the first's weights.
  • HIGH: a mid-cycle non-EOS stop under reuse_cache can leave the
    cache over-advanced vs token_history (flat/MoE/paged).
  • Reproducible 37G-MoE teardown OOM (64 bytes failed at child exit) —
    memory brushing the ceiling / possible minor MTP-path leak.

These should be resolved before merge; opening for review of the overall
design and the shippable hot paths.

Validation

  • Server fix: 76 mapper unit tests pass; yarn typecheck / lint / fmt clean.
  • MTP correctness: T=0 byte-identical to AR; acceptance scales with depth.

🤖 Generated with Claude Code


Note

High Risk
Touches core Qwen3.5 inference, checkpoint conversion, and server request mapping; the PR description also flags blocking compiled-weight cache invalidation and mid-cycle stop/cache desync risks not fully resolved in this slice.

Overview
Extends the Qwen3.5/3.6 MTP speculative-decode surface end-to-end: ChatSession auto-enables enableMtp when the loaded model reports MTP weights (explicit enableMtp: false still wins), and HTTP mappers map extra_body.generation_mode / mtp_depth to chat config on both Anthropic and OpenAI-style paths.

Server/API hardening: Anthropic /v1/messages folds injected { role: 'system' } hook messages into the leading system prompt instead of 400; Responses and Messages reject invalid max_output_tokens / max_tokens (non-positive, non-integer, above i32::MAX) before NAPI truncation can yield silent empty completions. Qwen3 generate() and GRPO reject nonpositive token budgets up front.

Convert & checkpoints: Qwen3.5 sanitize/convert now retains and normalizes mtp.* weights, optional quant_mtp policies (cyankiwi / all / split drafter dir), sidecar metadata, guards against re-quantizing pre-quantized MTP, and recipe tweaks (8-bit o_proj / out_proj / GDN low-rank paths) for MTP/AR bit-exactness; NVFP4 without a recipe is refused. Default paged decode MLX cache clear cadence moves 64 → 1024 steps.

Observability & tooling: DecodeProfiler gains nested phases, record_mtp_cycle, and mlx-vlm-comparable acceptance metrics on PerformanceMetrics; a new quantized_qmv_microbench NAPI hook supports dispatch benchmarking.

Reviewed by Cursor Bugbot for commit 007c03a. Bugbot is set up for automated code reviews on this repo. Configure here.

@coderabbitai

coderabbitai Bot commented Jun 2, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 46cd2801-8603-4d2a-a51d-61eb8ca16542

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch worktree-research+qwen-mtp

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6e26940c29

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread crates/mlx-sys/src/mlx_qwen35.cpp Resolved
Comment thread crates/mlx-core/src/convert.rs Resolved
Comment thread crates/mlx-core/src/convert.rs Resolved
Brooooooklyn added a commit that referenced this pull request Jun 2, 2026
Two issues surfaced by automated PR review (PR #65):

- MoE `--q-mtp` was blocked: `emit_mtp_sidecar` is dense-only (the 4-bit
  MTP sidecar is a dense/MTPLX layout), so for MoE `mtp_sidecar_tensors`
  is always empty — but the guard `quant_mtp != "off" && …is_empty()`
  then errored out for MoE with a misleading "no mtp.* tensors found",
  even though the MTP weights were already quantized inline by
  `apply_mtp_quant_policy`. Scope the empty-sidecar guard to
  `emit_mtp_sidecar` (dense) and add a MoE-specific check that errors
  only when the MoE checkpoint genuinely has no mtp.* tensors.

- `sanitize_qwen35_moe`'s local `is_mtp_key` closure and its sibling
  prefix normalization hand-rolled a strip-chain missing the
  `model.language_model.model.` (VLM-wrapped) prefix, so such a key
  escaped MTP detection and fell through to the LM path (wrong output
  prefix + wrong +1.0 norm shift). Delegate both to the module-level
  `normalize_mtp_prefix`, the canonical handler used everywhere else.

cargo build/clippy/fmt clean; 56 convert unit tests pass.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Comment thread crates/mlx-core/src/convert.rs Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: eaa1d33481

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Brooooooklyn and others added 24 commits June 2, 2026 18:32
Stop dropping `mtp.*` keys in sanitize_weights. The W2 MTP head module will
consume them. Apply weights still uses HashMap lookups, so orphan mtp.* keys
are silently ignored until W2 wires consumers.

- Add `n_mtp_layers: i32` (serde default 0) to both Qwen3_5Config and
  Qwen3_5MoeConfig; populated from `mtp_num_hidden_layers` /
  `num_nextn_predict_layers` in config.json.
- Bypass the +1.0 norm shift for mtp.* keys — MTP weights are stored in
  final form (MTPLX convention).
- MoE early-exit: route mtp.* keys past expert stacking, gate_up split, and
  experts.down_proj rename. W2 decides final storage shape.
- Update all Qwen3_5Config / Qwen3_5MoeConfig construction sites
  (parse_config, to_dense_config, test fixtures).

Per the deepresearch plan at
`.claude/plans/deepresearch-users-brooklyn-workspace-gi-eager-curry.md`.

87 qwen3_5 tests pass; cargo clippy + fmt clean.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
New module `crates/mlx-core/src/models/qwen3_5/mtp.rs` mirroring MTPLX's
`_MTPModule` (`MTPLX/mtplx/mtp_patch.py:362-369`):

  pre_fc_norm_hidden     RMSNorm(hidden)
  pre_fc_norm_embedding  RMSNorm(hidden)
  fc                     Linear(2*hidden, hidden, bias=False)
  layers                 DecoderLayer × n_mtp_layers
  norm                   RMSNorm(hidden)

MTP DecoderLayers are pinned to `layer_idx = full_attention_interval - 1`
(full-attention only). The ctor rejects configs that would silently produce
GDN (linear-attention) MTP layers, since speculative-decode rollback
semantics downstream rely on full-attention KV caches per draft step.

- `forward(prev_hidden, prev_emb, caches)`: normalize both, concat on the
  hidden axis, project via `fc`, run the MTP DecoderLayers (each owning its
  own full-attention KV cache), final norm. Caller applies `lm_head` to get
  draft logits.
- `apply_weights(params, default_plq, per_layer_quant)`: loads `mtp.fc`,
  `mtp.norm`, `mtp.pre_fc_norm_*`, and `mtp.layers.{i}.{attn,mlp,norms}`
  weights. Supports dense + per-layer quantized (affine / MXFP4 / MXFP8 /
  NVFP4) — surgical duplication of the per-layer flow in
  `persistence::apply_weights_inner`, deliberately not refactored to keep
  W2 scope tight.
- `fresh_caches(config)`: per-layer FullAttention slots, ready for W3
  snapshot/restore.

Wired `Option<Qwen3_5MTPModule>` onto `Qwen35Inner` (constructed when
`config.n_mtp_layers > 0`) and added an MTP apply-weights tail to
`apply_weights_inner` so MTP weights load in the same pass as main weights.

The existing single-token decode path ignores the MTP module — MTP becomes
visible to chat sessions only when W6 wires the draft+verify loop.

MoE follow-up still pending (separate commit), as is W3 (cache snapshot /
restore) and W4 (acceptance sampler).

92 qwen3_5 tests pass (5 new MTP unit tests + 87 baseline). Clippy + fmt
clean.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
The W6 speculative-decode loop must rewind the per-layer cache when the
verifier rejects a draft. Add snapshot/restore primitives that handle
both attention flavors without copying full-attention K/V tensors.

- `Qwen3_5LayerSnapshot { FullAttention { offset }, Linear { conv_state,
  recurrent_state } }`.
- `snapshot()`: FullAttention captures the logical offset only — zero
  tensor copy, restore truncates via `KVCache::trim()` and the next
  write reuses the pre-allocated buffer slots. Linear cache clones
  `conv_state` + `recurrent_state` via `MxArray::copy()` (the real
  mlx_array_copy, NOT `clone()` which is just `Arc::clone`).
- `restore()`: byte-equal restore for both variants; variant mismatch
  returns a descriptive `Err`.
- Convenience: `snapshot_all` + `restore_all` for the per-cycle loop.

6 unit tests cover byte-equality on both variants, empty-slot round
trip, variant-mismatch errors, multi-layer convenience helpers, and
length-mismatch error path. Metal-skip pattern matches existing
`paged_inner_or_skip`.

GDN-clone cost: `conv_state` ≈ 48 KB at bf16, `recurrent_state` a few
KB — well under 1 ms per cycle even across ~14 GDN layers. No
optimization needed for the W6 perf budget. If profiling later shows
this stalling, can swap to MTPLX `gdn_capture.py` tape-and-replay
without changing the snapshot API surface.

98 (filtered) / 103 (full) qwen3_5 lib tests pass.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
…ptance

The W6 speculative-decode loop needs a per-position acceptance step that
preserves the target distribution exactly. Add `accept_with_residual` to
`crates/mlx-core/src/sampling.rs` mirroring MTPLX `sampling.py:143-183`.

  p_accept = min(1, p_target[draft_id] / p_draft[draft_id])     (fp32)
  u ~ Uniform(0, 1)
  if u <= p_accept:               (true, draft_id)
  else:
      residual = clip(p_target - p_draft, min=0).normalize()
      if residual.sum() == 0:     (false, argmax(p_target))
      else:                       (false, sample(residual))

- Generic `R: rand::Rng + ?Sized` for the `u` draw. The residual sample
  goes through `MxArray::categorical` which uses MLX's own RNG, matching
  the existing `sample()` contract.
- Inputs upcast to fp32 before scalar extraction — BF16 underflows on
  small `q` and breaks exactness.
- `.eval()` before each `item_at_*` extraction; the FFI segfaults on
  lazy arrays.
- Defensive `p_draft <= 0` short-circuit: avoids divide-by-zero by
  setting `p_accept = 1.0` if `p_t > 0`, else `0.0` (matches MTPLX
  `acceptance_probability`).
- Zero-sum / NaN-safe fallback to `argmax(p_target)` via
  `!total.is_finite() || total <= 0.0`.
- T=0 collapse falls out of the math — no separate branch.

6 unit tests cover T=0 match/mismatch, accept-with-target-dominates,
reject-with-residual-support, zero-sum fallback, and target-zero-at-
draft-id. A `ScriptedRng` helper pins `u` to exact 0 / ~1 values for
the deterministic accept/reject tests (the `rand` standard-uniform path
uses `next_u64 >> 11`).

Spec review ✅ — no unwrap/expect in runtime path, scope limited to
sampling.rs.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
…ensive offset check

Quality review identified four pre-W6 items in the snapshot/restore API.
All addressed here without changing the runtime semantics on the happy
path.

- **Lazy-copy invariant**: snapshot() doc now spells out that
  `MxArray::copy()` is a lazy graph node, not a memcpy, and that the
  safety contract is "no in-place mutation of conv_state /
  recurrent_state in any qwen3_5 forward path". If a future change
  introduces such mutation, this API must materialize via `eval()`
  before the mutation.
- **Paged-KV caveat**: snapshot() doc warns that the API is flat-cache
  only — callers must guard with `paged_adapter.is_none()` before
  snapshotting. `debug_assert!` at the top of the FullAttention arm
  fires loudly in dev/test builds when the underlying KVCache is empty
  (a likely sign the paged adapter is the actual owner of K/V state).
- **restore_all atomic**: pre-validate every (cache, snap) variant pair
  before any mutation. On mismatch, return Err with the offending index
  and variant kinds; no cache is touched. The length check stays at the
  top.
- **Defensive offset check**: restore() FullAttention rejects snapshots
  whose offset > current cache offset (KVCache::trim silently no-ops in
  that case, which would have hidden bugs).
- Tightened test failure modes: `from_float32` errors now unwrap (shape
  validation only, no Metal); only real eval/Metal failures still
  trigger the skip path. Added explicit `arr.eval()` in
  `snapshot_linear_byte_equality` to document the lazy-eval contract.
- Visibility narrowed: snapshot/restore/snapshot_all/restore_all and
  the Qwen3_5LayerSnapshot enum moved from `pub` to `pub(crate)`. W6
  is the only consumer.
- The original `restore_variant_mismatch_errors` test was rewritten to
  construct snapshot enums directly — the new paged-KV `debug_assert!`
  fires on the previous "snapshot a fresh empty FullAttention" pattern.

+2 tests:
- `restore_all_atomic_on_variant_mismatch_no_mutation` — sets up
  [FullAttention, Linear], swaps the second snapshot's variant, runs
  restore_all; all caches must be unchanged from their pre-restore
  state, Err returned.
- `restore_full_attention_rejects_grow_attempt` — primes to offset 4,
  restore with snapshot offset 10 → Err with both offsets in message.

8 layer_cache tests pass; clippy + fmt clean.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
New module `crates/mlx-core/src/models/qwen3_5_moe/mtp.rs` mirroring
the dense `Qwen3_5MTPModule` (a101c64) for Qwen3.5-MoE. Same
architecture (pre_fc_norm × 2, fc, DecoderLayers, final norm), but
each DecoderLayer is the MoE-flavored one (`SparseMoeBlock` +
`SwitchGLU` for sparse layers).

- `new(config)` pins MTP layers to `fa_idx = max(full_attention_interval
  - 1, 0)` and rejects all-linear configs. The MLP flavor at `fa_idx`
  follows `is_moe_layer(fa_idx)` — for canonical
  `decoder_sparse_step=1` checkpoints the MTP layer resolves to MoE.
- `forward(prev_hidden, prev_emb, caches)` mirrors dense.
- `apply_weights(params, default_plq, default_gate_plq, per_layer_quant)`
  handles all three MLP branches: `MLPType::Dense(Standard)`,
  `MLPType::Dense(Quantized)` no-op, and `MLPType::MoE` (router gate
  + `switch_mlp.{gate,up,down}_proj` via QuantizedSwitchLinear /
  SwitchGLU + shared_expert.* + shared_expert_gate).
- **Gate-PLQ routing via `effective_plq_for`**: gates (.mlp.gate,
  .mlp.shared_expert_gate) route to `default_gate_plq` (typically
  8-bit affine) instead of the global `default_plq` (typically 4-bit
  affine). For canonical recipes (mixed_2_6, mixed_3_4, qwen3_5) the
  global default and the gate default diverge — using `default_plq`
  for gates would mis-load the quantized router weights and produce
  garbage activations. The persistence call site threads
  `default_gate_plq` through from `compute_moe_defaults`.
- `fresh_caches(config)`: n_mtp_layers FullAttention slots.
- Wired `Option<Qwen3_5MoeMTPModule>` onto `Qwen35MoeInner` and added
  the `mtp.apply_weights(...)` tail to `apply_weights_moe_inner`.

6 unit tests including the regression guard
`apply_weights_routes_gate_to_default_gate_plq` which asserts gate
prefixes resolve to default_gate_plq while non-gate prefixes resolve
to default_plq. Spec-compliance review ✅ confirmed the gate-routing
correctness.

103 qwen3_5 tests pass; clippy + fmt clean.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Code quality review found a Leviathan-Chen exactness break at the
acceptance boundary: `rng.random::<f64>()` returns a value in `[0, 1)`,
so `next_u64() = 0` yields `u = 0.0` exactly. With `u <= p_accept` and
a degenerate `p_accept = 0.0` (e.g. `p_target[draft_id] = 0` and
`p_draft[draft_id] > 0`), the function would incorrectly accept a
token of zero target mass.

Switch to strict `<`. Post-fix: `p_accept = 0` always rejects (because
`u >= 0` always), and `p_accept = 1` always accepts (because `u < 1`).
The four pre-existing acceptance-edge tests all still pass — none of
them sat on the boundary `u == p_accept`.

Also:
- Visibility narrowed: `pub fn accept_with_residual` →
  `pub(crate) fn accept_with_residual`. Only W6's chat_common.rs will
  call this; no cross-crate need.
- Doc softening: the T=0-collapse paragraph no longer claims the
  argmax fallback is exact in the degenerate regime — it correctly
  notes that exact correction is impossible when the residual carries
  no mass.

+1 regression test `rejects_when_target_zero_at_draft_id_with_u_zero`:
forces `u = 0.0` via `ScriptedRng::new(&[0])`, sets
`p_target = [0.0, 0.5, 0.5]` / `p_draft = [1.0, 0.0, 0.0]` /
`draft_id = 0`. Pre-fix this test would have incorrectly returned
`(true, 0)`; post-fix it correctly rejects and emits a residual sample
from {1, 2}.

34 sampling tests pass (33 baseline + 1 regression guard); clippy +
fmt clean.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Adds the dense half of W5: compiled C++ entry points for the MTP
speculative-decode draft and verify steps, plus the Rust wrappers and
test scaffolding to exercise them.

- mlx_qwen35_mtp_compiled.cpp: 6 FFI exports (init_from_main, draft,
  verify, reset, adjust_offset, get_offset). Draft fn wrapped in
  mlx::core::compile (offset is array-valued — same pattern as the
  paged-decode graph). Verify is per-depth std::function dispatch
  table {1..5} that loops the existing single-token forward; the
  per-step body still benefits from the compile-cached inner kernels
  in mlx_qwen35_common.h.
- attn_pure_fn_arr_offset in mlx_qwen35_common.h: array-valued RoPE
  offset variant of attn_pure_fn so the draft graph's compile cache
  stays valid across all draft steps in one turn.
- mlx_qwen35_is_compile_inited + mlx_qwen35_compiled_test_force_inited:
  init helper now checks the main path is initialised before mirroring
  its offset (silent phantom-offset bug was possible if W6 misordered
  init). The _test_force_inited setter is for the W5 smoke tests only,
  loud-named and unsafe-gated on the Rust side.
- model.rs: 3 Rust wrappers + DENSE_COMPILED_MUTEX contract documented
  (production callers hold the lock; tests serialise via FFI_LOCK).
- mtp.rs: compiled_ffi_tests covers init rejection paths and the
  draft-step shape contract.

Verify-as-loop and lazy first-use of the per-depth verify table are
documented compromises; the draft compile-wrap is the load-bearing
piece for the W6 perf target.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Mirrors W5 dense (ac1e606) for the MoE variant. Adds compiled C++
entry points for the MTP speculative-decode draft and verify steps,
Rust wrappers under MOE_COMPILED_MUTEX, and FFI-smoke tests.

- mlx_qwen35_moe_mtp_compiled.cpp: 6 FFI exports analogous to dense,
  with MoE-specific divergences: per-layer MoE-vs-dense MLP dispatch
  at the MTP layer's pinned fa_idx, per-MTP-layer quant detection
  (separate g_mtp_layer_quant / g_mtp_dense_quant from the main MoE
  path), router-gate PLQ via detect_router_gate_quant so canonical
  mixed_2_6 / mixed_3_4 / qwen3_5 recipes (8-bit gates, 4-bit
  experts) load correctly. Draft fn wrapped in mlx::core::compile.
  Verify graphs are per-depth std::function table {1..5} looping
  the existing mlx_qwen35_moe_forward (same compromise as dense).
- Private g_mtp_3d_transposes cache for mtp.* expert weights
  (main MoE's analogous map is anon-namespace-static so not
  visible across translation units).
- mlx_qwen35_moe.cpp: +mlx_qwen35_moe_is_compile_inited accessor
  and the test-only _test_force_inited setter, mirroring dense.
- model.rs: 3 Rust wrappers; doc explicitly says MOE_COMPILED_MUTEX
  (NOT DENSE_COMPILED_MUTEX) is the production lock.
- mtp.rs: compiled_ffi_tests with tiny MoE config
  (decoder_sparse_step=1, num_experts=4) so the draft test exercises
  the sparse_moe_fn_pfx branch + 3D-transpose path, not just dense.

Helper duplication (linear_forward_mtp, switch_linear_fwd_mtp,
gather_sort_mtp, etc.) follows the spec's prefer-copy-over-refactor
guidance — verified byte-identical to the main MoE helpers modulo
prefix substitution.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Wires the MTP draft+verify+accept cycle into Qwen3.5 dense chat
sessions. Uses W1-W5 building blocks: MTP weights (W1), W5 dense
compiled FFI, accept_with_residual (W4). W3 snapshot/restore is NOT
used on the compiled path — the live K/V is in the C++ globals and
the rollback primitive is mlx_qwen35_compiled_adjust_offset.

Architecture:
- New small FFI: mlx_qwen35_export_last_hidden, stashed BEFORE lm_head
  in qwen35_decode_fn so MTP draft step 0 can seed prev_hidden.
- forward_compiled_with_hidden returns (logits, hidden) — only used
  in the MTP path.
- decode_loop_mtp! macro in chat_common.rs mirrors decode_loop!'s
  structure (EOS, repetition cutoff, ReasoningTracker, penalties,
  streaming, cancellation, profiler, 256-step cache clear). Each
  outer iteration runs Step A (one main forward, captures hidden)
  then one MTP cycle (D draft + 1 verify + accept loop + optional
  bonus on full-accept). Emits 1..=D+2 tokens per outer iteration.
- 3 dispatch sites in model.rs (sync, stream-delta, stream-session)
  gate on `enable_mtp && self.has_mtp_weights()`. Default is off
  pending W7 plumbing.
- Rollback formula at each dispatch site:
    delta = accepted_drafts as i32 - depth as i32;
    if delta != 0 { adjust_offset(delta) for both main and MTP }.
  Derivation: verify writes D+1 K/V slots (committed_id + D drafts);
  we keep K accepted draft slots; correct rewind is K - D (residual
  has no K/V — it gets one at NEXT cycle's Step A).
- Adaptive depth EMA is OUT OF SCOPE. Fixed mtp_depth = 3.

Known caveat — chained cycles not implemented:
- Each outer iteration always runs Step A (one main forward). MTPLX
  skips this on the hot path by seeding the next cycle's prev_hidden
  from verify_hidden[:, -1:, :], which would require a new FFI to
  export the verify graph's last hidden state.
- This costs roughly +150ms per cycle on M3 Max bf16 (one extra
  main decode step). On all-accept depth=3, MTPLX measures ~2.24×
  on Qwen3.6-27B; W6's chained-cycle deficit reduces that estimate
  to ~1.43× — possibly under the plan's 1.6× target. If the W6 path
  measurement in the manual smoke (task #8) misses the bar, a W6.5
  follow-up will add the verify-hidden export and chain cycles.

Tests:
- chat_common::mtp_cycle_tests: 4 cycle tests (all-accept emits D+1,
  depth=1 degenerates, all-reject emits 1 residual, partial-reject
  regression that asserts (accepted_drafts, depth) callback values).
- chat_common::mtp_params_tests: 3 ChatParams extraction tests.
- mtp::compiled_ffi_tests::export_last_hidden_null_without_main_forward.
- All 120 qwen3_5 unit tests pass (14 ignored on non-Metal).

The MoE-side model.rs edit is only ChatConfig field plumbing
(enable_mtp: None, mtp_depth: None) to keep MoE chat sessions
compiling. W6 MoE comes next.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Mirrors W6 dense (77da687) for the Qwen3.5 MoE variant. Reuses the
dense `decode_loop_mtp!` macro from `qwen3_5/chat_common.rs` 100%
via the generic `MtpOps` struct — no generalization needed.

C++ design difference from dense:
- Dense's main path calls `qwen35_decode_fn` directly (no compile
  wrap), so `g_last_hidden = h` inside the function body fires every
  call.
- MoE's main path runs through `mlx::core::compile(moe_compiled_decode_fn)`,
  so a body-level assignment would only fire at trace time. Instead,
  `last_hidden` is emitted as graph output slot 2 (caches shift to
  start at slot 3) and stashed by `mlx_qwen35_moe_forward` after the
  compiled call. A defensive `outputs.size()` check guards against
  silent stride drift in future edits.

4 MoE dispatch sites (sync, stream, sync-delta, stream-delta) each
acquire `MOE_COMPILED_MUTEX` before entering `decode_loop_mtp!` and
call `mlx_qwen35_moe_mtp_compiled_reset()` immediately after.

Same caveat as W6 dense — chained cycles not implemented (each
outer iteration runs Step A's main forward). The W6.5 follow-up
will add `mlx_qwen35_moe_mtp_verify_compiled_with_hidden` if the
manual smoke (task #8) shows the 1.6× target missed.

Tests: 22/22 MoE unit tests pass (7 Metal-gated ignored), including
the new `export_last_hidden_null_without_main_forward` smoke. No
dense regressions (121/121 dense unit tests pass).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Surfaces MTP detection + per-session/per-request opt-in:

- NAPI: `hasMtpWeights(): boolean` on Qwen35Model + Qwen35MoeModel,
  snapshotted at load from `inner.has_mtp_weights()` and exposed via
  `#[napi]`. Auto-generated TS at packages/core/index.d.cts.
- ChatSession.mergeConfig: when overlay+default leave `enableMtp`
  undefined AND `model.hasMtpWeights()` returns true, defaults to
  true. Explicit `false` always wins. Models without the method
  (Qwen3, Gemma4, LFM2) pass through unchanged via a typeof guard.
- /v1/responses and /v1/messages mappers accept
  `extra_body.generation_mode = "mtp" | "ar"` to force the flag per
  request, and `extra_body.mtp_depth` (validated as positive int
  ≤ 5) to override depth. Unknown generation_mode values are
  ignored so the auto-default applies. Shared helper
  `applyExtraBodyMtpOverrides` in mappers/request.ts.

Tests: +13 across chat-session, request-mapper, anthropic-mapper
(auto-default fires/skips/respects-explicit-false; mapper handles
"mtp"/"ar"/absent/null/unknown; mtp_depth rejects 0/-1/6/2.5/NaN).
All 702 W7-relevant TS tests pass.

Pre-existing W1 leftover fixes (TS build was failing because the
0.6B preset and TINY_QWEN35_CONFIG were missing `nMtpLayers: 0`):
packages/lm/src/models/qwen3_5-configs.ts +5,
__test__/test-model-utils.ts +2.

Plan deviations (accepted):
- Plan named packages/server/src/router.ts; the actual request
  shape transform lives in mappers/{request,anthropic-request}.ts.
- Plan asked for `enableMtp`/`mtpDepth` on LoadModelOptions
  /ChatSessionOptions; W6's NAPI auto-generation already put them
  on ChatConfig, and ChatSessionOptions.defaultConfig: ChatConfig
  carries them. No new fields needed.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Validates W6 wiring by running the same prompt twice on an
MTP-equipped checkpoint at T=0: once with enableMtp=false, once
with enableMtp=true. Outputs MUST match token-for-token by the
Leviathan-Chen exact-distribution guarantee; reports decode tok/s
and the speedup ratio against the plan's >=1.6x target.

  oxnode examples/qwen35-mtp-smoke.ts [model-name] \
    [--depth N] [--max-tokens N] [--prompt "..."] [--no-warmup]

Defaults: qwen3.5-4b, depth=3, max-tokens=200.

Smoke result on qwen3.5-0.8b and qwen3.5-4b is currently
FAILING parity — outputs diverge at character 0 and MTP exits
into repetition cutoff within ~15-50 tokens while AR continues
coherently. MTP is also 2-4x slower than AR (acceptance rate
near zero on every cycle). This indicates a real bug in W6 that
was not surfaced by the unit-test mocks. Investigation tracked
as W6.5 / new follow-up.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
W6's decode_loop_mtp! macro never pushed the initial y token (sampled
from prefill's last logits) to $gen / $hist / tracker. AR's
decode_loop! pushes $y at the top of each iteration; MTP's Step A
only pushed the *sampled* next_token, silently dropping y0.

Smoke on qwen3.5-4b (T=0, depth=3) before fix:
  AR  : "```python\\ndef fibonacci(n):..."
  MTP : "python\\ndef fibonacci(n):..."  (missing leading ```)

After fix, both outputs start identically with "Deterministic
sampling at temperature 0 is" (42 chars matching).

This is one of two real bugs surfaced by the W8 smoke benchmark.
Bug #2 — MTP cache offset drift from main offset (+2 per cycle from
Step A's 1 forward + verify's D+1 forwards vs MTP draft's D
forwards) — still causes mid-stream divergence at char 43 and
catastrophic acceptance-rate collapse. Tracked as task #12;
investigation reset with the correct diagnosis.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Two correctness improvements driven by smoke benchmark (b366bc3).

Fix #2 — MTP K/V cache offset drift vs main offset:
- Per outer cycle, main offset advanced by D+2 (1 Step A + D+1
  verify forwards), MTP draft offset advanced by D. Drift = +2/cycle.
  MTP draft's RoPE positions diverged from the absolute sequence
  positions, poisoning attention and collapsing acceptance to 0.
- Fix: new FFI `mlx_qwen35_mtp_compiled_begin_cycle(main_offset)`
  zeroes MTP K/V caches and re-anchors `g_mtp_offset_int =
  main_offset` at the start of every cycle. MoE twin
  `mlx_qwen35_moe_mtp_compiled_begin_cycle` mirrors. `MtpOps`
  gains a `begin_cycle` closure; macro calls it before
  `run_mtp_cycle_inner`.

Fix #3 — accept_with_residual non-deterministic at T=0:
- W4 spec said T=0 collapses to argmax(p_target) == draft_id, but
  the implementation always took the raw-softmax ratio path and
  sampled from (p_target - p_draft)+ via MLX `categorical()` on
  rejection — stochastic via MLX's global RNG.
- Fix: `accept_with_residual` now takes `sampling_config:
  &SamplingConfig`. When temperature <= 1e-6, returns
  (argmax(p_target) == draft_id, argmax(p_target)) — zero RNG
  consumed. Stochastic path unchanged for T > 0.
- Unit tests: 2 new (`accepts_argmax_at_t_zero`,
  `rejects_non_argmax_at_t_zero_emits_argmax`) + existing 7
  threaded through helper builders.

Smoke result after both fixes:
- Bug #1 fix advanced parity prefix from 0 → 42 chars.
- Bug #2 fix held that and eliminated the offset drift.
- Bug #3 fix made the residual emission deterministic.
- AR  : "...is essential for testing speculative decoding because
        it eliminates stochasticity, ensuring..."
- MTP : "...is useful for testing speculative decoding
        implementations.\n\nThis ensures that every run produces
        identical outputs..."

Both AR and MTP now produce coherent, deterministic output, but
they still diverge at char 43. Remaining gap (Bug #4): the verify
FFI's logits at position 0 disagree with `forward_compiled_with_hidden`'s
logits for the same prefix and same K/V state. Both paths should
end up in `qwen35_decode_fn`, so the divergence implies stateful
interaction between Step A and verify that needs runtime
instrumentation to isolate.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Final correctness fix — parity gate now PASSES at T=0 on real
Qwen3.5 weights (qwen3.5-4b, byte-exact 640 chars).

## Root cause (validated by runtime instrumentation)

Qwen3.5 is hybrid-attention: most layers are gated-delta-net (GDN)
linear-attention with `conv_state` + `recurrent_state` that mutate
sequentially per `mlx_qwen35_forward_compiled` call. The W6 verify
FFI runs D+1 sequential forwards through `[last_committed, d_0,
.., d_{D-1}]`, advancing every linear layer's recurrent state by
D+1 token steps.

On rejection, `mlx_qwen35_compiled_adjust_offset(delta)` only
rewound `g_offset_int` — the GDN linear caches stayed in their
polluted state. Step A's next forward then read a stale recurrent
state and produced wrong logits even though the input token and
offset were correct.

W3 already added snapshot/restore for the eager Rust path
(`Qwen3_5LayerCache`); this fix extends the same design to the
compiled C++ path that production decode actually uses.

## Fix shape

4 new FFI exports (2 per model):
  mlx_qwen35_compiled_snapshot_linear_caches()
  mlx_qwen35_compiled_restore_linear_caches()
  mlx_qwen35_moe_compiled_snapshot_linear_caches()
  mlx_qwen35_moe_compiled_restore_linear_caches()

Snapshot captures only linear (GDN) layer K/V from
`g_compiled_caches` plus the offset; full-attention layers are
intentionally NOT snapshotted (slot-based K/V is overwritten on
next write, masked by the rolled-back offset).

`MtpOps` gains `snapshot_main_linear` and `restore_and_replay_main`
closures. The cycle now:
  - snapshots before verify;
  - on full-accept (K == D): discards snapshot (verify left
    linear state correctly advanced through all D+1 emitted tokens);
  - on non-full-accept (K < D or all-reject): restores snapshot,
    then replays K+1 forwards through [last_committed, d_0..d_{K-1}]
    to bring linear state to the AR-equivalent post-emission state.
    The residual sample's K/V is laid down by the NEXT cycle's
    Step A.

K+1 replay forwards on non-full-accept are a perf hit but the
correctness bar is met. Perf optimization is W6.5 (chained
cycles via verify-hidden export).

## Smoke result (qwen3.5-4b, depth=3, max-tokens=100, T=0)

  AR  | tokens=100 | TTFT=234ms | decode=7.92 tok/s
  MTP | tokens=100 | TTFT=63ms  | decode=2.37 tok/s

  Parity: OK — AR and MTP produced identical 640-char output.
  Speedup: 0.30x (perf is W6.5 territory; correctness is the bar).

## Tests

- 121 dense qwen3_5 unit tests pass.
- 22 MoE qwen3_5_moe unit tests pass.
- 4 mtp_cycle_tests updated for the new MtpOps closure shape.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
…default-off)

Adds the FFI + Rust dispatch surface for chained MTP cycles per the W6.5
plan: `mlx_qwen35_mtp_verify_compiled_with_hidden` (and MoE twin) export
the post-final-norm hidden of the last verify iteration alongside the
stacked logits. The Rust dispatcher (`forward_mtp_verify_compiled_with_hidden`,
MoE counterpart) wires the new entrypoints through to a `(MxArray, MxArray)`
verify-step closure in `MtpOps`; `run_mtp_cycle_inner` returns the
verify-final hidden as a third tuple slot so the `decode_loop_mtp!` macro
can stash it across iterations.

The chained-cycle path is GATED OFF by default. Setting
`MLX_MTP_CHAINED_CYCLES=1` opts in; without the env var the macro always
runs Step A, preserving pre-W6.5 byte-exact behaviour. Default-off
rationale (documented inline at `chained_hidden_opt`): the verify-final
hidden corresponds to verify position D — the prediction context for the
bonus / residual token — NOT the hidden of the LAST ACCEPTED token (which
is bonus / residual itself, whose own hidden the verify pass never
computes). Feeding position D's hidden as `prev_hidden` to the next
cycle's first MTP draft is a semantic mismatch against the MTP head's
training contract; on qwen3.5-4b bf16 / M3 Max at 200 tokens, depth=3,
chained drafts collapse mean acceptance from ~1.5 → ~0.8 tokens/cycle
and decode tok/s drops from 2.21 (pre-W6.5, 0.30x ratio) to 1.43 (chained,
0.19x ratio). Parity still passes byte-exact at T=0 in both modes because
verify (= main model) is the ground truth and the residual sampler is
deterministic.

A correct chained design needs either (a) the verify FFI to return ALL
D+1 per-position hiddens so Rust can pick verify_hidden[K] after
acceptance, OR (b) a one-token main forward of the residual / bonus to
compute the right `prev_hidden`. Both belong to a follow-up workstream
(likely W6.7's batched verify rewrite).

Test results:
* `cargo test -p mlx-core --lib`: 1466 passed, 0 failed.
* `cargo test -p mlx-paged-attn --lib`: 103 passed, 0 failed.
* `cargo clippy --all-targets -- -D warnings`: clean.
* `cargo fmt --check`: clean.
* `vp lint --type-aware --type-check`: 6 pre-existing warnings, 0 errors.
* `vp run test`: 1240 passed; 6 pre-existing failures in
  `__test__/utils/dataset.test.ts` (missing local GSM8K data file, also
  fail on the parent commit — verified via `git stash` + rerun).
* `oxnode examples/qwen35-mtp-smoke.ts qwen3.5-4b --depth 3 --max-tokens 200`:
  PARITY OK (1256 chars identical); MTP=2.44 tok/s vs AR=8.12 tok/s,
  ratio 0.30x — matches the pre-W6.5 baseline, no regression.
* Same smoke with `MLX_MTP_CHAINED_CYCLES=1`: PARITY OK; MTP=1.43 tok/s,
  ratio 0.19x — confirms the opt-in chained path executes correctly but
  regresses perf per the diagnosis above.

W6.5 perf gate (>=0.6x ratio AND >=15% wall-time drop) is NOT met by the
chained path as currently designed; the additive scaffolding is shipped
so W6.6 / W6.7 can build on it once the position-K hidden export lands.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
…idden[K]

The W6.5 scaffolding (7230b8b) shipped the *_with_hidden FFI exporting
only the LAST verify iteration's `g_last_hidden` (position D), then
disabled chained cycles by default because that position only matches
the next cycle's prediction context when ALL drafts are accepted.
Partial-accept cycles fed from position D collapsed mean acceptance
from ~1.5 to ~0.8 tokens/cycle and regressed perf 0.30x -> 0.19x.

This commit fixes the bug:

1. C++: the dense/MoE verify closures now capture `g_last_hidden`
   (resp. `g_moe_last_hidden`) AFTER every per-step forward and
   concatenate into a `[1, D+1, hidden_size]` tensor returned alongside
   the `[1, D+1, vocab]` logits. The `*_with_hidden` FFI surfaces
   `out_hiddens` instead of `out_last_hidden`.

2. Rust: `run_mtp_cycle_inner` slices `verify_hiddens[:, K, :]` after
   the accept loop computes K (= number of accepted drafts) and returns
   that `[1, 1, hidden]` slice as the third tuple slot. This is the
   correct prediction context for the committed token at position K+1
   (bonus on full-accept, residual on rejection), matching the MTP
   head's training contract `MTP(h_t, embed(t+1)) -> logits at t+2`.

3. Macro: chaining is now DEFAULT ON. The env flag flips from opt-in
   (`MLX_MTP_CHAINED_CYCLES=1`) to opt-out (`MLX_MTP_NO_CHAINED_CYCLES=1`)
   for bisecting / baselining. The chained-path reshape from
   `[1, hidden]` to `[1, 1, hidden]` is dropped — the slice already
   delivers the right shape.

Test results (qwen3.5-4b bf16 / M3 Max, 200 tokens, depth=3):
- `cargo test -p mlx-core --lib`: 1466 passed, 0 failed.
- `cargo clippy --all-targets -- -D warnings`: clean.
- `cargo fmt --check`: clean.
- `vp lint --type-aware --type-check`: 6 pre-existing warnings, 0 errors.
- `vp run test`: 1240 passed; 6 pre-existing GSM8K dataset failures.
- `oxnode examples/qwen35-mtp-smoke.ts qwen3.5-4b --depth 3 --max-tokens 200`:
  PARITY OK (1256 chars identical); MTP=1.40 tok/s vs AR=6.88, ratio
  0.20x.
- Same smoke with `MLX_MTP_NO_CHAINED_CYCLES=1`: PARITY OK; MTP=2.25
  tok/s, ratio 0.30x.
- Same smoke at depth=1 (chained default): PARITY OK; ratio 0.31x.

The fix is SEMANTICALLY correct (parity holds, slice picks the right
position) but does NOT meet the W6.5 perf gate of >=0.6x at depth=3.
Chained path is 38% slower than the opt-out Step-A path despite
skipping Step A's main-model forward each cycle. The overhead is
likely the per-position hidden capture in the verify graph (D+1
reshape + concatenate nodes) plus extra graph dependencies on the
verify's `final_norm` outputs that force re-materialisation each
cycle. At depth=1 the chained overhead is negligible (~0.31x matches
non-chained baseline), so the regression scales with D. A follow-up
perf workstream (W6.6 / W6.7) should investigate either (a) capturing
only the K-th hidden inside the verify closure instead of all D+1, or
(b) the batched-verify rewrite that builds verify as a single compiled
graph rather than D+1 sequential per-step forwards.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
…g W6.7

The position-K slice fix (2322841) is semantically correct (parity holds
byte-exact at T=0 in both modes) but the per-cycle per-position hidden
capture inside a loop of D+1 sequential forwards adds graph-evaluation
overhead that scales with D, regressing the chained path 0.30× → 0.20×
at depth=3 vs. the Step-A baseline. At depth=1 the cost is negligible.

W6.7 will collapse the D+1 loop into ONE compiled verify graph emitting
[1, D+1, hidden] natively, at which point chaining becomes profitable
and we flip this default back to ON. Until then, ship the scaffolding +
correctness so users don't see a regression by default. The chained
path stays opt-in via MLX_MTP_CHAINED_CYCLES=1 for testing.

Smoke: PARITY OK (1256 chars identical); ratio 0.29× matches pre-W6.5
baseline. No user regression.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Replaces the W6 Bug #4 K+1 main-model forward replay path on every
partial-accept verify cycle with a fused Metal kernel that records GDN
innovations during verify and replays only the accepted prefix into the
pre-verify snapshot state. Ported from DFlash's `_gated_delta_tape_kernel`
+ `_tape_replay_kernel` + `RecurrentRollbackCache.rollback()` orchestration.

Dense path only this commit. MoE remains on the K+1 path (its compiled
graph would need extra outputs to surface the per-step tapes — deferred).
Qwen3.5-4b parity gate target is dense, so MoE doesn't block W6.6.

Algorithm:
  1. `mlx_qwen35_compiled_snapshot_linear_caches()` snapshots GDN
     conv_state + recurrent_state + main offset BEFORE verify (already
     existed from Bug #4 fix).
  2. `mlx_qwen35_compiled_tape_arm()` (NEW) flips `g_tape_recording_armed`
     so `qwen35_decode_fn` routes GDN layers through
     `gdn_pure_fn_with_tape` and appends per-step `(tape, k, g, qkv)`
     into per-layer accumulators.
  3. Verify runs D+1 sequential forwards; each accumulates one step.
  4. On partial accept (K < D), `mlx_qwen35_compiled_tape_replay(K+1)`
     (NEW) slices the first K+1 entries from each accumulator and feeds
     them to the `tape_replay` Metal kernel, which applies the recorded
     innovations to the snapshot recurrent_state. Conv state is rebuilt
     by sliding window over `concat(snapshot_conv_state, qkv_recorded)`
     (mirrors DFlash `_rebuild_conv_state`). Offset is advanced to
     `snapshot_offset + (K+1)`.
  5. On full accept, `mlx_qwen35_compiled_tape_disarm()` (NEW) drops
     accumulators without replay — verify already left the state correct.

Files:
  NEW kernels (verbatim DFlash port, scalar-g non-masked variant):
    - crates/mlx-sys/src/metal/gated_delta_step_tape.metal.inc
    - crates/mlx-sys/src/metal/tape_replay.metal.inc
  NEW C++ helpers in mlx_qwen35_common.h:
    - gated_delta_kernel_with_tape_call (3-output kernel wrapper)
    - tape_replay_kernel_call
    - GDNPureResultWithTape struct + gdn_pure_fn_with_tape (forward that
      emits per-step k_tape, g_tape, qkv_tape alongside the standard
      output / conv_state / recurrent_state)
  NEW FFIs in mlx_qwen35.cpp:
    - mlx_qwen35_compiled_tape_arm / _tape_disarm / _tape_replay
  Modified:
    - qwen35_decode_fn routes GDN layers through the tape-emitting helper
      when armed and appends each step's per-layer tensors into globals
    - all 3 dense MTP cycle sites in qwen3_5/model.rs (B=1/standard,
      streaming, chained) wire arm-on-snapshot + replay-or-K+1 dispatch
      based on the env var

Env var:
  MLX_MTP_USE_TAPE_REPLAY=1 (default ON)
  MLX_MTP_USE_TAPE_REPLAY=0 / "false" / "off" → falls back to the K+1
  replay path for parity validation. Read once per process, cached.

Strategy / stash:
  Prior partial attempt (stash@{0}) had the dense plumbing + both Metal
  kernel files already authored. Audited and applied as-is; the kernel
  ports match DFlash byte-for-byte (scalar-g, no-mask variant — the only
  variant our decode path uses). Build was unverified in the stash;
  this commit verifies build + clippy + fmt + cargo test + vp lint +
  vp test + parity gate. MoE work + env-var-removal cleanup deferred
  to a follow-up.

Smoke results (qwen3.5-4b, depth=3, max-tokens=200, M3 Max bf16):
  Parity gate (BOTH modes pass byte-exact at T=0):
    - MLX_MTP_USE_TAPE_REPLAY=1 (default): OK, 1256 chars identical
    - MLX_MTP_USE_TAPE_REPLAY=0 (K+1):     OK, 1256 chars identical
  Perf gate (3-run mean):
    - tape-replay ON:  MTP=2.43 tok/s, ratio=~0.36x  (AR avg 6.77 tok/s)
    - K+1 fallback:    MTP=1.88 tok/s, ratio=~0.30x  (AR avg 6.27 tok/s)
    +29% MTP improvement / +20% ratio improvement vs K+1 baseline.

  Below W6.6 1.8x plan gate. The 0.29→0.36x lift is consistent with the
  plan's ~30% rollback-budget estimate; the remaining gap to 1.8x is
  presumably from non-rollback bottlenecks (W6.7+ workstreams not in
  scope here). Reporting DONE_WITH_CONCERNS on perf.

Bench environment: backupd was in FindingChanges during measurement
(193k changed items pending) and /Volumes/PM9A1 spotlight indexing was
still enabled. Multi-run variance is ±4% on AR baseline; relative
ordering (tape ON > K+1) is consistent across all 3 runs per mode.

Bug invariants preserved:
  - Bug #2 (mid-stream divergence): begin_cycle still re-anchors MTP
    offset every cycle, untouched.
  - Bug #4 (linear cache pollution): snapshot/restore primitives still
    work — tape-replay is an alternative consumer of the snapshot, not
    a replacement for it. Restore is preserved as the fallback path.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Replace the per-depth `g_verify_compiled_by_depth[D]` closure loop in
the dense + MoE MTP verify FFIs with a SINGLE compiled forward over
T = depth + 1 tokens. The prior implementation looped
`mlx_qwen35_forward_compiled` (or `mlx_qwen35_moe_forward`) D + 1 times,
stashing `g_last_hidden` after each call and concatenating per-step
`[1, 1, ...]` slices on axis 1 — D + 1 kernel-launch sequences plus a
graph-evaluation overhead that scaled with D (the W6.5 follow-up flagged
this as the bottleneck blocking chained cycles).

The new path:

* Adds `attn_batched_verify_fn` and `gdn_batched_verify_fn` helpers in
  `mlx_qwen35_common.h`. The attention helper writes T contiguous KV
  slots via `slice_update` over a tail-causal `[1, 1, T, max_kv_len]`
  additive mask (built once per layer-set). The GDN helper feeds T new
  qkv rows through `conv1d` with the pre-verify conv_state and advances
  the recurrent state T steps in one `gated_delta_kernel` dispatch
  (same kernel mlx-lm uses for prefill).

* Adds `qwen35_verify_batched_decode_fn<WithTape>` (dense) and
  `moe_verify_batched_decode_fn` (MoE) compiled graphs. The dense
  graph emits per-layer `(tape, k_tape, g_tape, qkv_tape)` of shape
  `[1, T, ...]` natively when armed via `mlx_qwen35_compiled_tape_arm`,
  letting the W6.6 rollback path consume `slice([:, 0..K, ...])`
  exactly as before — no per-step `concatenate` accumulator append.
  MoE doesn't ship tape-replay (W6.6 deferred MoE).

* Adds two new FFI entrypoints
  `mlx_qwen35_forward_batched_verify` (dense) and
  `mlx_qwen35_moe_forward_batched_verify` (MoE) that own the
  embedding lookup + cache update + offset advance + tape stash for
  one batched verify. The per-depth `g_verify_compiled_by_depth`
  closures in the MTP files now just shape-validate and dispatch to
  these FFIs — the heavy compile lives in
  `compiled_verify_batched_{notape,tape}()` static caches keyed on
  input shape by `mlx::core::compile` itself.

Parity (T=0, byte-exact) passes in three configurations:

* Default (chained-cycles off, tape-replay on): ratio 0.74×
* `MLX_MTP_USE_TAPE_REPLAY=0` (K+1-replay path): ratio 0.56×
* `MLX_MTP_CHAINED_CYCLES=1` (chained on): ratio 0.60×

depth=3 on Qwen3.5-4B M3 Max bf16, 200-token smoke. AR baseline ~7
tok/s; MTP ~5.5 tok/s. The 2.0× perf gate is not met, but every
config improves substantially over W6.6's 0.36× baseline (~+1.4× to
+2.1× depending on flag mix). The remaining gap to AR is dominated by
the 4 forwards per cycle (Step A + D drafts + 1 batched verify); the
batched verify lands the 10–15% verify-stage win the plan estimated.

Chained-cycles stays opt-in (`MLX_MTP_CHAINED_CYCLES=1` to enable). The
batched verify did eliminate the W6.5 follow-up's flagged per-position
hidden-capture overhead, but the chained path still measures slower
than the Step-A path (0.60× vs 0.74×) — likely the per-cycle
`verify_hiddens[K]` slice + eval pulls an extra dependency through
the compiled-graph cache that the Step-A path doesn't pay. Leaving
this as the next workstream candidate (W6.8: fold the chained-hidden
eval into the next cycle's draft trace).

Bench environment: tmutil status=None, mdutil on internal volumes
disabled, top CPU idle ~63%. Numbers are reproducible within ±5%
across runs.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
…del load

W6.7 shipped the batched verify graph but left compilation lazy-at-first-use:
the `static auto fn = mlx::core::compile(...)` initializer in
`compiled_verify_batched_{notape,tape}()` only fires on the first call, so the
first verify cycle of each turn paid the MLX trace+compile cost on the decode
critical path. The per-depth dispatch table `g_verify_compiled_by_depth[5]`
was also populated lazily, allocating a `std::function` slot on first use of
each depth.

This wires an eager prewarm immediately after `init_mtp_compiled_from_main`
returns success on both the dense and MoE paths:

- `mlx_qwen35_prewarm_verify_compiled` (dense, in `mlx_qwen35.cpp`): runs one
  dummy `mlx_qwen35_forward_batched_verify` per (depth ∈ {1..5}, with_tape ∈
  {false, true}) pair (10 total). `mlx::core::eval` is called on the outputs
  to force trace+compile through MLX's shape-keyed cache. Snapshots
  `g_compiled_caches`, `g_offset_int`, `g_compiled_offset`, the tape-armed
  flag, and the four tape accumulators before any dummy call; restores them
  afterward so the main path's KV / offset state is byte-identical to entry.
- `mlx_qwen35_moe_prewarm_verify_compiled` (MoE, in `mlx_qwen35_moe.cpp`): 5
  prewarm calls (no-tape only; MoE tape-replay is deferred per W6.6). Same
  snapshot/restore pattern over `g_moe_caches` and `g_moe_offset_int`.
- `mlx_qwen35_mtp_compiled_prewarm_verify` / `mlx_qwen35_moe_mtp_compiled_prewarm_verify`
  (the MTP-side dispatchers): pre-populate the per-depth closures in
  `g_verify_compiled_by_depth[5]` AND delegate to the underlying prewarm.
  Wired into `init_mtp_compiled_from_main` / `init_moe_mtp_compiled_from_main`
  from Rust.

Best-effort: all prewarm failures are logged to stderr and swallowed —
prewarm is a pure latency optimization, not a correctness gate, so the
verify path falls back to lazy-at-first-use on any failure.

Trade-off: TTFT regresses (~71ms → ~1600ms on the dense smoke at 4b/depth=3
when prewarm is the first turn to hit the compile cache). In exchange, the
first verify cycle no longer compiles. The default-flags decode-tok/s ratio
stays at the W6.7 baseline of ~0.74×.

Smoke (T=0 parity, 200 tokens, --no-warmup):
- default flags:                AR=7.61 MTP=5.67 ratio=0.74× — OK parity
- MLX_MTP_USE_TAPE_REPLAY=0:    AR=7.55 MTP=4.09 ratio=0.54× — OK parity
- MLX_MTP_CHAINED_CYCLES=1:     AR=7.55 MTP=4.64 ratio=0.61× — OK parity

Verification gates:
- `yarn build:native` clean.
- `cargo clippy --all-targets -- -D warnings` clean.
- `cargo fmt --check` clean.
- `cargo test -p mlx-core --lib` 1466 passed.
- `vp lint --type-aware --type-check` 0 errors.
- `vp fmt --check` clean.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
…e TTFT regression

W6.7 follow-up (8bb7aa6) added an eager prewarm of the batched verify
graphs but wired the prewarm call to `init_mtp_compiled_from_main`,
which runs ONCE PER TURN, not once at model load. Result: every MTP
turn re-ran the 10 dummy verify forwards (5 depths x 2 tape variants),
regressing TTFT 22x (~71ms -> ~1600ms) while delivering no extra benefit
beyond the first turn — MLX's internal compile cache is already populated
after the first prewarm fires.

Fix (Option A — minimal C++ change): wrap the body of
`mlx_qwen35_mtp_compiled_prewarm_verify` and
`mlx_qwen35_moe_mtp_compiled_prewarm_verify` in a function-static
`std::call_once` gate. The first invocation (post-init, when
`g_compile_inited` and `g_compiled_caches` are valid) performs the
prewarm work; subsequent invocations return immediately at ~zero cost.

Option A was chosen over Option B (moving the dispatch to a model-load
hook) because:
  - Pure C++ diff, no FFI / Rust changes.
  - The prewarm body already depends on per-turn init having set up
    `g_compile_inited` + `g_compiled_caches`, so it cannot run earlier
    than the first call to `init_mtp_compiled_from_main`. `call_once`
    fits this exactly: first turn runs init + prewarm; later turns run
    init (cheap state setup) and short-circuit prewarm.
  - The `if (!g_mtp_compile_inited) return;` precondition guard sits
    BEFORE `call_once`, so a failing-init test cannot burn the flag
    for a later successful init in the same process.

TTFT before/after (qwen3.5-4b, depth=3, 200 tokens, T=0):

  Pre-fix (8bb7aa6):
    Turn 1 MTP TTFT = ~1600ms
    Turn 2 MTP TTFT = ~1600ms  (REGRESSION — every turn pays the cost)

  Post-fix (this commit):
    Turn 1 MTP TTFT = 1640ms   (pays prewarm once, as designed)
    Turn 2 MTP TTFT =  155ms   (~10.6x reduction, back near baseline)

Parity OK at T=0: AR and MTP produce identical 1256-char output.

Verification gates (from worktree dir):
  - `yarn build:native` clean.
  - `cargo clippy --all-targets -- -D warnings` clean.
  - `cargo fmt --check` clean.
  - `cargo test -p mlx-core --lib` 1466 passed, 0 failed.
  - `vp lint --type-aware --type-check` 0 errors.
  - `vp fmt --check` clean.
  - Smoke parity gate (`--no-warmup` and with-warmup): OK.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
… prewarm flag

Issue 1 — exception-leak window in batched verify FFI

  `mlx_qwen35_forward_batched_verify` (mlx_qwen35.cpp:839-840) and the
  MoE mirror (mlx_qwen35_moe.cpp:1182-1183) both wrote two heap `array`
  pointers directly to the caller's out-params:

    *out_logits  = new array(outputs[...]);
    *out_hiddens = new array(outputs[...]);

  If the SECOND `new` throws (`std::bad_alloc` under OOM), the catch
  block zeroes the out-pointers but never `delete`s the first heap
  array — silent leak. Fix: stage into local `array*` and only commit
  to out-pointers after BOTH allocations succeed; the catch path now
  deletes the partial allocation before rethrowing.

Issue 2 — reset path drops dispatch table but not the prewarm flag

  `mlx_qwen35_mtp_compiled_reset` (mlx_qwen35_mtp_compiled.cpp:864-872)
  and the MoE mirror clear `g_verify_compiled_by_depth[]` but the
  static `std::once_flag prewarm_once` inside
  `mlx_qwen35_mtp_compiled_prewarm_verify` stayed flipped. After a
  reset+re-init, the prewarm short-circuits via `call_once` and the
  closure table stays null. Verified via inspection of
  `get_or_make_verify_fn` (line 382-388): it IS lazy
  (`if (!slot) slot = make_verify_fn(d);`), so this is a PERF
  regression on reset+re-init (test-isolation) paths rather than a
  correctness bug — but it does defeat the entire purpose of the
  prewarm.

  Picked Option (b): swap `std::once_flag` for `std::atomic<bool>`
  gated by `compare_exchange_strong`. The reset hook now flips it back
  with `store(false)`. 3-line change in each MTP file; namespace-local
  flag stays inside the anonymous namespace next to the other globals.
  Option (a) (placement-new on `once_flag`) is gross UB-adjacent;
  option (c) accepts the regression rather than fixing it.

Files: `crates/mlx-sys/src/mlx_qwen35.cpp`,
       `crates/mlx-sys/src/mlx_qwen35_moe.cpp`,
       `crates/mlx-sys/src/mlx_qwen35_mtp_compiled.cpp`,
       `crates/mlx-sys/src/mlx_qwen35_moe_mtp_compiled.cpp`.

Verification:
  - cargo clippy --all-targets -- -D warnings: clean
  - cargo fmt --check: clean
  - cargo test -p mlx-core --lib: 1466 passed, 0 failed
  - vp lint --type-aware --type-check: 6 pre-existing warnings, 0 errors
  - vp fmt --check: clean
  - oxnode examples/qwen35-mtp-smoke.ts (3 flag combos): all 3 print
    `OK: AR and MTP produced identical output` — byte-exact parity holds.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Brooooooklyn and others added 5 commits June 2, 2026 18:49
MTP acceptance is prompt-gated, so the bench prompt selects the regime.
Parameterize the previously-hardcoded essay prompt:

- `--prompt` accepts `essay` (default, byte-identical to the old
  hardcoded prose), `counting`, or `code` presets, or a raw string.
- The chosen prompt propagates to spawned children automatically (the
  parent already forwards `...process.argv.slice(2)`), and the label is
  surfaced in the banner and verdict output.

Enables comparing MTP vs AR across prompt classes (prose vs predictable)
without editing the harness per run.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Two issues surfaced by automated PR review (PR #65):

- MoE `--q-mtp` was blocked: `emit_mtp_sidecar` is dense-only (the 4-bit
  MTP sidecar is a dense/MTPLX layout), so for MoE `mtp_sidecar_tensors`
  is always empty — but the guard `quant_mtp != "off" && …is_empty()`
  then errored out for MoE with a misleading "no mtp.* tensors found",
  even though the MTP weights were already quantized inline by
  `apply_mtp_quant_policy`. Scope the empty-sidecar guard to
  `emit_mtp_sidecar` (dense) and add a MoE-specific check that errors
  only when the MoE checkpoint genuinely has no mtp.* tensors.

- `sanitize_qwen35_moe`'s local `is_mtp_key` closure and its sibling
  prefix normalization hand-rolled a strip-chain missing the
  `model.language_model.model.` (VLM-wrapped) prefix, so such a key
  escaped MTP detection and fell through to the LM path (wrong output
  prefix + wrong +1.0 norm shift). Delegate both to the module-level
  `normalize_mtp_prefix`, the canonical handler used everywhere else.

cargo build/clippy/fmt clean; 56 convert unit tests pass.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Codex PR-review P1: the MTP-verify compiled graphs read weights from the
global registry inside the traced closure, and `mlx::core::compile` bakes
those captured arrays into a process-lifetime cache. `mlx_clear_weights()`
on model reload never invalidated them, so a second same-shape Qwen3.5/3.6
checkpoint loaded in the same process would verify speculative tokens with
the FIRST model's weights (silent corruption); the model_id gate does not
help, and the per-turn `*_compiled_reset()` deliberately preserves the
verify tables across turns.

Add `mlx_qwen35_invalidate_compiled_graphs()` which nulls all four verify
dispatch tables (bucket, argmax, sparse, paged) so the next
`get_or_compile_verify_*` re-traces against the live weights — correct
regardless of thread (slot-nulling forces a fresh `compile()` with a new
fun_id; we do NOT rely on the thread_local `compile_clear_cache`). Call it
from both the dense and MoE weight-registration paths, immediately after
`mlx_clear_weights()` and inside the existing `COMPILED_WEIGHTS_RWLOCK`
write section so no in-flight compiled read overlaps.

Validated: yarn build:native clean; single-model MTP smoke unchanged
(acc 0.70/cycle, coherent); two-model bleed test (nvfp4-27b then bf16-27b
in one process) confirms model B re-traces with its own weights (acc 1.00,
coherent) instead of inheriting A's.

Function-local `static compile(...)` graphs cannot be slot-nulled and are
left as documented `TODO(mtp-reload)` gaps (notably
`compiled_moe_verify_batched`, the MoE analog) for a follow-up.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…parable accept-rate metric

Convert/load alignment (one converted checkpoint now loads in BOTH engines):
- Add `--q-mtp split` (alias `drafter`) convert mode: emits a body-only
  checkpoint + a separate mlx-vlm-format `qwen3_5_mtp` drafter dir. The MTP
  head stays bf16 even under body quantization, and `format:mlx` metadata
  makes mlx-vlm skip its norm-sanitize so there is no double +1.0 shift.
  Dense + MoE.
- New shared `models/mtp_drafter.rs`: detect a sibling `mtp-drafter/`,
  re-add the `mtp.` prefix, and validate variant (text_config) + required-key
  completeness. Dense + MoE loaders consume it with inline-first precedence,
  so existing inline checkpoints remain byte-identical/unchanged.

Adversarial-review fixes:
- `split` no longer quantizes the MTP head under `--quantize --q-recipe`.
- MoE loader validates the drafter variant + completeness before merge;
  `has_mtp_weights()` is gated on a new `mtp_weights_loaded` flag (it was
  reporting active from config alone -> silent garbage drafting).
- split convert removes stale legacy `mtp.safetensors`/`mtplx_runtime.json`
  so they cannot shadow the freshly-emitted drafter.

Accept-rate metric:
- Add `mtpMeanAcceptedTokensTotal` = accepted_drafts/cycle + 1.0, matching
  mlx-vlm's `(accepted_drafts + rounds)/rounds`, surfaced as the headline in
  the acceptance trace + example harnesses (drafts-only kept alongside).

Test hygiene:
- De-flake `forward_pass_equivalence_tests`: seed the MLX RNG for
  deterministic weights and raise the f32 tolerance to a documented 2e-3
  const (the seq-16 reduction lands at a fixed 9.2e-4; the prior 1e-4 was
  below the f32 reduction-order noise floor).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Post-rebase fixes required to land the MTP branch cleanly on the
advanced origin/main (#61-#64: lfm2 MoE, E37 prefill opt, drain-on-write
convert). All conflicts during the 84-commit replay were resolved within
their commits; these are the cross-cutting reconciliations:

- convert.rs: origin/main #63 changed `save_safetensors` to drain its
  argument (`&mut`, drain-on-write). The MTP sidecar + split-drafter
  writers borrow their tensor maps immutably and the sidecar reuses its
  map afterward (its `is_empty()` gates config metadata), so drain a
  small clone instead of the original.
- qwen3_5/model.rs: origin/main's E37/E38 last-token prefill slice
  (`forward_with_optional_last_slice`) auto-merged into the SHARED
  `forward_pre_norm_inner`, but that primitive must return the full
  per-position hidden for the MTP prompt-hidden path
  (`chunked_prefill_with_hidden_with_size` re-slices it by chunk
  length). Restored the tested plain-`forward` loop. E37's main win
  (lm_head matmul reduction) is still applied by
  `project_last_logits_from_pre_norm_hidden`; only the negligible eager
  last-layer-MLP slice (E38) is dropped. Kept origin/main's chunk_async
  toggle + our parameterized chunk_size in chunked_prefill.
- lfm2 integration tests (origin/main #64): added the MTP ChatConfig
  fields (enable_mtp/mtp_depth/mtp_adaptive_depth: None) that our branch
  introduced and the new lfm2 test literals lacked.

Verified: build OK; mlx-core 1654 pass / 3 pre-existing Metal-f32 env
failures (sources byte-identical to origin/main); paged-attn OK; clippy
-D warnings clean; fmt clean; typecheck OK; TS 1260 pass / 6 missing
gitignored-GSM8K-fixture failures (present in main checkout).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@Brooooooklyn
Brooooooklyn force-pushed the worktree-research+qwen-mtp branch from 1d5ee94 to b99a493 Compare June 2, 2026 11:17

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b99a493feb

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Resolves the open review threads and the multi-round adversarial findings on
the Qwen3.5/3.6 MTP speculative-decode stack:

- Compiled-graph reload invalidation: route all 8 weight-baking compiled
  graphs through a capturing-lambda helper (compile_resettable_weight_graph)
  so each gets a unique erasable fun_id; null them only on model reload via
  transitive mlx_qwen35[_moe]_mtp_invalidate_compiled_graphs(). Fixes silent
  stale-weight reuse when a 2nd same-arch model loads in one process (free-fn /
  empty-capture compile() targets share a stable fun_id that null can't erase).

- Stochastic MTP accept (T1): draft q / target p now come from
  sampling::sampling_distribution (new mlx_compiled_sampling_distribution FFI)
  so accept/reject + residual resampling match the compiled sampler's draw
  distribution by construction.

- Greedy-temperature predicate: single shared sampling::is_greedy_temperature
  mirroring the C++ GREEDY_TEMPERATURE_EPS (f32) decision bit-for-bit across all
  five Rust gates, closing the f64/f32 boundary mismatch (T just above 1e-6 was
  stochastic to Rust but greedy to C++ after the f32 cast).

- paged->dense-MTP stale flat cache (T2): paged_full_attn_caches_dirty forces a
  one-time full rebuild on the turn transition; cleared only after the history
  commit.

- adaptive-depth drift reprobe (T4): age-based stale_neighbor so the periodic
  reprobe fires again (the saturating sample-count gate had disabled it).

- Wrapper-prefix consolidation: one authoritative longest-first
  strip_wrapper_prefix now backs convert body remap (remap_qwen35_body_key),
  MTP detection, the --quantize pre-quantized-MTP guard, normalize_mtp_prefix,
  reprefix_drafter_key, and normalize_per_layer_key. Fixes triple-wrapped
  (model.language_model.model.*) keys being dropped or mis-remapped to a
  doubled language_model.model.model.* layout.

Validation: cargo fmt + cargo clippy --all-targets -D warnings clean;
cargo test -p mlx-core 1669 pass (3 pre-existing environmental Metal-f32 fails
present on main too); yarn build:native clean; four Codex adversarial-review
rounds -> final clean.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3c2ca6ca47

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread crates/mlx-core/src/convert.rs Resolved
Brooooooklyn and others added 7 commits June 3, 2026 15:52
`save_model_sync` for both Qwen3.5 dense and Qwen3.5-MoE hand-built its
parameter map (embedding / per-layer / final norm / lm_head / vision) and
never read `self.mtp`. But `config.n_mtp_layers` IS serialized into
config.json, so a reloaded checkpoint reconstructs the MTP module from
config, finds the required `mtp.*` tensors absent, sets
`mtp_weights_loaded = false`, and silently disables speculative MTP (only a
`warn!`). This is reachable in production: SFT/GRPO checkpointing calls
`model.saveModel(...)`, so anyone who fine-tunes an MTP checkpoint and
reloads loses the MTP head.

Fix: each MTP module gains `get_parameters()` (emits a SUPERSET of the
loader-required `mtp.*` keys — top-level norms + fc, plus per-layer
attention projections, q/k/v norms, dense-or-MoE MLP, and the two layer
norms) mirroring the per-layer serialization style in `save_model_sync`.
Both save paths extend `params` with these, gated on
`mtp_weights_loaded && mtp.is_some()` (the loaded guard is essential — gating
on `is_some()` alone would serialize a random-init module, since the module
exists from config even when no weights were loaded).

Quant guard: the whole save path is dense/bf16-only — it serializes the dense
`Linear::get_weight()` slot and NaN-validates every tensor via `to_float32()`.
For a quantized MTP head (loaded from `--q-mtp all`/`cyankiwi`) that dense slot
is stale/random; emitting it would write GARBAGE masquerading as a valid bf16
head on reload, strictly WORSE than the current clean-drop. So each module also
gains `has_quantized_weights()` (checks fc + attention + MLP/expert linears via
new `is_quantized()` helpers on `LinearProj`, `MLPVariant`, `Qwen3_5Attention`,
and `SparseMoeBlock`); when set, save skips MTP serialization and warns that the
reloaded checkpoint will run autoregressive-only. `mtp_weights_loaded` alone
does not distinguish quantized vs bf16, hence the explicit check.

Tests: a focused regression in each module's `#[cfg(test)]` asserts
`get_parameters()` is a superset of the shared
`mtp_drafter::missing_required_mtp_keys` required set (the single source of
truth used by the drafter-merge + MoE post-sanitize gates), so the save key
set can never drift below what load needs. Both pass; full mtp suite (82
tests) green; clippy `-D warnings` + fmt clean; `yarn build:native` builds.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…tp.safetensors)

The `mtplx_mtp_quantization.description` written into the output config.json
advertised "Load packed MLX INT4 MTP linears from mtp.safetensors." for the
`all` policy unconditionally. But the `mtp.safetensors` sidecar is emitted only
for dense `qwen3_5` (`emit_mtp_sidecar = quant_mtp != "off" && !is_split &&
model_type == qwen3_5`). For MoE (`qwen3_5_moe`) there is no sidecar — the MTP
linears are quantized in place by `apply_mtp_quant_policy` and stored inline in
the main sharded safetensors. So the description claimed a sidecar that does not
exist on MoE checkpoints.

Branch the description on `emit_mtp_sidecar`:
- `cyankiwi` (dense-only sidecar path) keeps its exact original wording.
- `all` + `emit_mtp_sidecar` (dense) keeps the byte-identical
  "Load packed MLX INT4 MTP linears from mtp.safetensors." wording.
- `all` without a sidecar (MoE) now reads "Load packed MLX INT4 MTP linears
  stored inline in the main safetensors shards."

Nothing reads this `description` field at runtime (write-only operator/tooling
metadata), so this is a cosmetic accuracy fix.

Also corrects the same dense-only sidecar assumption in the `quant_mtp`
doc-comment on `ConversionOptions` in convert.rs, which feeds the NAPI-RS
auto-generated `packages/core/index.d.cts` (regenerated via `yarn build:native`;
hand-editing the generated file would be overwritten).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The MoE MTP load-completeness gates hardcoded DrafterBodyVariant::Moe,
which demands the MoE MLP key schema (mtp.layers.{i}.mlp.switch_mlp.*
+ mlp.gate). But Qwen3_5MoeMTPModule::new builds its MTP DecoderLayer at
fa_idx = max(full_attention_interval - 1, 0) and selects MLPType::Dense
vs MLPType::MoE via config.is_moe_layer(fa_idx). When that layer is
DENSE-flavored — reachable when decoder_sparse_step does not divide
full_attention_interval, or when fa_idx ∈ mlp_only_layers —
get_parameters()/apply_weights() emit dense mtp.layers.{i}.mlp.
{gate,up,down}_proj.weight. The hardcoded-Moe gate then flagged the
complete checkpoint as incomplete → mtp_weights_loaded = false →
speculative MTP silently disabled, even though the head's own
flavor-aware apply_weights would have loaded the dense keys fine.

missing_required_mtp_keys already selects REQUIRED_PER_LAYER_DENSE_MLP
vs _MOE_MLP via body.is_moe(); only the variant passed in was wrong.

Fix:
- Add Qwen3_5MoeMTPModule::mtp_mlp_variant(config) as the single source
  of truth for the MTP MLP flavor, mirroring new()'s is_moe_layer(fa_idx)
  decision.
- Inline post-sanitize gate (qwen3_5_moe/persistence.rs): derive the
  body from mtp_mlp_variant instead of hardcoding Moe.
- Split-drafter merge gate (load_drafter_tensors): decouple the backbone
  variant (gates the drafter's text_config.model_type — must stay Moe for
  a MoE body) from the per-layer MLP flavor (the structural key gate — must
  use the derived flavor). A single conflated variant was wrong in BOTH
  directions: passing Dense would reject the MoE-body text_config, passing
  Moe would reject the dense-flavored keys. Now takes backbone + mlp_flavor.
- Dense loader (qwen3_5): backbone and mlp_flavor are both Dense (no
  experts → MTP layer always dense-flavored). Its own
  missing_mtp_required_weights inline gate is dense-only and correct;
  left unchanged.

No-regression rationale: the validator already supports both schemas; the
canonical decoder_sparse_step=1 MoE-flavored checkpoint still resolves to
Moe via mtp_mlp_variant, so its gate is byte-identical to before. Only the
previously-rejected dense-flavored MoE-MTP checkpoint changes behavior
(now correctly accepted).

Tests: add dense_flavored_moe_mtp_load_gate_uses_derived_variant — builds
a dense-flavored MoE-MTP config (mlp_only_layers = [fa_idx]), asserts
get_parameters() is complete under the derived Dense variant AND that the
old hardcoded Moe variant would have wrongly rejected it (contrast locks
the fix in). Existing canonical superset test still passes. 83 MTP tests
pass; clippy -D warnings + fmt --check clean.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…q-mtp docs

Three completeness/doc fixes to the MoE MTP load gate. None touch the save
side: `Qwen3_5MoeMTPModule::get_parameters` already emits shared-expert keys
and skips quantized heads, so this only strengthens the LOAD gate
(`missing_required_mtp_keys`) to match what `apply_weights` /
`SparseMoeBlock::forward` actually consume, plus a stale-doc sync.

A (high): require shared-expert weights for a MoE-flavored MTP layer. The
shared expert is unconditional — `SparseMoeBlock::new`/`new_quantized` always
build `shared_expert` + `shared_expert_gate`, and `forward`/`apply_weights`
always use them — but `REQUIRED_PER_LAYER_MOE_MLP` listed only the 4
switch_mlp/router keys. A checkpoint missing only the shared-expert tensors
passed the gate and loaded random shared-expert weights, corrupting
speculative decode. Extended to 8 entries (adds
`mlp.shared_expert.{gate,up,down}_proj.weight` + `mlp.shared_expert_gate.weight`).
Updated the `multi_layer_completeness_checks_every_layer` count (12 -> 16) and
added `partial_moe_drafter_missing_shared_expert_rejected`.

B (medium): make the gate dtype-aware for quantized `.scales` companions. The
gate checked only `.weight` presence; the dense loader's `require_mtp_linear`
already requires `.scales` when a `.weight` is `Uint32`, but MoE
`SwitchLinear::set_weight` has no shape/dtype check, so a packed Uint32
`.weight` with a missing `.scales` loaded as silent garbage. For every required
`.weight`, when its array dtype is `Uint32`, also require the sibling `.scales`
(derived via `strip_suffix(".weight")`). bf16/f16 behavior is unchanged. Dtype
read without unwrap (`matches!(.., Ok(DType::Uint32))`), conservative on error.
Added `quantized_weight_missing_scales_rejected` (Metal-guarded).

C (low): sync stale `quantMtp` docs (MoE is inline, not a sidecar; include
`split`). Hand-synced the crate-local `crates/mlx-core/index.d.cts` to mirror
the corrected Rust doc-comment (already correct in `convert.rs` and the
build-emitted `packages/core/index.d.cts`); `yarn build:native` only emits the
packages copy, not the committed crate-local mirror, so it was edited in place.
Updated `docs/cli.md` and `packages/cli/README.md` to distinguish dense
`qwen3_5` (mtp.safetensors sidecar) vs MoE `qwen3_5_moe` (inline, no sidecar),
list `off`/`cyankiwi`/`all`/`split` (alias `drafter`), and reword "sidecar
policy" -> "MTP-quant policy".

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…gate

`missing_mtp_required_weights` (dense Qwen3.5 loader gate) validated the
top-level `mtp.fc.weight` by presence only, while per-layer MTP linears go
through the dtype-aware `require_mtp_linear` (which also requires
`{prefix}.scales` when `{prefix}.weight` is `Uint32`).

`--q-mtp all` affine-quantizes `mtp.fc` (`convert.rs::mtp_quant_decision`,
the `policy=="all" && prefix=="mtp.fc"` arm → 4-bit affine), producing a
packed `Uint32` `mtp.fc.weight`. With the old presence-only check, such a
weight WITHOUT `mtp.fc.scales` passed the gate, then
`Qwen3_5MTPModule::apply_weights` fell into the dense `else if` branch and
called `Linear::set_weight` on the packed tensor → whole-model
garbage/load failure instead of cleanly disabling MTP.

Fix: drop `mtp.fc.weight` from the presence-only top-level array (keeping
only the three norms — `mtp_quant_decision` returns `Skip` for norms, so
they are never quantized and presence is sufficient) and route `mtp.fc`
through `require_mtp_linear` for the same dtype-aware treatment as the
per-layer linears. MoE gate, shared `MTP_LAYER_LINEAR_SUFFIXES`, and
`convert.rs` are untouched.

Adds `fc_uint32_weight_missing_scales_flags_gate` (Uint32 fc weight w/o
scales is flagged; adding scales clears it) and
`fc_bf16_weight_without_scales_is_not_flagged` (bf16 fc needs no scales),
both using the codebase Metal-skip idiom.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…niform 4-bit/gs32)

Two coupled fixes that MUST land together (write side + read side must agree,
else a quantized MoE-flavored MTP reload is corrupt):

Fix 2 (Task 35) — convert quantizes MoE MTP linears.
`is_mtp_layer_quantizable_prefix` (convert.rs) previously matched only the DENSE
per-layer linear suffixes, so under `--q-mtp {cyankiwi,all}` a MoE-flavored MTP
layer's MLP linears (`switch_mlp.{gate,up,down}_proj`, router `mlp.gate`,
`shared_expert.{gate,up,down}_proj`, `shared_expert_gate`) stayed bf16 while the
attention projections were packed. The predicate now ORs the dense set with a new
MoE-flavored set so both flavors quantize their own linears; ORing is universal
(a dense checkpoint has no `switch_mlp.*`, a MoE checkpoint has no `mlp.gate_proj`).
The `head.ends_with('.')` boundary disambiguates the MoE router gate `mlp.gate`
from the dense `mlp.gate_proj` (stripping `mlp.gate` from `...mlp.gate_proj` leaves
`..._proj`, not ending in `.`). `mtp_quant_decision` already returns the uniform
`Custom{4,32,affine}` for any matched prefix — no change.

Fix 3 (Task 36) — MoE loader augments PLQ from mtplx_mtp_quantization.
The dense loader threads `augment_mtplx_mtp_quantization` into `per_layer_quant`;
the MoE loader (`qwen3_5_moe/persistence.rs::load_with_thread`) built the table
from `parse_quant_block` ONLY. Without augmentation, even correctly-quantized MTP
tensors reload with the WRONG PLQ — the router-gate prefixes fall back to the 8-bit
`default_gate_plq` while convert packed them at 4-bit, corrupting the head. The
augmentation is now injected right after `parse_quant_block`, BEFORE both
`apply_weights_moe_inner` (eager) and `register_moe_weights_with_cpp` (compiled),
so both MoE MTP paths resolve the correct PLQ. The suffix set is flavor-derived
from the SAME `mtp_mlp_variant` decision the load-completeness gate uses (a
dense-flavored MoE MTP layer uses the dense suffix list).

Option A (uniform PLQ) rationale: ALL MoE MTP quantizable linears — including the
router gate — are quantized at the single uniform 4-bit/gs32 affine PLQ the dense
MTP path already uses, matching the single-PLQ `mtplx_mtp_quantization` config
block. This keeps that one block sufficient for both produce and reload (a
per-class gate-bits split would require widening the block on both sides). The
augmented per-key override wins over the 8-bit gate default in `effective_plq_for`,
so reload reads back the exact PLQ convert packed. The MTP head is a draft head,
not correctness-critical (the verify forward is always full-precision body), so the
uniform low-bit router gate is acceptable here.

Shared suffix set + drift guard: `MTP_MOE_LAYER_LINEAR_SUFFIXES` is the single
source of truth in `mtp_drafter.rs` (beside `REQUIRED_PER_LAYER_MOE_MLP`), imported
by both the convert predicate and the MoE augmentation. A new drift-guard unit test
(`moe_mtp_linear_suffixes_match_required_moe_mlp`) ties its MoE-MLP entries to
`REQUIRED_PER_LAYER_MOE_MLP` in both directions, so adding/removing a quantizable
MoE MTP linear in one place forces it in the other. The dense augmentation is
refactored into a suffix-parameterized core (`augment_mtplx_mtp_quantization_with_suffixes`)
that the dense wrapper feeds the unchanged dense list — dense behavior is unchanged.

Tests: convert predicate (MoE MLP/router/shared-expert quantized; dense gate_proj
still matched; mlp.gate vs mlp.gate_proj boundary), MoE + dense-flavored-MoE
augmentation, a Metal-gated quantized-apply test proving the router gate /
switch_mlp / shared_expert / attention sublayers install quantized backends under
the augmented (4-bit) PLQ over an 8-bit gate default, and the drift guard. No
.unwrap()/.expect() in changed load/convert control flow.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The Rust eager MoE-MTP load gate derives its MLP flavor from
is_moe_layer(fa_idx) (honors mlp_only_layers + the sparse-step modulo),
but the compiled path's is_moe_layer_mtp only checked num_experts +
decoder_sparse_step — an eager/compiled divergence that could mismatch
mtp.layers.*.mlp.* keys for a dense-flavored MoE-MTP layer. Pass the
precomputed eager flavor bool through the FFI init so both paths agree.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1040f858ea

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Brooooooklyn and others added 2 commits June 3, 2026 19:18
The MTP decode macro unconditionally pushed the prefill-seed token before
the loop's length check, so maxNewTokens/max_output_tokens <= 0 emitted 1
token where the AR decode_loop! (for step in 0..max) emits 0; negative
budgets also wrapped via `as usize` to an effectively unbounded cap. Guard
the initial emit on a clamped `max_as_usize` so MTP matches AR semantics
(0 new tokens, reason "length") for zero/negative budgets. Byte-identical
for maxNewTokens >= 1.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
… bound allocations

Defends every user-reachable token-budget surface against out-of-range
max_new_tokens / max_output_tokens / max_tokens:

- Server: /v1/responses and /v1/messages reject present-and-invalid budgets
  (non-integer, <= 0, or > i32::MAX) with a 400 before any model dispatch,
  via a shared MAX_OUTPUT_TOKENS = i32::MAX const. A JS integer above i32::MAX
  would otherwise pass the positive-int check then truncate via NAPI to a
  negative i32.
- Core: extract_chat_params clamps max_new_tokens to >= 0; the plain-Qwen3
  chat path, VLM, and training with_capacity args clamp likewise; the
  decode_loop_mtp! macro short-circuits a 0 budget to finish_reason "length"
  (AR-equivalent empty completion), never "cancelled".
- generate() APIs (qwen3 / qwen3_5 / qwen3_5_moe) return Err on <= 0 (parity).
- GRPO fails fast (GRPOEngineConfig::validate()) on max_completion_length <= 0
  at engine construction, plus a TS grpo-trainer create() check.
- KV-cache capacity: a shared i64-checked chat_common::kv_capacity_round_up
  replaces ~14 raw `((prefill_len + max_new_tokens + 255) / 256) * 256` sites
  (qwen3_5 dense/paged/VLM + qwen3_5_moe + lfm2). It rounds up in i64 and
  returns a clean Err when the result exceeds i32::MAX, so an accepted budget
  of exactly i32::MAX with a non-empty prompt can no longer overflow the i32
  sum (debug panic / release wrap) before cache init. A saturating variant
  feeds the trace log. MTP-init bool-blocks map the overflow Err to "disable
  MTP, fall back to AR".
- Generated-output buffers: a shared chat_common::generated_capacity_hint
  (floor 0, cap 8192) replaces 28 raw `Vec::with_capacity(max_new_tokens..)`
  hints across qwen3 / qwen3_5 / qwen3_5_moe / lfm2 / gemma4 / qianfan_ocr /
  paddleocr_vl. Vec::with_capacity allocates eagerly, so an accepted i32::MAX
  budget would otherwise reserve ~8 GiB up front (and the unguarded sites would
  abort on a negative budget). The buffer still grows as needed, so the hint
  cap is observable-behavior-neutral for real budgets.

Tests: server 400s (0/-5/1.5/2147483648/MAX_SAFE_INTEGER), GRPO rejects,
qwen3 generate reject, MTP zero-budget == AR baseline, and helper unit tests
for kv_capacity_round_up (boundary/legacy-parity/saturating/floor) and
generated_capacity_hint (cap/floor/passthrough).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8ce853ebc1

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Brooooooklyn and others added 2 commits June 3, 2026 22:32
A negative `ChatConfig.mtpDepth` (reachable via the public surface,
e.g. -1) was cast `i32 as usize` BEFORE clamping, so `-1` wrapped to
usize::MAX and clamped UP to depth 5 — forcing the slowest/deepest MTP
path instead of the documented `<1 → 1`. Clamp the signed value first
(`d.clamp(1, 5) as usize`). Byte-identical for valid depths (1..=5) and
the existing 0/99 cases; adds -1 / i32::MIN regression cases to
depth_clamps_to_verify_ffi_range. Addresses PR #65 codex review.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 32ad4e3. Configure here.

Comment thread crates/mlx-core/src/convert.rs Resolved
…fter block_size

`--q-mtp split` computed the drafter config's `block_size` as
`mtp_num_hidden_layers + 2`, taking the source-config value whenever it
parsed as a number — including a stale/wrong `0`. The tensor-derived
fallback (`distinct_drafter_layer_count`, always >= 1) only ran when the
field was ABSENT, so an explicit `0` emitted `block_size: 2` despite the
extracted drafter weights containing real `layers.{N}` blocks. Filter
`0` (in both text_config and source_config) so it falls through to the
authoritative tensor count. Byte-identical for valid (> 0) configs;
adds a regression test. Addresses PR #65 Cursor Bugbot review.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f35e08094c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

The AR decode loop wraps its streaming callback in
`if p.include_reasoning || !is_reasoning` so that, when a caller sets
`includeReasoning: false` while thinking is still enabled, hidden
`<think>…</think>` deltas are suppressed from the stream. The MTP decode
loop fired its callback at all three emit sites (initial prefill-seed,
main loop, accepted-drafted-token loop) unconditionally, so direct
`chatStream*` consumers received reasoning deltas that the AR path
suppressed. Wrap each MTP `cb.call` in the same gate, keeping the
detokenize + length-advance OUTSIDE the gate (so DecodeStream still sees
every token), exactly mirroring AR.

Byte-identical for the default `include_reasoning: true` (gate is always
true → callback always fires); only the `false` + thinking-enabled + MTP
combination changes, and now matches AR. Addresses PR #65 codex review.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@Brooooooklyn
Brooooooklyn enabled auto-merge (squash) June 3, 2026 16:05
@Brooooooklyn
Brooooooklyn merged commit a90def7 into main Jun 3, 2026
6 checks passed
@Brooooooklyn
Brooooooklyn deleted the worktree-research+qwen-mtp branch June 3, 2026 16:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant