Skip to content

Chat-engine refactor: model-neutral engine (P1–P8) + honor generation_config.json (#38) - #70

Merged
Brooooooklyn merged 95 commits into
mainfrom
worktree-refactor-chat-engine
Jun 22, 2026
Merged

Brooooooklyn merged 95 commits into
mainfrom
worktree-refactor-chat-engine

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Jun 16, 2026 •

Copy link
Copy Markdown
Contributor

Chat-engine refactor — model-neutral engine → paging inversion → compiled coexistence → pure-Rust eager/MTP → declarative convert

Scope. This branch carries the entire chat-engine refactor stacked on main — Phase 1 (engine extraction, S1–S12) plus follow-ups P1–P8, the MTP and vision genericizations, and the #38 generation-config feature: 73 commits, 143 files, +39.5k / −54.0k (net ≈ −14.5k LOC). The phases were developed on one long-lived branch and build on each other, so they cannot be split into separate PRs against main. Opened for review.

Synced with main. Merged origin/main (NVIDIA DGX/CUDA backend #71 + qwen3.5 GDN chunked-ops prefill #72) into the branch — PR is now conflict-free / mergeable. The CUDA additions are Metal-gated, so the macOS path is byte-for-byte unchanged; the only merge work was repointing CUDA's compiled_forward_backend_available() Metal guards from the pre-refactor qwen3_5::persistence_common to the relocated engine::persistence, and keeping both our GDN tape-replay test and #72's new chunked-ops tests.

Why

Adding a new model family cost ~10–17k LOC because the production engine (decode loop, session mgmt, paged-KV, compiled-graph path, MTP) was built inside the first family (qwen3_5/) and copy-forked into each new one. This refactor extracts a model-neutral engine and pushes every production feature behind an engine-owned seam, so a new family becomes a thin backend impl — hence the large net deletion.

Phases on this branch

Phase 1 — extract the model-neutral chat engine (S1–S12). New crates/mlx-core/src/engine/: ChatConfig/ChatResult/ChatStreamChunk types, ChatBackend/DecodeStep traits, generic run_decode_loop, generic session cores + ChatCmd + napi glue, compiled locks, persistence helpers. All five families (qwen3, qwen3_5 dense, qwen3_5_moe, gemma4, lfm2) migrated onto it; legacy per-family chat machinery deleted (grep-gated).

P1–P3 — engine seams. ThinkingPolicy + ChatML delta single-source-of-truth; paged-turn lifecycle dedup via a PagedTurnPlan adapter.

P4 — paging inversion (engine::run_paged_turn<B: PagedBackend>). The default paged auto-regressive whole turn now flows through one generic engine path + run_decode_loop for all five families, behind a paged-forced byte-equivalence gate.

P5 — per-model-id compiled slot map. Replaces the single process-global g_active_model_id gate over the C++ compiled-decode state with per-model-id slot maps, so two compiled models coexist in one process instead of the 2nd load silently demoting the 1st to eager. Includes the MTP draft/commit-graph residency owner-guard and a deadlock fix on the per-Inner Drop.

P6/P7 — delete the C++ compiled forwards, go pure-Rust. Removed the qwen3_5 dense + MoE C++ compiled forward paths (~9.4k LOC + 104 FFI externs) in favor of a pure-Rust eager forward and a pure-Rust eager MTP (drafter + batched verify + accept/rewind + a Rust GDN tape for bit-exact acceptance). AR eager == former compiled (parity); eager MTP keeps committed-history acceptance. lfm2/gemma4 compiled paths preserved. A hard perf gate (eager-MTP must not regress vs compiled-MTP) was enforced.

P7 (collapse) — TS / NAPI / Cmd / training. 6 streaming wrapper classes → one makeStreamingModel factory + MODEL_REGISTRY; 35 hand-written #[napi] chat methods → one chat_napi_surface! decl-macro; per-family training enums → engine::cmd::TrainCmd + handle_train_cmd<B> (+ 12 fallible AdamW-apply unwrap → ?).

P8 — declarative convert (ConversionRecipe registry). Collapsed the 7 scattered per-family convert.rs dispatch sites into one recipe_for(model_type) registry; e2e mlx convert output is byte-identical (sha256) for qwen3_5 / lfm2 / privacy-filter.

#38 — honor generation_config.json defaults engine-wide (vLLM out-of-box). When a request leaves a sampling field unspecified it falls back to the checkpoint's generation_config.json, and that file's eos_token_id list merges into the per-turn stop set. Precedence request > generation_config > sampler builtin; eos is a union (never an override). Default-ON. index.d.cts unchanged (defaults live on each Inner).

MTP genericization — engine::run_mtp_turn<B: MtpBackend> + run_mtp_cycle<S: MtpStepper>. Continuing P4's inversion for speculative decoding: the MTP whole turn and its propose / verify / accept-or-rewind cycle moved off the per-family decode_loop_mtp! macro onto one engine-owned generic path. qwen3_5 dense (flat sync, flat streaming, paged) and qwen3_5_moe (flat) all run it; the now-dead decode_loop_mtp! macro + MtpOps closure-bundle were deleted. Per-family T=0 byte-identity gates; the macro's unit tests were migrated to the live engine path — Codex caught a real dense accept_with_residual (T=1.0 dense-accept) coverage gap the migration had dropped, fixed with exact-one-hot deterministic tests.

Vision merge-contract genericization — engine::vision::{VisionMerge, run_vlm_prefill_layers}. The qwen3.5 dense + MoE image-prefill already shared the vision encode + image-feature merge + M-RoPE step (one free fn); its last forked piece — the prefill layer loop — is now unified behind an engine-owned VisionMerge DTO + a VlmPrefillLayer trait (associated cache type, so each family keeps its distinct layer cache) + one generic run_vlm_prefill_layers. The sole divergence (dense relies on the attention layer's internal causal SDPA; MoE passes an explicit causal mask) is now a parameter, not a forked loop. gemma4 stays on its own core — it is structurally disjoint (masked_scatter + 4D mask, no M-RoPE) and even rejects a text delta on an image session. Env-gated T=0 image-chat goldens are byte-identical before / after for both dense (Qwen3.5-4B) and MoE (Qwen3.6-35b-a3b).

Docs & examples

  • Docs: ModelGenerationDefaults rustdoc now documents the full generation_config.json vs config.json override order (sampling ladder + eos union + raw-generate()/Gemma4 divergences).
  • Examples cleanup: removed ~30 internal debug/probe/microbench/perf-A-B/smoke scripts (incl. the grpo/validation/** real-API subtree); examples/ now keeps only user-facing examples — inference (lm.ts), VLM (vlm-inference.ts), OCR (paddle-ocr-pipeline.ts), tool-use (tool-use-example.ts), and the GRPO/SFT GitHub-tool training example. Reference-safe (yarn typecheck + lsp.test.ts 75/75 green; dead package.json bench scripts + doc references pruned).

Verification

  • cargo test -p mlx-core --lib green (only the 2–3 pre-existing Metal-f32 failures, documented; on code paths byte-identical to origin/main) · cargo test -p mlx-paged-attn green.
  • Per-family real-checkpoint parity at each P4/P5 step (paged-vs-flat byte-identical); P6/P7 AR eager==compiled + eager-MTP acceptance parity; P8 byte-identical convert; feat: add Qianfan-OCR #38 real-checkpoint smoke + 11 unit tests.
  • clippy --all -D warnings + cargo fmt --check clean · yarn build:native ok · packages/core/index.d.cts byte-stable · yarn typecheck + TS lint clean.
  • Post-sync re-gate on the merge commit: build + clippy -D warnings + fmt --check clean; mlx-core lib 1775 pass; the merged gated_delta module runs both the GDN tape-replay test and perf(qwen3.5): CUDA GDN chunked-ops prefill (~1.3–1.75× TTFT, all Qwen3.6 classes) #72's chunked-ops tests (7/7).
  • MTP + vision genericization: per-family T=0 byte-identity goldens green before / after; mlx-core lib 1796 pass / 3 pre-existing Metal-f32; Codex adversarial-review approve (no material findings) on both.
  • Adversarial (Codex) review on each landed phase (all approve / findings fixed).

Post-review follow-ups & CI

  • Open review threads resolved (3/3), each verified against real control flow first: restored the native config constructor on the streaming wrappers (ConstructorParameters<C> — new Gemma4Model(config) / new QianfanOCRModel(config) type-check again); reinserted the .biases sidecar on the vision-dequant fallback so a failed dequant can't emit a corrupt affine quant group; the gemma4 paged-cap flag was confirmed not a regression (the clamp was intentionally converged onto the shared engine contract — the KV pool is sized to max_position_embeddings and record_tokens rolls back on exhaustion, so over-budget turns abort cleanly rather than overrun).
  • Rust Lint fix: moved the VlmPrefillLayer impl above the test module (clippy::items-after-test-module, a --all-targets-only lint that the local --lib check missed).
  • Removed T=0 parity scaffolding (scripts/t0-smoke.sh + its env-gated Rust capture harnesses, −1.6k LOC): dev-only, never ran in CI, and the refactor it verified has landed. Kept the real CI coexistence test.
  • Gated heavy model E2E, folded into ci.yml to reuse the single Build: real-checkpoint tests run as a label-gated model-test job inside .github/workflows/ci.yml that reuses the build job's mlx-node + mlx-metallib artifacts — no second native build (the original standalone model-e2e.yml duplicated the entire build job verbatim). A per-family matrix downloads the smallest checkpoint (qwen3 0.6B · qwen3.5 dense 0.8B · lfm2 1.2B · gemma4 E2B) and runs that family's self-referential --ignored parity/session tests (paged≡flat, reset/replay determinism, session warm-reuse, greedy MTP≡AR — no host-specific golden). Runs only on main pushes, workflow_dispatch, or a PR labeled model-e2e — keyed on the label that fired the event, so adding an unrelated label to an already-labeled PR is a no-op. On a model-e2e label event only build + model-test run (the regular test/lint already ran on the PR's push). qwen3.5 MoE is excluded (no checkpoint below 35B-A3B).

🤖 Generated with Claude Code


Note

High Risk
The declaration file removes and reshapes large parts of the public @mlx-node/core API (chat, Qwen3 paged paths, training hooks), and publish now gates on optional E2E—both affect consumers and release flow.

Overview
Adds a model-test CI job inside ci.yml that reuses the build artifacts, downloads small real checkpoints per family (qwen3, qwen3.5 dense, lfm2), and runs #[ignore] parity/session tests when pushing to main, on workflow_dispatch, or when a PR carries the model-e2e label—with guards so unrelated label events do not re-run the full test/lint suite. Publish now depends on model-test succeeding (or being skipped) so a failed E2E leg blocks release.

Regenerates packages/core/index.d.cts to match the refactored native surface: unified ChatConfig / ChatResult / ChatStreamChunk, session + streaming entry points on model classes, ChatStreamHandle, block-paged cache helpers, expanded GRPO/SFT engine factories, and new exports (Gemma4, LFM2, Harrier, PrivacyFilter, QianfanOCR, ResponseStore, profiling/memory helpers). Several legacy Qwen3 paged-attention and in-process chat()/forward APIs are removed from the typings in favor of model-thread session APIs.

Small follow-ups: Gemma4 loader test asserts transitive subclass via makeStreamingModel; README TUI example points at train-github-tool.ts.

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

Brooooooklyn and others added 30 commits June 12, 2026 02:10
Add check_metallib_canaries() to scripts/t0-smoke.sh — runs 4 fast
behavioral tests (<1 s total) at the start of both capture and compare.
Aborts with a loud remediation message if any fail, since the locally-
built mlx.metallib nondeterministically drops kernel symbols and produces
garbage output without any build error.

Re-captured coherent baselines for all 5 families at HEAD fd0bef1:
  qwen3 (0.6B)       — 64 reasoning tokens, text="" (thinking truncated,
                        deterministic via num_tokens + cached_tokens)
  qwen3_5 (0.8B)     — coherent thinking trace about Paris/European capitals
  gemma4 (2B)        — "Paris" / "Berlin" / "Rome" (crisp 1-word answers)
  lfm2 (1.2B)        — coherent thinking trace about Paris
  qwen3_5_moe (35B)  — coherent thinking trace about Paris

Two consecutive compares pass 5/5. Full suite: 1755 passed / 3 failed
(known f32-tolerance) / 42 ignored.

Co-Authored-By: Claude Fable 5 <[email protected]>
…eview fixes)

Finding 1 (vacuous pass): all 5 families are now REQUIRED in both capture
and compare. Missing model path → loud FATAL + nonzero exit. Missing/empty/
malformed digest after cargo run → FATAL + exit. Stale current-run dir is
wiped at the start of every compare. Missing baseline in compare → hard
error. Optional escape hatch: MLX_SMOKE_ALLOW_SKIP="fam1 fam2" (prints
prominent WARNING; a skipped family with an existing baseline is also a
hard error to prevent silent gate holes). run_family no longer has a soft
"return 1 on skip" path unless the family is in the allow list.

Finding 2 (digest lacks token identity): include_reasoning switched from
Some(false) to Some(true) so raw_text carries the full decoded output
including thinking tokens. result_digest now includes thinking,
prompt_tokens, reasoning_tokens, and tool_calls in addition to the existing
fields. Option (c) chosen: no new model accessor needed — at T=0 same token
IDs ↔ same decoded bytes, so raw_text is the token-identity signal. The
existing parity tests likewise compare text/raw_text. New doc comment
explains the choice.

Co-Authored-By: Claude Fable 5 <[email protected]>
…qwen3_5/mtp_decode.rs

Pure code motion — engine/chat_common.rs (6662 lines) is split into
focused modules, items moved verbatim with their docs and tests:

- engine/params.rs: ChatParams + extract_chat_params, resolve_* thinking
  helpers, default thinking-budget helper, kv_capacity_round_up(+_saturating),
  generated_capacity_hint, ChatML delta-text builders
- engine/penalties.rs: apply_all_penalties, ReasoningTracker
- engine/finalize.rs: compute_performance_metrics, parse_thinking_and_tools,
  finalize_chat_result, raw_text_with_reasoning_suppressed, send_stream_error
- engine/cache.rs: verify_cache_prefix_direct (GDN all-or-nothing contract
  rustdoc kept verbatim), save_cache_state_direct/_after_delta, rope-delta
  gates, image cache-key helpers, IMAGE_CHANGE_RESTART_PREFIX
- engine/decode.rs: DecodeOps + decode_loop! (transitional, replaced in S5),
  should_propagate_compiled_paged_error, and the mtp_trace_logits/trace_top2
  helpers that also serve the AR trace diagnostics
- models/qwen3_5/mtp_decode.rs (NEW): MtpOps, run_mtp_cycle_inner,
  decode_loop_mtp!, and the MTP-only cached env-flag readers — MTP stays
  family-specific in phase 1

engine/chat_common.rs is deleted; engine/mod.rs flat-re-exports the new
submodules and the qwen3_5 chat_common shim now globs crate::engine::* +
super::mtp_decode::*, so every existing importer keeps compiling unchanged.
$crate:: paths inside decode_loop!/decode_loop_mtp! repointed accordingly.
Test inventory balanced: 78 tests before == 78 after, all green.

Co-Authored-By: Claude Fable 5 <[email protected]>
Replace Bash-4-only `declare -A` associative arrays with per-family
scalar variables (res_*/rr_*) plus case-dispatch in the summary loops.
Also replace `${family^^}` uppercase expansion with `tr 'a-z' 'A-Z'`.
All gate semantics preserved: mandatory 5-family coverage, hard exits,
digest validation, canary precheck, MLX_SMOKE_ALLOW_SKIP escape hatch.

Co-Authored-By: Claude Fable 5 <[email protected]>
New engine/backend.rs:
- DecodeStep trait (forward / eval_step / trace_offset) generalizing the
  DecodeOps closure pair; the turn-constant embedding_weight parameter
  moves into the impl (captured at begin_decode).
- ChatBackend trait — the per-family seam the S6 session cores will
  drive; every method's doc maps it to the per-family function it
  generalizes. verify_cache_prefix documents the GDN all-or-nothing
  contract by reference to engine/cache.rs::verify_cache_prefix_direct.
- ChunkSink trait unifying the StreamSender(StreamTx) mpsc wrappers and
  the raw ThreadsafeFunction sink (both expose .call(result, mode)
  today); impls provided for both concrete sinks.
- Support structs: ThinkingSetup, SaveStateArgs (union of
  save_cache_state_direct / save_cache_state_after_delta /
  Lfm2Inner::save_cache_state inputs), TurnSetup (minimal fields the
  compiled/eager decode-setup blocks actually read), WholeTurnArgs +
  TurnOutput for the paged/mtp/vision whole-turn overrides.

engine/decode.rs:
- run_decode_loop<S: DecodeStep>(step, DecodeLoopArgs, Option<StreamingCtx>)
  — faithful port of the decode_loop! macro body (macro stays until S12).
  Exactly two intended behavior differences: (a) the every-32-step trace
  uses step.trace_offset() (None skips the line) instead of hardcoding
  mlx_qwen35_get_cache_offset(); (b) ChatStreamChunk referenced directly
  from engine::types.
- Mock tests: scripted MockStep driving T=0 argmax pins EOS stop,
  repetition cutoff, ReasoningTracker budget forcing (forced </think>
  lands after the in-flight pipelined token), include_reasoning=false
  streaming suppression with detok still advancing, reasoning-tagged
  streaming, and a 400-step run through the 256-step cache-clear cadence.
  verify_cache_prefix_direct semantics were already pinned by
  engine/cache.rs's verify_cache_prefix_invariant_tests (no new test
  needed).

Deliberate deviations from the plan sketch (derived from real call
sites):
- ChatBackend::reset_caches returns Result<()> — Qwen3.5's
  reset_caches_sync is fallible; an infallible signature would force a
  panic path.
- StreamingCtx carries the raw &tokenizers::Tokenizer (what the macro
  reached via $tok.inner()) so mock tests don't need a full
  Qwen3Tokenizer; call sites pass qwen3_tokenizer.inner().
- begin_decode uses the elided Self::Decode<'_> form
  (clippy::needless_lifetimes).
- Whole-turn overrides return Option<Result<TurnOutput>> where
  TurnOutput = Complete(Box<ChatResult>) | Streamed, mirroring the two
  real return shapes (chat_sync_core_paged -> Result<ChatResult>,
  chat_stream_sync_core_paged -> Result<()> with sink-delivered output);
  Boxed for clippy::large_enum_variant.
- Dead-code allows: module-level on backend.rs; item-level (same
  marker comment) on the new decode.rs items, since decode.rs also
  hosts live code that must keep dead-code analysis.

Co-Authored-By: Claude Fable 5 <[email protected]>
Qwen3's chat-session surface (start/continue/tool + streaming twins +
reset) now runs on the model-neutral engine: Qwen3Inner implements
ChatBackend + DecodeStep, Qwen3Cmd nests the 7 chat commands as a
single Chat(engine::ChatCmd) variant beside the untouched
training/generate variants, and the NAPI methods are thin shims
(signatures, doc comments, ts_args_type byte-stable; streaming wired
via engine::napi_glue::start_chat_stream).

Moved, not duplicated: the block-paged whole-turn cores
(chat_sync_core_paged + chat_stream_sync_core_paged and their inners)
relocate verbatim behind the paged_turn probe — the dominant
default-ON production path is preserved byte-exactly. The streaming
paged core's only mechanical change is messages->tokens (the engine
renders the identical jinja prompt) and StreamSender->ChunkSink.

Deleted (replaced by the generic session cores + run_decode_loop):
chat_sync_core, chat_stream_sync_core, chat_session_*_sync,
chat_tokens_delta_sync, chat_stream_tokens_delta_sync(_inner),
pump_stream_to_callback, StreamSender (-1682 net LOC).

Hook overrides reproduce qwen3 behavior exactly: <|im_end|> session
EOS, template-honoring thinking setup, "Tokenizer not loaded" /
delta-guard strings, wired_limit_bytes()=None (qwen3 never created a
WiredLimitContext), streaming-delta prompt_tokens = full history+delta,
profiler labels qwen3_chat_stream[_delta] with the _rust relabel at
begin_decode, paged sync GenerationConfig defaults (temp 0.7 / top_p
0.9) rebuilt inside paged_turn. The flat exact-prefix-match rewind is
expressed via the sanctioned pure-KV exception: verify_cache_prefix
returns cached_len-1 on exact match and arms a rewind flag flat_prefill
consumes (cache_idx-1 re-forward of the final token).

ONE SANCTIONED BEHAVIOR FIX: streaming-delta turns now route through
the same paged_turn probe as sync deltas. Legacy qwen3 had no paged
dispatch on chat_stream_tokens_delta — with the paged adapter ON (the
default) the flat inner cloned the never-populated flat KV vectors and
forward_fused read num_layers KV pointers from a zero-length vec
(latent out-of-bounds UB). Streaming deltas now run the paged pipeline
by construction (documented at paged_chat_turn).

Documented accepted non-default-config divergences (panel-reviewed,
flat opt-out path only): legacy flat SYNC loops' penalty-context
off-by-one / ignored thinking budget / temp 0.7-0.9 defaults align to
the macro semantics qwen3's own streaming paths already used;
stream-start im_end guard wording collapses to the trait message;
the qwen3.5 cache-offset trace line drops (trace_offset None).
No engine-side changes were required.

Gates: cargo test -p mlx-core --lib (1781 passed; only the 3 known
pre-existing f32 banded-attn/attention-vjp failures; metallib canaries
green), clippy --all-targets -D warnings clean, cargo fmt --check
clean. NAPI surface byte-stable (no index.d.cts change).

Co-Authored-By: Claude Fable 5 <[email protected]>
…gine

Collapse the six qwen3_5 dense chat Cmd variants + ResetCaches into
Qwen35Cmd::Chat(ChatCmd) routed through engine::cmd::handle_chat_cmd,
with ChatBackend + DecodeStep implemented on Qwen35Inner. The compiled
C++ decode entry (lifecycle mutex -> weights rwlock -> model-id recheck
-> graph seeding -> CompiledResetGuard), MTP speculative cores, vision
turns, and block-paged cores are kept verbatim behind whole-turn
override probes; only the generic text/non-paged/non-MTP flow runs the
neutral decode loop. NAPI signatures, docs, and ts_args_type are
byte-stable; training/Generate/SaveModel variants untouched; qwen3_5_moe
left for S9.

Co-Authored-By: Claude Fable 5 <[email protected]>
Gate 4 — qwen3_5_delta_chat::stream_session_path_keeps_ttft_flat_across_turns:
NOT an S8 regression. The legacy dense streaming-delta path has reported
prompt_tokens as the per-turn DELTA count since PR #48; the test (cumulative
growth) fails IDENTICALLY (17 -> 16, 14, 16) on pre-S8 e4eee4a~1 — verified
empirically by reverting model.rs and rerunning. The S8 engine default
faithfully reproduced the legacy payload; the test contract was simply never
exercised (env-gated, unset until this gate). Fix: qwen3_5 dense ChatBackend
now overrides stream_delta_prompt_tokens -> full history+delta length,
matching its own sync delta result, its paged streaming core, and every
other family. Engine default (delta count) is unchanged so the un-migrated
MoE keeps today's payload until S9; doc comments updated to record the new
state. Test now passes: 17 -> 96 -> 173 -> 252, 7/7 suite green.

Gate 3 — lfm2 T=0 smoke nondeterminism (turn_2/turn_3, ~2/5 runs):
Root cause is a CPU-side read race in the FFI scalar readers, not a logits
or engine divergence. mlx_array_item_at_{float32,int32,uint32} dereferenced
array::data<T>() with no eval/event-wait; after MxArray::async_eval_arrays
the buffer exists but the GPU may not have finished writing it. lfm2's flat
double-buffered delta loops hit the window at exactly two steps where no
graph encoding separates the async_eval from the read: the thinking-budget
force step (forced </think> constant skips sample/eval) and the final
next_y=None step. The race-lost read returned stale recycled-buffer bytes —
reserved vocab ids 45/125 in place of ' capital'/' for'/trailing tokens —
while the GPU-side stream stayed correct (token-id dumps differ at exactly
pos 32/63; continuations byte-identical). Fix: ensure_readable() in the
three item_at readers — array::eval() (full eval when unscheduled, event
wait when scheduled), mirroring upstream mlx array::item<T>(). lfm2 smoke
is now byte-identical across 8/8 consecutive runs; the lfm2 baseline was
recaptured (the original had recorded the race-lost garbage variant) with
.t0-smoke/baseline/LFM2-BASELINE-RECAPTURE.md documenting the evidence.

Gates: t0-smoke compare 5/5 PASS (qwen3/qwen3_5/gemma4/moe byte-identical
to original baselines — fix changes nothing for non-racing paths); lib
suite 1782/2/42 with both failures in the documented pre-existing f32 set
(f32_causal vjp now PASSES — its finite-diff reads no longer race);
clippy --all --all-targets -D warnings clean; cargo fmt --all --check clean;
metallib untouched (sha 84c24f93 known-good).

Co-Authored-By: Claude Fable 5 <[email protected]>
Mirrors the S8 dense migration: ChatBackend + DecodeStep on
Qwen35MoeInner, Qwen35MoeCmd::Chat(ChatCmd) nested beside untouched
training variants, NAPI methods as thin engine shims via
napi_glue::start_chat_stream, paged/MTP/vision whole-turn cores moved
behind the probes verbatim.

Decisions recorded in code:
- stream_delta_prompt_tokens overridden to full history+delta length,
  matching dense (S8 round 1) and the moe_session env-gated contract;
  the engine default stays delta-count until S10/S11 decide for
  gemma4/lfm2 (engine/backend.rs doc updated).
- trace_offset keeps the DENSE compiled global
  (mlx_qwen35_get_cache_offset): the legacy decode_loop! macro
  hardcoded it on both MoE arms, so the throttled trace line stays
  byte-identical; diagnostics only.

Gate gauntlet ran green against this tree (workflow wf_f0029bdc-72d):
lib 1781/3 known-f32/42; --no-fail-fast clean; T=0 smoke 5/5 families
byte-identical; moe paged-vs-flat parity PASS; moe_session 8/10 (2
failures pre-existing blocking_recv-in-tokio harness defects from PR
#65, never green as committed); moe chunked-prefill 0/3 pre-existing
reuse_cache=Some(false) test config vs the PR #48 guard, never green
as committed; MoE-MTP oracle PASS on qwen3.6-35b-a3b-mxfp8-mtp
(mean_accepted 1.07, pos0 0.642) after restoring a freshly-regenerated
broken release metallib (documented nondeterministic ~63KB kernel
drop, infra not code); clippy -D warnings clean; fmt clean;
packages/core/index.d.cts byte-stable; typecheck clean.

The workflow implementer died before committing; the diff was
verified structurally complete (impls, Cmd nesting, shim routing,
hook overrides, no dead cores beyond the deliberately retained
paged/MTP/vision cores) and committed by the controller.

Co-Authored-By: Claude Fable 5 <[email protected]>
Gemma4's chat-session surface (start/continue/tool + streaming twins +
reset) now runs on the model-neutral engine: Gemma4Inner implements
ChatBackend + DecodeStep (Gemma4Decode carries its own step counter for
the MLX_DEBUG_GEMMA4_DUMP diagnostic::set_step calls), Gemma4Cmd is
DELETED entirely (grep gate: 0 hits) — gemma4 is chat-only, so the
model thread dispatches the engine ChatCmd directly via
handle_chat_cmd::<Gemma4Inner> with no per-family wrapper enum — and
the NAPI methods are thin shims (signatures, doc comments, ts_args_type
byte-stable → index.d.cts unaffected; streaming wired via
engine::napi_glue::start_chat_stream).

Moved, not duplicated: the block-paged whole-turn cores
(chat_sync_core_paged + chat_stream_sync_core_paged + inners) relocate
verbatim behind the paged_turn probe, answering for all four legacy
dispatch shapes (fresh + delta, sync + streaming); the deleted flat
cores' VISION flows become vision_chat_sync_core /
vision_chat_stream_core behind the vision_turn probe (unconditional
cold-start == the legacy has_images forced miss; image-key save kept;
prepare_vision_tokens keeps the exact "Images provided but model has no
vision support (no vision_config in config.json)" string, surfaced from
inside the turn).

Hook overrides reproduce gemma4 behavior per the fit-review map:
session_eos_id = turn_end_id() with config eos_token_ids as
extra_eos_ids (filtered >= 0; reproduces is_eos_token); resolve_params
folds make_sampling_config's model-config defaults (unset → T=0 argmax
fast path), neutralizes the documented penalty no-ops (rep 1.0 / pres
0.0 / freq 0.0 → apply_all_penalties is structurally pass-through),
forces report_performance=true (gemma4 always returns metrics), pins
include_reasoning=true defensively; thinking_setup disabled (channel
parser owns reasoning segmentation); render_prompt keeps the manual
<bos><|turn> wire-format fallback verbatim; prefill =
prefill_body_gemma4 + eval_gemma4_caches + forward_inner(last token) +
squeeze(&[1]) with defensive init_caches_sync; eval_caches = the
post-sample eval_gemma4_caches; reset_caches(PrefixMiss) = reset+init,
(Command) = reset only; save_cache_state = save_tokens ++
generated[..len-1 unless finish_reason=="length"], fresh turns clear
cached_image_key, last_token_in_cache ignored; finalize_turn = raw
decode_sync(.., false) → parse_gemma4_output →
promote_channel_only_output → tool_calls finish-reason promotion,
prompt_tokens/reasoning_tokens/performance verbatim, cached_tokens left
to the session core; stream_skip_special_tokens=false with the
Gemma4StreamParser+Gemma4StreamDispatchState emitter (terminal chunk:
text "", parser-sourced tool_calls()/thinking(), rest from the
finalized result); supports_images()=true UNCONDITIONALLY;
text_delta_image_guard rejects with the byte-identical no-space legacy
strings despite image support; has_live_session folds both legacy delta
guards (!history.is_empty() && caches.is_some());
stream_delta_prompt_tokens = full history+delta; augment_performance
no-op override (exact profiling-payload parity: no MTP fields, no
profile_phases); wired_limit usize::MAX and emit-then-EOS streaming
order keep the trait defaults; repetition-cutoff defaults (16/3/64)
equal extract_chat_params' so the engine's shared checker covers the
flat path — the thin Gemma4RepetitionCutoff wrapper stays only for the
kept paged/vision cores (it already delegates to
sampling::check_repetition_cutoff).

Deleted (replaced by the generic session cores + run_decode_loop +
ChatCmd): Gemma4Cmd + handle_gemma4_cmd, chat_sync_core,
chat_stream_sync_core, chat_session_start/continue/continue_tool_sync,
chat_tokens_delta_sync, chat_stream_session_*_sync,
chat_stream_tokens_delta_sync(_inner), the three inline stream pumps,
and the per-family extract_images_from_messages (-746 net LOC).
model_thread.rs doc example updated off the deleted enum.

Documented accepted drifts (the panel-sanctioned 11, none beyond):
1. session_start now rejects reuse_cache=Some(false);
2. streaming delta reuse-guard names chat_stream_tokens_delta;
3. live-cache guard folds to one "requires an initialized session"
   message + caches-check ordering;
4. one-space drift in the session_continue image-guard;
5. single unified no-template enable_thinking error string (sync long
   form);
6. 256-step cadence pays synchronize_and_clear_cache (perf-only);
7. generation_start anchored earlier (wall-clock only);
8. profiling-gated extras when enableProfiling() is on;
9. engine info! log-line drift; MLX_DEBUG_GEMMA4_DUMP set_step(-1) now
   uniform across entry points (legacy delta paths skipped it);
10. streaming terminal finish_reason from finalize (identical by
    construction);
11. render now precedes the vision failure on doomed image turns.

No engine-side changes were required (engine/ diff is empty).

Gates: cargo test -p mlx-core --lib (1782 passed, 42 ignored; only the
2 known pre-existing f32 banded-attn/attention-vjp failures; metallib
canaries green), clippy --all-targets -D warnings clean, cargo fmt
--check clean. NAPI surface byte-stable (no index.d.cts change). Grep
gate: Gemma4Cmd → 0 hits.

Co-Authored-By: Claude Fable 5 <[email protected]>
Last family migration. ChatBackend + DecodeStep on Lfm2Inner;
Lfm2Cmd DELETED (grep gate: 0 hits in crates/ + packages/) — the
thread is ModelThread<ChatCmd> dispatching
engine::cmd::handle_chat_cmd::<Lfm2Inner> directly (gemma4 pattern);
NAPI methods are thin engine shims via napi_glue::start_chat_stream.
engine/cmd.rs changes are doc-only (scrub references to the deleted
Lfm2Cmd, which was ChatCmd's reference shape).

lfm2-specific hook overrides: eos_before_emit=true (EOS checked
before cancellation AND emission, preserving the suppressed-EOS-chunk
ordering), end_decode = compiled-path teardown/export (Err aborts
before save_cache_state; model-id registry contract preserved),
verify_cache_prefix strictly all-or-nothing (conv/GDN no-rewind — no
len-1 exception), stream_delta_prompt_tokens = full length, always-on
thinking setup with budget semantics preserved verbatim.

Net -1,263 LOC in lfm2/model.rs (+1,177/-2,440 across 3 files).

The workflow implementer finished this work but died on a session
limit before committing; the controller verified compile, structure
(impls/Cmd deletion/shim routing/hook overrides), lfm2 unit tests
98/98, engine tests 105/105, lfm2_compiled_e2e 15/15, clippy -D
warnings, and fmt --check before committing. Full gauntlet (T=0
smoke, --no-fail-fast, env-gated lfm2 binaries, d.ts stability) runs
next.

Co-Authored-By: Claude Fable 5 <[email protected]>
…report

Final step of the phase-1 neutral-chat-engine extraction. All five
families (qwen3 S7, qwen3_5 S8, qwen3_5_moe S9, gemma4 S10, lfm2 S11)
run on crates/mlx-core/src/engine/; this commit deletes the transitional
machinery, renames the retained whole-turn cores, and locks the grep
gates.

Deleted:
- models/qwen3_5/chat_common.rs (re-export shim) — all 10 consumer files
  now import crate::engine::* / mtp_decode directly
- models/qwen3_5/persistence_common.rs (re-export shim) — consumers now
  import crate::engine::persistence directly
- the 5 identical per-family stream_delta_prompt_tokens overrides — every
  migrated family settled on full_len, so it is now the engine default
  (mock test updated; no behavior change for any family)
- the module-level #![allow(dead_code)] in engine/{backend,session,cmd,
  napi_glue}.rs and the item-level allows in engine/decode.rs ("remove in
  S12" markers) — zero dead-code warnings remain, every hook has a
  consumer

Moved (NOT deleted — Phase 7 scope):
- decode_loop! macro + DecodeOps from engine/decode.rs to
  models/qwen3_5/mtp_decode.rs, next to its sister decode_loop_mtp!.
  Its only remaining consumers are the qwen3_5 dense/MoE MTP/vision
  whole-turn cores behind the engine's mtp_turn/vision_turn probes
  (AR fallback arms); retention rationale documented at the macro.

Renamed (live whole-turn cores, names now reflect their probe role):
- chat_sync_core_paged{,_inner} -> paged_turn_sync_core{,_inner}
  (qwen3, qwen3_5, moe, gemma4, lfm2)
- chat_stream_sync_core_paged{,_inner} -> paged_turn_stream_core{,_inner}
- qwen3_5/moe chat_sync_core -> vision_mtp_whole_turn_core,
  moe chat_stream_sync_core -> vision_mtp_whole_turn_stream_core
- gemma4 vision_chat_{sync,stream}_core -> vision_whole_turn_{sync,stream}_core
- qianfan_ocr chat_sync_core/chat_stream_sync_core ->
  chat_turn_sync_core/chat_turn_stream_core
- stale doc references to deleted/renamed cores updated across
  engine/, lfm2, gemma4, transformer/block.rs

Grep gates (crates/mlx-core/src):
- `fn chat_sync_core` -> 0
- `Lfm2Cmd` -> 0, `Gemma4Cmd` -> 0
- non-MTP `decode_loop!` -> 0 (14 remaining invocations, all inside the
  retained qwen3_5/moe MTP/vision whole-turn cores, macro scoped to
  mtp_decode.rs)

LOC report (vs origin/main fba240b, branch end-state):

| file                          | +ins  | -del  | net    |
|-------------------------------|-------|-------|--------|
| models/qwen3/model.rs         | 1801  | 3492  | -1691  |
| models/qwen3_5/model.rs       | 1055  | 1315  |  -260  |
| models/qwen3_5_moe/model.rs   | 1021  | 1032  |   -11  |
| models/gemma4/model.rs        |  821  | 1580  |  -759  |
| models/lfm2/model.rs          | 1197  | 2463  | -1266  |
| family model.rs subtotal      | 5895  | 9882  | -3987  |
| chat_common.rs -> mtp_decode.rs (rename) | 90 | 2517 | -2427 |
| persistence_common.rs -> engine/persistence.rs | 0 | 0 | pure move |
| engine/ (12 new files)        | 7092  |    0  | +7092  |
| engine/persistence.rs         | moved verbatim (427 lines)     |
| t0 smoke harness (tests/t0_smoke.rs + scripts) | 814 | 0 | +814 |
| everything else               |  130  |  115  |   +15  |
| WHOLE BRANCH (42 files)       | 14021 | 12514 | +1507  |

Net legacy chat machinery deleted from the families: -6,414 lines
(model.rs -3,987 + chat_common -2,427). The branch is net +1,504 because
the replacing engine/ is 7,532 lines of which 3,337 are new mock-driven
unit tests (105 engine tests families never had) and the rest carries
the per-hook migration contracts as rustdoc; plus the new +814-line T=0
byte-equivalence smoke harness.

Gates: cargo test -p mlx-core --lib (known f32 failures only),
cargo test -p mlx-core --test lfm2_compiled_e2e 15/15,
clippy --all-targets -D warnings clean, fmt --check clean.

Co-Authored-By: Claude Fable 5 <[email protected]>
…-safe compiled locks (codex)

Two findings from the final whole-migration adversarial review.

[HIGH] reset_caches was not a cold reset for paged families. The
explicit reset cleared flat caches + token/image history, but for the
paged adapter only called release_request() — content-addressed prefix
blocks survived in the shared BlockAllocator. A reset-then-rerun of the
same prompt then took the prefix-hit 1-token-suffix prefill path, whose
bf16 reduction order differs from a cold full prefill and can flip a
greedy near-tie (measured on lfm2.5-1.2b: "says," vs "said" at token
~6) — so reset diverged from a fresh session despite the doc promising
a "fully cold state". The S12 lfm2_session tests masked this with a
prime-turn workaround.

Fix: new BlockAllocator::purge_prefix_cache() (evicts every prefix
entry, returns now-unreferenced blocks to the free pool) +
PagedKVCacheAdapter::release_request_and_purge_prefix_cache(). lfm2 and
qwen3 (the two families whose explicit reset both release-on-reset and
document a cold contract) now purge on ResetScope::Command only;
ResetScope::PrefixMiss keeps release-only (turn-internal cross-request
reuse is the paged design's point). The prime-turn workaround is
removed; lfm2_session reset-determinism + stream-vs-sync tests now
assert cold == post-reset byte-for-byte WITHOUT priming, and pass on
the real checkpoint. qwen3_5/moe/gemma4 are paged-opt-in
(use_block_paged_cache=Some(true)) and make no cold-reset doc promise;
their reset path is byte-identical to legacy and left unchanged (noted
for a future hardening pass).

[MEDIUM] Generic compiled begin_decode could panic on a poisoned
COMPILED_WEIGHTS_RWLOCK. A panic during a prior registration/clear
while holding the write lock poisons the rwlock; the migrated qwen3_5
and qwen3_5_moe begin_decode paths recovered the lifecycle-mutex poison
but then bare-unwrapped the shared read guard, panicking every
subsequent compiled-capable turn's model thread before the model-id
recheck could demote to eager. Fix: engine::compiled_lock now exposes
compiled_weights_read()/_write() with unwrap_or_else(into_inner)
recovery (sound: the lock guards a unit payload; mlx_clear_weights()
resets g_active_model_id to 0 first, and every reader re-validates the
model id under the guard and falls back to eager on mismatch). All
read/write call sites in qwen3_5/qwen3_5_moe model.rs + persistence.rs
swept onto the recovering helpers; regression test poisons the rwlock
and asserts begin_decode acquisition no longer panics.

Gates: lib 1782/3-known-f32/42 (4 metallib canaries green); workspace
clippy -D warnings + fmt clean; lfm2_compiled_e2e 15/15; 2 new unit
tests (poison recovery, purge_prefix_cache); env-gated lfm2 reset tests
pass workaround-free on lfm2.5-1.2b-thinking-mlx; T=0 smoke 5/5
byte-identical.

Co-Authored-By: Claude Fable 5 <[email protected]>
…ma4/qwen3_5/moe (codex follow-up)

Co-Authored-By: Claude Fable 5 <[email protected]>
…tokens==0 actually bites

The single-block "Say hi" prompt (<=16 tokens) made the deterministic
cached_tokens==0 assertion a no-op: the paged prefix lookup is capped at
max_cache_hit_tokens = prompt_len - 1 and find_longest_cache_hit only
matches COMPLETE blocks, so a sub-block prompt reports cached_tokens==0
on turn 2 regardless of the purge. Switched all three gemma4/qwen3_5/moe
reset-purge tests to a >=33-token (>=2-block) prompt. Negative-controlled
on real checkpoints: with purge disabled turn 2 hits cached_tokens=32
(2-block prefix hit) and the test FAILS; with the purge it cold-prefills
(cached_tokens=0).

Co-Authored-By: Claude Fable 5 <[email protected]>
…aults, generic cache helpers

Phase-2 roadmap P1 (first executable step). All changes byte-identical T=0;
shrinks what a new ChatML family must write (goal 3.1 "easy thinking budget").

- thinking (3.1): new declarative `ThinkingPolicy {None, TemplateHonoring,
  AlwaysOnBudgetFromEffort}` + `resolve()` in engine/params.rs. The 5 per-family
  `thinking_setup()` bodies collapse to a one-line `policy()` pick (gemma4=None,
  lfm2=AlwaysOnBudgetFromEffort, qwen3/qwen3_5/moe inherit the TemplateHonoring
  default). `resolve()` is a field-for-field transcription of the deleted bodies
  (lfm2 effort:"low"→256-cap-but-still-enabled footgun preserved verbatim).
- ChatML render deltas: `render_continue_delta`/`render_tool_delta` gain ChatML
  default bodies; qwen3/qwen3_5/moe drop their identical copies (req→optional).
  gemma4 (turn-format) + lfm2 keep their overrides.
- cache: `save_cache_state_direct`/`_after_delta` made generic over <C>; deletes
  engine's last concrete-model import (Qwen3_5LayerCache). All 12 call sites
  infer C=Qwen3_5LayerCache unchanged → identical monomorphized code. 4 test
  fixtures reworked onto a zero-sized DummyCache (same invariants asserted).
- trace: `DecodeStep::trace_name()` (default "Qwen3.5") replaces the hardcoded
  AR-trace literal in decode.rs; + REQUIRED/OPTIONAL implementer checklist atop
  the ChatBackend trait (doc-only).

Net -128 LOC (qwen3/qwen3_5/moe each shed ~50). No #[napi] change → index.d.cts
byte-stable. Gates: clippy -D warnings + fmt clean; codex adversarial-review
APPROVE (no findings); lib 1782 pass / 3 known-f32 fail / 4 canaries + 4
DummyCache fixtures ok; t0-smoke 5/5 byte-identical vs main-at-fork; 3
reset-purge tests pass.

Co-Authored-By: Claude Fable 5 <[email protected]>
Thread the engine-resolved ThinkingSetup through WholeTurnArgs so every
whole-turn core builds its ReasoningTracker from ONE resolved value
instead of re-deriving enable_thinking/budget inline.

- backend.rs: ThinkingSetup is Copy; WholeTurnArgs gains `thinking`.
- penalties.rs: ReasoningTracker::from_setup(&setup, id) keystone
  (== new(setup.enabled, setup.budget, id)).
- session.rs: populate wt_args.thinking from the SAME resolved value the
  flat tracker uses (single source).
- qwen3 / qwen3_5 / qwen3_5_moe / lfm2: 13 inline ReasoningTracker::new
  folded to from_setup(args.thinking); cores read thinking.enabled.
- Fixes the latent paged enable_thinking=false bug: qwen3_5 + moe paged
  cores hardcoded thinking_enabled=true. Now honored.
- qwen3 paged path threaded too (codex review finding) - byte-identical
  SSOT plumbing (qwen3=TemplateHonoring already honored the flag).
- Remove dead ChatParams.thinking_token_budget: zero readers is the
  proof the budget now flows ONLY through ThinkingSetup.

Gates: t0-smoke byte-identical across all 5 families; new
p2_paged_thinking_honors_enable proves the paged fix (none->0,
medium->>0); lib suite green; clippy -D warnings + fmt clean.

Co-Authored-By: Claude Fable 5 <[email protected]>
…Plan

Replace each family's hand-rolled warm-continue/cold-start paged-KV
lifecycle with the shared adapter `prepare_turn_with_max_cache_hit_tokens`
(gemma4 already shipped this exact call). ~60 lines of fiddly state
machine per block collapse to one call; 8 blocks across 4 families.

- qwen3, lfm2: byte-identical — the adapter runs the same warm
  `continue_turn` / cold `release -> reset -> find_cached_prefix ->
  allocate_suffix_blocks` arms, and `find_cached_prefix_with_max_tokens`
  was a pure pass-through to the same `find_cached_prefix_inner`. lfm2
  passes reuse_cache=true (its hand-rolled can_continue had no reuse
  term; the adapter ANDs reuse_cache, so true preserves it).
- qwen3_5 dense, qwen3_5_moe: per-block -> uniform lookup substitution.
  Byte-identical for text-only dispatch — build_paged_extra_keys returns
  all-empty per-block vecs whose block hashes equal the uniform &[] path
  (the contract already documented in-code). The pre-turn [MLX_TRACE]
  probe is hoisted to an immutable read before prepare_turn mutates
  request_tokens; lookup_extra_keys kept (GDN-prefix-state + per-block
  finalize still consume it).
- Suffix blocks are allocated inside prepare_turn; the explicit
  allocate_suffix_blocks calls are removed (no double-allocation).

Net -248 LOC. Gates: t0-smoke byte-identical across all 5 families
(gemma4 negative control), qwen3 inline chunked-prefill lifecycle tests
pass, clippy -D warnings + fmt clean.

Co-Authored-By: Claude Fable 5 <[email protected]>
P4 inverts the per-family paged whole-turn cores into a generic
run_paged_turn<B>. But the default t0_smoke runs FLAT for qwen3_5 +
qwen3_5_moe (use_block_paged_cache.unwrap_or(false)), so the paged path P4
rewrites had ZERO byte coverage — the verdict's single highest-leverage gap.

Add qwen3_5_paged_smoke + qwen3_5_moe_paged_smoke: clone the checkpoint with
use_block_paged_cache=true (symlink weights, copy+patch only config.json) and
run the same deterministic 3-turn T=0 session, capturing a byte-for-byte
baseline of today's paged output. Each P4 inversion step must reproduce it
byte-identical (the (i) pre/post gate). qwen3/lfm2/gemma4 default PAGED, so
their existing smoke already covers paged — only the 2 default-flat families
need a forced variant.

Empirically: paged != flat at T=0 for qwen3_5 dense (flat=compiled C++,
paged=Rust), so the gate is pre/post PAGED byte-identity, NOT paged==flat.
Both paged baselines produce coherent output (Paris / Berlin / Paris).

Wire both into scripts/t0-smoke.sh capture/compare (.t0-smoke stays gitignored).

Co-Authored-By: Claude Fable 5 <[email protected]>
…d_turn

Replace the two hand-rolled per-family paged loops (chat_stream_sync_core_paged_inner / chat_sync_core_paged_inner) with the generic run_paged_turn<B: PagedBackend> + run_decode_loop, mirroring how FLAT flows through chat_turn_core. Net ~-1100 LOC in qwen3/model.rs. PagedBackend / DecodeStep traits carry the per-family seams; Qwen3PagedDecode drives the loop via run_paged_decode_step.

DecodeStep::materialize_final: the forward-before-emit loop skips the final token's forward on a length exit, leaving a paged stepper one token short of the kept history. Qwen3PagedDecode records that token's K/V before end_decode (== fba240b's unconditional bottom-of-loop forward; mlx-lm and mlx-vlm also materialize; vLLM one-shorts for batched throughput, not adopted for single-stream sessions). LENGTH exits only; EOS/cancel/repetition boundary tokens are left unmaterialized.

resolve_params now uses the uniform engine::extract_chat_params (the old 0.7/0.9 inline defaults were phantom; proven no-op at T=0). The D2 keep-all-iff-length save-history contract and the single top-of-iteration streaming-cancel snapshot match origin/main fba240b.

Gates: T=0 behavior-preserving (cross-binary qwen3-0.6b branch-HEAD vs branch-live byte-identical; on-branch t0-smoke green incl. warm-continue turns); perf == main (xbin decode-tps +1.36%, within control band); codex adversarial-review approve, 0 findings; 115 engine:: tests; clippy -D warnings + fmt clean; no index.d.cts drift.

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

Vision (image) turns now run ONLY on the block-paged KV backend across
qwen3.5 dense, qwen3.5_moe, and gemma4. The flat-vision turn cores and the
shared flat-VLM prefill seam are removed (no legacy fallback).

- Vision-capable dense/moe checkpoints now default use_block_paged_cache to
  true at load (keyed on vision_config presence); gemma4 already defaulted
  paged. An explicit use_block_paged_cache:false, a non-Metal build, or the
  dense sym8 force still yield no paged adapter.
- A vision turn that reaches a None paged adapter returns a clear error
  ("image turns require the block-paged KV backend") instead of running a
  flat-vision path.
- image+MTP turns route to the paged-vision autoregressive core (MTP is a
  decode optimization and is simply not run on image turns) instead of
  hard-erroring.
- Deleted: gemma4 vision_whole_turn_{sync,stream}_core +
  prefill_body_gemma4_with_embeds; dense/moe inlined flat-vision arms +
  vlm_prefill / vlm_prefill_moe; the shared engine/vision.rs VlmPrefillLayer
  trait + run_vlm_prefill_layers loop + the now-unread VisionMerge.rope_deltas
  field + both decoder_layer VlmPrefillLayer impls.
- Kept: the paged-vision path, shared vision-feature/M-RoPE extraction
  (vlm_prepare_vision_features), gemma4 sliding-window flat KV cache, the
  text-flat path.

Parity tests reworked from paged-vs-flat to paged-only correctness (coherence +
determinism + image-dependence) plus a new error-contract test (a
use_block_paged_cache:false vision clone rejects image turns).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01N6k6E8zikyis7hJZyqkmsq

@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: 2eeaa4c5ca

ℹ️ 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 .github/workflows/ci.yml Resolved
Brooooooklyn and others added 6 commits June 22, 2026 09:02
gemma4's ~4.7GB embed_tokens_per_layer.weight exceeded the Metal
per-buffer cap during `mlx convert`, aborting the e2e gemma4 leg: a
whole-tensor MLX eval on a Metal build always routes through
MetalAllocator regardless of stream, so no astype/flatten-to-cpu dance
avoids it.

When a converted tensor keeps its source dtype (bf16/f16, no astype,
handle preserved), copy its bytes straight from the source safetensors
file to the destination instead of materializing the array. A new
mlx-sys FFI (`mlx_safetensor_read_raw`) does a bounds-checked, chunked
file read; provenance is keyed on the native array handle (Arc-clone
identity), pinned against ABA, and gated on
dest_len == src.byte_len == threshold with a fail-safe fallback to
array_to_bytes when the handle does not match.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01N6k6E8zikyis7hJZyqkmsq
On a VLM checkpoint the engine now load-forces the block-paged backend,
so the MTP cache snapshot runs on paged caches. Empty FullAttention
shells (offset 0) tripped a debug-assert and aborted the e2e
qwen3_5-dense leg. Snapshot now skips those empty shells on the paged
path while staying byte-identical to the old behavior on flat.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01N6k6E8zikyis7hJZyqkmsq
run_paged_turn left the session marked live after save_paged_history
returned an error, so the next turn could reuse a half-written cache.
On a save failure, reset the backend caches (Command scope) before
propagating the error so the session falls back to a clean cold prefill.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01N6k6E8zikyis7hJZyqkmsq
The MTP oracle tests asserted against an AR run that was ALSO cancelled
mid-stream; because MTP commits in cycle-batches and AR one token per
step, the two cancels stranded different token counts on this host, so
the turn-2 desync-heal equality was skipped (vacuous pass) whenever the
partials differed.

Drive the AR ground truth from a clean length stop at the MTP cancel's
exact emitted-token count instead. A cancel and a length stop both drop
the last unforwarded token, so a healed MTP cancel and the AR run commit
the identical turn-1 history; turn-2 equality is now asserted on every
host with no skip. Verified: mid-cycle cancel emits 3, AR length-stops
at 3, turn-2 byte-identical.

Also clone the checkpoint to a flat (use_block_paged_cache=false) copy
so the MTP oracles exercise the eager-MTP path under the new VLM paged
load-force default.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01N6k6E8zikyis7hJZyqkmsq
publish now lists model-test in `needs` and gates on its result. The
`always()` guard keeps publish running when model-test is SKIPPED (PRs
without the `model-e2e` label, where publish is a no-op) instead of
cascading the skip, while still requiring test + lint to have succeeded
and blocking on a model-test failure or cancellation.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01N6k6E8zikyis7hJZyqkmsq
Regenerated NAPI declaration doc comments for Qwen35 paged/VLM behavior
to match the already-committed Rust source. Declaration-only; no
signature changes.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01N6k6E8zikyis7hJZyqkmsq

@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: d1211ee33a

ℹ️ 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 packages/lm/src/stream.ts Resolved
gemma-4-E2B's embed_tokens_per_layer.weight is a single ~4GB bf16 tensor [vocab, num_layers*ple_dim]. On a Metal device whose maxBufferLength is ~3.5GB the whole-tensor materialize cannot allocate one buffer and LOAD fails (the same OOM the convert raw-passthrough fix exposed downstream).

Shard the table along vocab rows into sub-cap arrays streamed directly from the safetensors file via mlx_safetensor_read_raw; the embedding forward gathers across shards with a clamp+mask select chain, byte-identical to a dense take for normal/NaN/Inf/+-0 values. Gated on dense-bf16 + nbytes>budget (default 1GiB, env MLX_GEMMA4_PLE_SHARD_BYTES); quantized and small tables are untouched.

The shards stay model-owned outside the params map, so they are counted into the deterministic weight-byte total fed to the cache-limit coordinator (omitting them would inflate the cache cap on the constrained devices this targets), and set_sharded validates that the shards reconstruct the configured [num_embeddings, embedding_dim] table instead of installing a drifted checkpoint silently.

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

Claude-Session: https://claude.ai/code/session_01N6k6E8zikyis7hJZyqkmsq
A refactor left makeStreamingModel's applyChatTemplate member optional for every wrapper. Make the return type conditional on the options via a const type param so the four templating wrappers (Qwen35/Qwen35Moe/Lfm2/Gemma4, recordModelPath:true) again expose applyChatTemplate as required, while Qwen3 (applyTemplate:false) and QianfanOCR (recordModelPath:false) keep it not-required.

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

Claude-Session: https://claude.ai/code/session_01N6k6E8zikyis7hJZyqkmsq

@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: c334fe6b51

ℹ️ 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 Brooooooklyn added model-e2e Run the heavy Model E2E workflow (per-family real-checkpoint tests) on this PR and removed model-e2e Run the heavy Model E2E workflow (per-family real-checkpoint tests) on this PR labels Jun 22, 2026
The PLE sharding loader looked up the sanitized bare key
`embed_tokens_per_layer.weight`, but checkpoints store the tensor under
its raw prefixed name (raw HF `model.language_model.`, mlx-converted
`language_model.model.`). `load_bf16_tensor_sharded` did an exact bare
lookup, never matched the prefixed on-disk name, and errored "tensor not
found" — so the gemma-4-E2B PLE never sharded and the load OOM'd on the
~3.5GB-buffer-cap CI runner.

Resolve the bare key against the file's raw names, scanning only the SAME
canonical checkpoint files the main loader reads (single
`weights`/`model.safetensors`, else the `model-*-of-*.safetensors`
shards) so a stray or auxiliary `.safetensors` can neither win the lookup
nor abort it. Decide globally across those shards: an exact key anywhere
wins over any `*.{key}` suffix; a suffix is taken only when no exact match
exists; 2+ exact matches, or 2+ suffix matches with no exact, is a loud
error rather than silently gathering the wrong tensor.

Verified against raw-HF, pre-existing-converted, and freshly-converted
gemma-4-E2B (3-file checkpoint): the PLE shards into 5 sub-cap arrays and
both paged-vs-flat parity tests pass.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01N6k6E8zikyis7hJZyqkmsq

@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: 8ee40f813f

ℹ️ 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".

bf16 gemma-4-E2B is ~9.6GB on disk; the paged-vs-flat parity test holds a
flat AND a paged instance resident at once (measured ~20GB peak RSS, ~10GB
for one instance), so it SIGKILL/jetsam-OOMs the macos-latest (~7GB)
runner — one instance alone already exceeds it.

The PLE buffer-cap sharding fix landed this session lets E2B *load*, but
the test's total footprint still cannot fit the standard runner. Move
gemma4 into the documented "excluded families" list with the re-enable
path (macos-*-xlarge runner + sequential model load, or a quantized
checkpoint). The qwen3 / qwen3_5-dense / lfm2 e2e legs are unaffected.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01N6k6E8zikyis7hJZyqkmsq

@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: 2a0316bbcd

ℹ️ 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".

`run_paged_turn` already resets the session on a `save_paged_history`
failure, but `finalize_turn` ran afterward with its error propagated bare.
gemma4's `finalize_turn` decodes the assistant text (`decode_sync(..)?`)
and is fallible, so after `finalize_paged_turn` + `save_paged_history`
published the kept-live request and advanced `cached_token_history` for
the turn, a finalize error left that state live — a later warm-continue
could reuse a native cache holding a turn the conversation (which drops
the failed turn) omits.

Wrap the `finalize_turn` call so its error runs the same
`reset_caches(ResetScope::Command)` rollback as the save failure before
propagating. Engine-level, so it covers every family's finalize hook.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01N6k6E8zikyis7hJZyqkmsq
@Brooooooklyn Brooooooklyn added model-e2e Run the heavy Model E2E workflow (per-family real-checkpoint tests) on this PR and removed model-e2e Run the heavy Model E2E workflow (per-family real-checkpoint tests) on this PR labels Jun 22, 2026
@Brooooooklyn Brooooooklyn reopened this Jun 22, 2026
@Brooooooklyn
Brooooooklyn merged commit ee88b92 into main Jun 22, 2026
16 checks passed
@Brooooooklyn
Brooooooklyn deleted the worktree-refactor-chat-engine branch June 22, 2026 09:40
Brooooooklyn added a commit that referenced this pull request Jul 10, 2026
…) + fail-closed fixes (#94)

## Summary

vLLM-aligned per-turn execution planning: a new `engine/plan.rs`
(`TurnPlan`/`ExecutionPlan`) replaces scattered per-family probes so
paged/flat/speculative routing and delta-turn admission are decided in
one typed place, plus a model-loader registry rework in `@mlx-node/lm`
and a new `docs/inference-architecture.md`. On top of the refactor
baseline, three fixes close every blocker found in review:

- **Model loader fails closed** — malformed `config.json` (non-object
root, numeric/object `architectures`) now throws
`MalformedModelConfigError` instead of silently loading as qwen3;
`LoadableModel` is restored to the native `@mlx-node/core` class union
(registry rows carry `nativeModelClass`), so downstream native-instance
assignments keep compiling.
- **Gemma4 media prepare fails closed** —
`media_session_context`/`paged_text_turn_context` are cleared only after
the fallible paged prepare succeeds, and the text-delta guards consult
`session_media()`; a block-exhaustion failure now yields the typed
`IMAGE_CHANGE_REQUIRES_SESSION_RESTART:` rejection in both windows (keys
set, and warm-continued sessions where provenance lives only in the
context).
- **LFM2 delta turns stay paged** — `supports_delta: true`;
continuations ride the single existing `run_paged_turn` warm
strict-extension path (adapter block reuse + conv Pass-1
reconstruction). This ends the reproduced corruption where a paged fresh
turn + flat delta tail-prefilled onto never-populated flat attention KV
and emitted input-independent repeated `<think>` tokens. The parity
suite gains a content-sensitive memory-probe oracle (the old one passed
on a 48-token context-insensitive prompt).

## Verification

- Per-fix: TDD where applicable, `cargo clippy --all-targets -- -D
warnings`, `cargo fmt --check`, `yarn typecheck`, `vp lint --type-aware
--type-check`, full `cargo test -p mlx-core` green.
- LFM2 E2E on the real 1.2B checkpoint: parity suite 8/8; 3-turn TS
session (paged default) cachedTokens 0→494→683 with correct recall
answers matching the forced-flat control.
- Each fix passed a task-scoped adversarial review; the final
whole-branch adversarial review returned PASS with zero findings.

## Follow-ups (triaged, not blockers)

- Gemma4 media cores record `first_token_instant` after the decode loop
(invalid media TTFT/decode telemetry; pre-existing from #70).
- Silent MTP→AR fallback on paged checkpoints (`mtpCycles: 0` with
`enableMtp: true`) deserves an explicit signal.
- Dense/MoE plan-helper duplication (qwen3_5 ↔ qwen3_5_moe), gemma4
`paged_text_turn_context` side-channel → explicit save-context
parameter, registry-derived draft-model error message.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> Changes core chat routing, speculative/media session semantics, and
model detection fail-closed behavior across many families; incorrect
planning or Gemma4 media state would corrupt KV reuse or mis-load
checkpoints.
> 
> **Overview**
> Introduces **`engine/plan.rs`** so each chat turn is planned once from
load-time **`ExecutionPlan`** and request facts (**`TurnPlan`**: media
input vs live context, paged attention, speculative decoder,
**`TurnPath`**). The session core stops chaining **`has_paged_adapter` /
`vision_turn` / `mtp_turn` probes** and instead calls required
**`run_paged_turn`**, **`run_speculative_turn`**, or
**`run_multimodal_turn`** handlers with bundled **`MediaInputs`** and
**`text_delta_media_guard`**.
> 
> **Gemma4** advertises media via **`gemma4_media_plan`** (truthful
encoders vs backend-validated admission), tracks persistent
**`media_session_context`**, and only clears media provenance after a
successful paged prepare so failed prepares still fail closed through
**`session_media()`**. **LFM2** sets **`supports_delta: true`** so
session continuations stay on the generic paged path instead of flat
tail-prefill on empty attention KV.
> 
> The **@mlx-node/lm** loader gains broad registry/detection tests
(architecture precedence, malformed **`config.json`** errors,
**`LoadableModel`** compile-time probes);
**`docs/inference-architecture.md`** is linked from **`CLAUDE.md`**.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
8c0f052. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5 <[email protected]>
Brooooooklyn added a commit to ivibes/mlx-node that referenced this pull request Aug 22, 2026
Review pass over the AWQ + quantize memory fix.

`apply_awq_prescaling` keeps only the part that moves the number: the
whole-map `eval()` at the tail is gone. The `AwqMaterialization` enum,
`apply_awq_prescaling_with`, the per-layer `layer_touched` retire loop
and its two tuning constants are removed. That machinery retired the
inverse-scale chains, roughly 100 KB per layer — under 10 MB on a 27B,
against a 21 GiB peak — and existed half for tests.

The two byte-equality tests collapse into one that reproduces the eager
arm itself with `values().for_each(eval)`, so no production code exists
only for tests. Its doc states the honest limit: with the quantize
loop's own `array.eval()` mutated away the test still passes, so it
guards MLX's evaluation order, not our call site.

The new triplet materialization is fallible. The safetensors writer used
to own it and could report an OOM; taking it over must not swallow one.

The memory test gains a lower bound and a key-count assertion: deleting
the triplet `weights.insert` calls also releases the sources, so the
upper bound alone passed on a converter that emitted no quantized
tensors at all. Verified by mutation — that now fails, and reverting the
eval-then-drop hunk fails with all 192 MiB still resident. Its comment
claiming sibling tests are kilobyte-scale was false; the isolation comes
from `RUST_TEST_THREADS = "1"`.

Two provenance comments corrected. The pin does not hold the checkpoint
because AWQ materializes each source — the quantize loop has always
evaluated its input, so the pin has held every quantized source since
mlx-node#70, with or without an imatrix.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Ti3ENgKzUMZkvWWpci58Ch
Brooooooklyn added a commit that referenced this pull request Aug 23, 2026
## Problem

`mlx convert --quantize` holds every quantized bf16 source resident for
the whole conversion, so the lazy SafeTensors load upstream of it buys
nothing. Add `--imatrix-path` and AWQ pre-scaling also materializes the
tensors it never touched. Converting Qwen3.8-27B (55.6 GB bf16 source)
exhausts a 36 GB machine.

Two coupled retention paths. Neither one alone is enough, and neither is
specific to AWQ.

### 1. Passthrough provenance pinned every bf16 source

`record_passthrough_sources` kept a `_keep_alive` clone of **every**
bf16/f16 source tensor so a recycled handle address could never be
mistaken for a passthrough. The clone is free while the array stays lazy
— but `quantize_weights_inner` has always called `array.eval()` on its
input, and the pin then held the dense bytes until
`drop(source_by_handle)`, just before the save.

Two changes close it.

**Sub-threshold tensors are no longer recorded.** The writer's raw path
is gated on `dest_len >= raw_threshold` (2 GiB) **and** `src.byte_len ==
dest_len`, so an entry below the threshold can never be consulted. It
only pinned.

**The entry no longer owns its source.** `_keep_alive: MxArray` becomes
`alive: Weak<MxHandle>`, and the lookup guards on
`SourceProvenance::matches`. Without this the pin still held every
recorded tensor that convert later transforms or quantizes — which is
the *largest* tensors, not the smallest, and the eval-then-drop below
cannot help while a second owner exists. Worst case on a plain
`--quantize`: Qwen3.5-122B-A10B stores each layer's
`mlp.experts.gate_up_proj` as bf16 `[256, 2048, 3072]` = 3.000 GiB, over
the gate, and `normalize_qwen35_prestacked_experts` splits it with
`slice_axis` — so all 48 entries are dead and pin 144 GiB. Under any
`--q-recipe` the 2.4–4.4 GiB `embed_tokens` / `lm_head` tables go the
same way, because the recipe predicates quantize keys `should_quantize`
would have skipped.

Neither change can produce a false passthrough. An entry that was never
inserted has no pointer for a recycled address to collide with; a weak
reference that fails to upgrade is exactly the freed-and-recycled case;
and a successful upgrade plus `Arc::ptr_eq` is exact identity, stricter
than the address match the pin allowed.

### 2. Quantized outputs pinned their dense inputs

`mlx_quantize` returns **lazy** arrays whose graph holds the bf16 source
alive. Storing them un-evaluated meant `drop(array)` freed nothing, and
the cost reappeared in the writer:

```
Quantizing 274 weights (3-bit affine, group_size=64)
  Quantized 50/274 tensors...      <- 0.9 ms for all of them
Quantization complete: 249 tensors quantized
shard written ... shard_ms=6400 mlx_peak_mb=15056
```

The triplet is now materialized before the source is dropped. The
allocator flush also gains a 1 GiB byte budget alongside the existing
every-50-tensors cadence, which is size-blind.

### And AWQ made it worse

`apply_awq_prescaling` ended with `for w in weights.values() { w.eval();
}` — the **whole** map, including tensors AWQ never touched. That eval
is gone. The rewritten tensors stay lazy, and the pre-scale multiply
runs inside the quantizer's existing per-tensor loop; tensors the
quantizer skips are materialized one at a time by the writer instead.
The same function serves the GGUF path (`utils/gguf.rs`), so both entry
points are covered.

## Output is unchanged

Reported by @ivibes and not re-run since the review pass; the unit tests
below are what CI checks.

- **`model.safetensors` is byte-identical** (sha256 `0670e78c…`) between
patched and unpatched on Qwen3.5-4B with a real Unsloth imatrix.
- `config.json` is canonically identical. Its key order varies run to
run from `HashMap` iteration in `build_quantization_object` — this
predates the change; two *unpatched* runs also differ from each other.
- `eval()` schedules, it does not rewrite arithmetic.

## Measurements

@ivibes, on a 38.7 GB M3 Max. Not reproduced on the review machine.

Qwen3.5-4B (9.32 GB bf16), 3-bit affine `--q-recipe unsloth` + imatrix:

| | before | after |
|---|---|---|
| MLX allocator peak | 14.7 GiB | **3.52 GiB** |
| peak RSS | 16.30 GiB | **4.46 GiB** |
| wall time | 12.6 s | 12.2 s |

Qwen3.8-27B (55.6 GB bf16) on a 38.7 GB M3 Max, previously not
completable:

| | peak RSS | time |
|---|---|---|
| Q4 | 21.3 GiB | 81 s |
| Q5 | 22.2 GiB | 91 s |
| Q6 | 16.6 GiB | 119 s |

Peak RSS is the measured bound. Swap traffic is **not** claimed: an
earlier revision of this PR carried a `swaps` column reading 0, which
came from `vm.swapins`/`vm.swapouts` sysctls that do not exist on the
test machine. A later run of the same code path, measured with
`vm_stat`, paged out ~7.9 GiB during a 27B convert. This change bounds
what MLX allocates; it does not make a 27B convert swap-free on a 36 GB
machine.

Total time is unchanged — the work moves out of the writer and into the
quantize loop rather than being added.

## Tests

- `quantize_releases_dense_sources_instead_of_pinning_them` — allocator
assertion that dense sources are released. Verified against its
mutation: with the eval-then-drop hunk reverted it fails with
`after=201326592`, all 192 MiB still resident.
- `awq_prescaling_survives_lazy_materialization` — AWQ then quantize,
bytewise, one arm materialized up front and one left lazy, across all
four AWQ dependency groups.
- `passthrough_provenance_skips_tensors_below_the_raw_threshold` — the
threshold gate, with the threshold passed in rather than set in the
environment.
- `provenance_does_not_keep_its_source_resident` — allocator assertion
that a recorded entry releases its source. Mutation-verified: restore
the strong clone and it fails with `after=67108864`, the full 64 MiB
still resident.
- `provenance_entry_stops_matching_when_its_source_dies` and
`provenance_matches_only_the_array_it_recorded` — the identity guard.
Dropping `Arc::ptr_eq`, or making `matches` return `true`, each kills
one of them.

`cargo test -p mlx-core --lib`, `cargo fmt`, `cargo clippy
--all-targets` clean.

## Known limits

- Releasing the pin turns the MoE case from an unconditional 144 GiB
into an **order-dependent** peak, not a strict one-tensor working set.
`slice_axis` returns a view sharing the parent buffer, so a fused expert
tensor stays resident until *both* halves are quantized, and
`quantize_weights_inner` builds its work list from `weights.keys()`
unsorted (`convert.rs:8005`). Bounding that means changing quantization
order or forcing a contiguous copy in the sanitizer — a different
function and a different tradeoff.
- Exercised end to end on **dense `qwen3_5` only**. MoE expert stacks
and `--q-mtp split` are covered by unit tests and reasoning, not by a
full conversion.
- `QUANTIZE_FLUSH_BYTE_BUDGET` (1 GiB) is reasoned, not swept.

## Review notes

Revised from the original submission:

- The AWQ change is reduced to deleting the whole-map eval. The
`AwqMaterialization` enum, `apply_awq_prescaling_with`, the per-layer
`layer_touched` retire loop and its two tuning constants are gone:
measured against the graphs they retire, that machinery bounded roughly
100 KB per layer — under 10 MB on a 27B — against a 21 GiB peak.
- The two byte-equality tests collapse into one. The eager arm is
reproduced inside the test with `values().for_each(eval)`, so no
production code exists only for tests. Note the honest limit: with the
quantize loop's own `array.eval()` mutated away, that test still passes,
so it guards MLX's evaluation order, not our call site.
- The provenance test no longer calls `std::env::set_var` — @ivibes
landed that independently while this review was running, and their
`record_passthrough_sources_with` is what shipped.
- The new triplet materialization is fallible
(`eval_arrays_with_context`). The writer used to own it and could report
an OOM; taking it over must not swallow one.
- The problem statement is corrected: the pin has held every quantized
source since #70, so this is not an AWQ-only fix. Two provenance
comments asserting the AWQ-only story are fixed with it.
- `SourceProvenance` no longer pins its source. Codex flagged the
residual as P1 on `c6f69d3a`; the mechanism is real but its stated path
is not — `apply_awq_prescaling` matches only exact dense `mlp.*` /
`self_attn.*` / `linear_attn.*` literals and can never touch an MoE
projection. The reachable path is `sanitize`, and it is worse than the
finding claimed.

The review commit is separate, so `git diff baf4dbe..HEAD` shows
exactly what it changed.

---------

Co-authored-by: LongYinan <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

model-e2e Run the heavy Model E2E workflow (per-family real-checkpoint tests) on this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant