Skip to content

perf: inference perf polish + quality sweep (qwen3.5 RoPE axis fix, MLX NAX-fork bump, metallib packaging hardening) - #83

Merged
Brooooooklyn merged 48 commits into
mainfrom
perf/inference-polish-quality-sweep
Jul 4, 2026
Merged

Brooooooklyn merged 48 commits into
mainfrom
perf/inference-polish-quality-sweep

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

What & why

Implements the inference perf polish + quality sweep design spec: a correctness pass over the shared inference paths, a vendored-MLX bump that fixes broken Apple-Silicon (gen-17 / M5) kernels, and a code/comment cleanup sweep. 48 commits on top of main (f65104aa).

Highlights

Correctness

  • qwen3.5 scalar RoPE axis fix — the scalar RoPE arm fed [B,T,H,D] to fast::rope, rotating along the head axis instead of the token axis (rotation angle was constant across tokens). This is the production path (dense / MoE / MTP / VLM-text, flat + paged), so every qwen3.5 output changed. Fixed by transposing to [B,H,T,D] → rope → back, matching mlx-lm. Self-referential gates never caught it; added an absolute regression test.
  • sym8 flat-KV pins (dense + MoE) — a sym8 checkpoint emits mixed-dtype K/V (f32 K after the f32-weight k_norm, bf16 V) which the block-paged pool rejects on the first write. Both loaders now pin sym8 to the validated flat path.
  • gemma4-prequant group_size metadata honesty; qwen3.5-MoE loader ensure_dense_weight_floating guards so packed weights with missing sidecars fail loud.

Vendored MLX bump (crates/mlx-sys/mlx)

  • Bumped to a fork branch nax-macos-26-0-floor @ de7e3429 = upstream ml-explore/mlx e9463bbfc + one cmake patch. The old pin's NAX kernels were broken on gen-17 / macOS ≥ 26.2 (bf16 unaligned-K GEMM, bf16 causal full-SDPA, sorted gather_mm all producing garbage; f32 sorted gather_mm SIGABRT). Three of four classes are fixed and probe-verified; the fourth (f32 TF32 degradation) is upstream's deliberate MLX_ENABLE_TF32=1 default, kept as-is with a documented escape hatch.
  • The one fork patch adds option(MLX_METAL_FORCE_NAX) so npm artifacts keep a macOS 26.0 load floor while still shipping the NAX kernels (compiled at their required 26.2 ABI; runtime is_nax_available() gates dispatch at 26.2+). Upstream's 26.2 gate turned out to be a correctness gate — building NAX at a uniform 26.0 target miscompiles.
  • Submodule URL is the public HTTPS fork; the pinned commit is on a pushed branch, so CI submodule checkout works.

Packaging hardening (packages/core)

  • metallib selection is now bound to the built .node's baked METAL_PATH (authoritative, not an mtime heuristic), byte-compared to the install copy, deployment-floor-gated, and fails closed in publish/release mode (MLX_METALLIB_STRICT=1 in CI). Closes a long-standing "stale/incomplete metallib" hazard (root-caused to stale-dir first-match pairing, not a corrupt build).

Cleanup — retired dead compiled-C++ comments/docs across qwen3.5 dense+MoE, canary-gated the tests that depend on the (now-fixed) NAX kernels, plus assorted comment/hygiene fixes.

Testing

  • Rust: mlx-core lib 1930/0 (46 ignored), mlx-paged-attn 220/0, clippy -D warnings clean, cargo fmt clean.
  • TS: yarn typecheck clean, metallib-select 45/45, full Vitest suite green apart from a missing gitignored GSM8K fixture and 4 gemma4 real-model E2E tests (see caveat).
  • Every high-risk area passed an independent adversarial review pass; the packaging series went through several review rounds.

Perf — new-pin decode (no regression; modest gains)

Full cooled re-bench on M5 Max (gen-17) through a fresh new-pin binary — both published 35B qwen3_5_moe series, every quant, median of 3×512-token greedy decodes with a 60-second GPU cooldown after every generation. tok/s, vs each model's previously-published (old-pin) number:

quant Ornith-1.0-35B old→new (Δ) Qwen-AgentWorld-35B-A3B old→new (Δ)
UD-Q3 103.8 → 111.6 (+7.5%) 105.8 → 112.3 (+6.1%)
UD-Q4 87.0 → 102.3 (+17.6%) 94.5 → 99.8 (+5.6%)
UD-Q5 91.2 → 95.4 (+4.6%) 90.8 → 95.4 (+5.1%)
UD-Q6 87.1 → 93.1 (+6.9%) 88.2 → 92.7 (+5.1%)
UD-Q8 84.2 → 91.5 (+8.7%) 64.3 → 91.1 (+41.7%)*
MXFP4 90.1 → 107.8 (+19.6%) 85.7 → 102.6 (+19.7%)
NVFP4 87.8 → 94.6 (+7.7%) 77.1 → 94.1 (+22.0%)
MXFP8 80.0 → 84.8 (+6.0%) 62.4 → 91.0 (+45.8%)*
BF16 56.5 → 62.8 (+11.2%) 41.8 → 60.8 (+45.5%)*

All 18 models coherent (per-model warm-up read). No quant regressed — the RoPE fix's added transposes cost no measurable decode throughput. The reliable branch signal is roughly +5–22% across the cool-baseline quants.

* The three outsized AgentWorld deltas are dominated by old-pin thermal crush — those prior numbers were measured hot at a sequence tail (~62–64 tok/s) — not a genuine pin speedup. The new cooled numbers restore correct size ordering and match Ornith's siblings. Separately, Gemma-4-26B-A4B (gemma4, bump-only) landed ~55–60% above its M3-Max baseline in an earlier sanity bench (host-mismatched, directional only).

Both collections' published HuggingFace model cards were regenerated with these numbers.

Caveat for the first build

The branch's packaging changes are TS-only and did not rebuild the native addon, so the checked-in dev artifacts are still the old pin. The first yarn build:native (locally or in CI) deploys a fresh new-pin addon + metallib — the 4 gemma4 E2E tests fail only because they currently run against that stale old-pin addon and go green once it's refreshed. Validate that first build against the metallib integrity gate (now enforced by strict mode).

🤖 Generated with Claude Code


Note

Medium Risk
Changes affect published macOS binary compatibility (26.0 floor), release metallib fail-closed behavior, and several inference/quant paths (sym8 MoE, decode cache cadence, privacy-filter memory); mitigated by extensive new tests but release impact is real.

Overview
CI and docs now pin MACOSX_DEPLOYMENT_TARGET=26.0 and MLX_METALLIB_STRICT=1 for the whole workflow so builds and tests match published npm darwin-arm64 artifacts (26+ load floor, fail-closed metallib gates). README states prebuilt binaries require macOS 26+ and explains NAX kernel runtime gating.

Metallib packaging gains a large metallib-select Vitest suite (bound to baked METAL_PATH, byte-identity checks, deployment-floor parsing, strict vs dev scan behavior) aligned with packages/core/build.ts selection logic referenced in CI comments.

Decode cache cadence: flat DecodeStep::maintain_cache now calls clear_cache only (no synchronize), with a unit test using thread-local counters; docs/comments updated across engine and cache-limit modules.

Privacy filter: classify() uses maybe_clear_cache_for_privacy_filter_call (default every 8 calls, env override) instead of clearing after every call.

Banded attention takes a caller-supplied band_mask (build once per (T, band)), rejects negative bands, and skips bf16/f32 parity tests when test_support detects broken half GEMM or TF32-degraded f32.

Quant/convert: sym8 extended to qwen3_5_moe with co-quant coherence for switch/shared expert trios; gemma prequant import uses group_size 128, derives honest top-level quantization metadata, and verifies override coverage; related convert tests added.

Gemma4 caches layer_kinds at model init. LFM2 adds opt-in MLX_LFM2_PAGED_PREFILL_PAGED_ATTENTION for graph-native cache-hit prefill (default off). Chat session tests cover multi-MB image identity hashing.

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

Brooooooklyn and others added 30 commits July 1, 2026 17:01
…native SHA-256

computeByteListKey hashed every image/audio buffer byte-at-a-time in pure JS,
blocking the event loop for 10-100ms per media-bearing send()/sendStream()
call (measured 25-60x slower than node:crypto on identical buffers), which
stalls every other request handled by the same @mlx-node/server process.
Swap to node:crypto's native SHA-256 with the same length-prefixed framing;
the resulting key is still a purely in-process, order/length-sensitive cache
token, never parsed, so the algorithm swap is behavior-preserving.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…he per-layer loop

Qwen3_5VisionEncoder::forward rebuilt the O(seq_len^2) additive attention mask from scratch in every one of the 27 VisionEncoderLayer::forward calls, even though it's a pure function of cu_seqlens/seq_len/dtype that is identical across all layers in one forward pass (Gemma4VisionModel already hoists the equivalent mask once). Build it once per forward call via the new VisionAttention::forward_with_mask / VisionEncoderLayer::forward_with_mask (which take a pre-built mask instead of cu_seqlens), keeping the original per-layer forward() as a thin backward-compatible wrapper for other callers (e.g. PaddleOCRVisionModel) that still build their own mask per call.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…clearing every call

`classify()` called `synchronize_and_clear_cache()` unconditionally after
every invocation — a full GPU stall + allocator wipe on top of the actual
forward pass, on every single PII scan. Mirror the paged-decode cadence
gating (crate::array::memory) so the wipe only fires every Nth call
(default 8, override via MLX_PRIVACY_FILTER_CACHE_CLEAR_INTERVAL).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Every PagedKVWrite/PagedAttention dispatch rebuilt the kernel-name string
via std::ostringstream on every call, purely to look it up in MLX's own
Device::get_kernel cache, even though the name is fully determined by
parameters that never change for a loaded model. Cache the formatted name
behind a per-parameter-keyed map (same pattern as mlx_gated_delta.cpp's
get_or_create_kernel) so repeat calls skip the formatting and the copy.

Keyed field-wise (per-parameter) so distinct tuples never alias.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
PPDocLayoutV3ImageProcessor always resizes to a fixed 800x800 target, so
spatial_shapes_list (and therefore generate_anchors' output) is identical on
every detect() call for a given model instance. Cache (anchors, valid_mask)
in a OnceLock on the model struct instead of recomputing ~30-40 MLX ops
(arange/reshape/broadcast/concat/sigmoid) on every call.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…2B QAT linears

Google's per-output-channel symmetric QAT format carries exactly one scale per row (repack_symmetric_to_mlx_affine broadcasts it into every group), so group_size=64 buys nothing over the maximum legal 128 — it only doubles the scales/biases table and per-group kernel reads for zero numerical benefit.

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

The FLAT `DecodeStep::maintain_cache` default called `synchronize_and_clear_cache()` every 256 decode steps, but `synchronize()` blocks on the thread's default stream — which is idle at that point (the forward runs on `generation_stream`, only made default for the brief `StreamContext` scope around the forward build, then restored). The loop's own `y.eval()` already forces everything scheduled so far, so the extra synchronize is redundant regardless of which stream it targets. Switch to `clear_cache()` only, matching mlx-lm's reference decode-loop cadence.

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

Qwen3.5-MoE's `forward_pre_norm_inner`, `forward_pre_norm_inner_with_tape`
(the eager-MTP verify primitive), and `forward_inner` always built a
`create_causal_mask` array for full-attention layers whenever seq_len > 1
— exactly the MTP-verify (`[1, K+1]`) and chunked-prefill shapes — and
passed it explicitly to `Qwen3_5Attention::forward`, even though that's
the identical attention module the dense Qwen3.5 model reuses (via `pub
use` in qwen3_5_moe/mod.rs) and dense already always passes `mask: None`
to hit the fused "causal" SDPA kernel. Mirror dense: pass `None`
unconditionally so every full-attention layer picks the fused kernel
instead of a materialized boolean-mask array, on every decode step for
the life of a generation.

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

Gemma4Inner::compute_layer_kinds() re-derived the per-layer paged/sliding/shared-KV
routing table (a BTreeMap/BTreeSet grouping + sort pipeline in
transformer/kv_cache_spec.rs) from scratch on every single prefill chunk and
decode step, even though it is a pure function of the immutable Gemma4Config.
Compute it once in Gemma4Inner::new() and cache it as a field; the four paged
call sites are unchanged since the accessor keeps its Result<Vec<...>> signature.

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

banded_attention rebuilt the arange/sub/abs/less_equal/where_ band mask from scratch on every one of the 8 privacy-filter transformer layers, even though band_for_layer only ever alternates between 2 distinct (T, band) pairs per forward_logits call. Thread a precomputed band_mask through Block/AttentionLayer/banded_attention instead, built once per distinct band value in forward_logits.

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

Precompute a block-ordered (queries-flat | gate-flat) q_proj weight once at
load time so forward()/forward_paged() slice two row-contiguous halves of
one matmul instead of reshaping the checkpoint's per-head-interleaved
q_proj output, which forced a strided copy_gpu_inplace Metal dispatch on
every full-attention layer, every prefill and decode call.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…per full-attention layer

During Qwen3.5-VL paged prefill, every FullAttentionPaged layer independently
recomputed the M-RoPE cos/sin table + interleaved axis-selector gather from
`position_ids`, even though all full-attention layers in one forward pass
share byte-identical position_ids/mrope_section/dtype (`init_mrope_layers`
seeds every layer from the same config). With `full_attention_interval=4`,
~1/4 of decoder layers redid this ~10-15-op sequence from scratch. Thread a
per-forward-pass `mrope_cache` scratch slot through
`Qwen3_5Attention::forward_paged` so only the first full-attention layer
computes the selected cos/sin; every later layer in the same prefill reuses
it. Affects both dense and MoE Qwen3.5-VL (MoE reuses the same attention
type). Byte-identical output preserved (new unit test + existing e2e
determinism gate).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Replace VecDeque<u64>+retain()/push_back() LRU bookkeeping with
hashlink::LinkedHashSet<u64> so cache-hit "touch" (lookup_prefix,
register_prefix) is O(1) amortized instead of O(n) over the whole
LRU order -- a long shared prefix (e.g. 4096 tokens at block_size=16)
was doing 256 O(n) retains per request just for LRU bookkeeping.
try_evict_lru_for_allocation no longer clones the entire lru_order
into a fresh Vec on every allocation that hits an empty free pool.

All 42 existing block_allocator unit tests pass unchanged; behavior
is byte-identical, only the internal data structure changed.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Port the PR #56 native_kv_write_enabled()-gated try/fallback pattern (already default-on for Gemma4/Qwen3.5/LFM2) into TransformerBlock::forward_paged_adapter, Qwen3 dense's sole paged forward path: prefer update_keys_values_native + gather_kv_for_decode_graph, falling back to the synchronous update_keys_values/gather_kv_for_decode on error or via MLX_QWEN3_NATIVE_KV_WRITE=0. Removes a per-layer, per-decode-token blocking mlx_metal_synchronize() + command-buffer host wait that Qwen3 was the last family still paying.

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

Every fresh paged chat_session_start turn reconstructs self.caches' conv-layer
state via a full re-embed + causal-SDPA reconstruction over the entire cached
prefix (run_conv_only_prefill), even on a plain "resend growing conversation"
continuation whose live caches already hold that state. Add conv_state_reusable()
+ a skip path that reuses the live conv state when the cached-attention-prefix
length and content exactly match cached_token_history from the previous
successful turn, keeping paged_perf_prefill_tokens telemetry honest on the fast
path. Gated behind MLX_LFM2_CONV_STATE_REUSE, DEFAULT OFF: the reused incremental
conv state differs materially from the single-pass reconstruction it replaces
(~40 ULP, near-tie argmax may flip; LFM2 ShortConv T=1-vs-batched bf16) — arguably
closer to flat continuous generation, but a material change, so it ships opt-in
until a conv oracle validates enabling it by default. Default-off is byte-identical
to prior behavior (all paged-vs-flat parity siblings unchanged).

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

Mirrors the qwen3_5/gemma4 forward_paged cache-hit branch: attempt
gather_kv_for_prefill_chunk (reads the KV pool through MLX graph
dependencies, no forced host sync) before falling back to read_kv_range
(which forces eval_pending_pool_write_for_layer per layer on every
multi-turn continuation).

Held behind MLX_LFM2_PAGED_PREFILL_PAGED_ATTENTION (default off): the
bridge reads the same physical KV bytes, differing only in the attention
kernel (fused paged-attn vs explicit-mask SDPA, the accepted ~1-ULP
class), but the one available LFM2 checkpoint is greedy-decode degenerate
so there is no green automated parity gate yet. Flip on once a
gemma4-style paged-vs-flat gate exists on a stable checkpoint.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…matmul on the paged path (gated)

Persistence loads a tied/quantized embedding via load_quantized_packed
(packed-resident) instead of legacy load_quantized (full dense
pre-dequant) ONLY for the paged (compiled-backend), non-MTP, non-VLM
case, where the tied lm_head projection on the paged
prefill/decode/MTP-verify path now routes through Embedding::as_linear
(packed quantized_matmul) when the embedding is packed. Flat/sym8,
MTP-draft, and VLM image turns keep the legacy load (they still eval a
per-turn get_weight()); extending the win to them is a follow-up.

The paged gate also requires compiled_forward_backend_available():
use_block_paged_cache == Some(true) is only config INTENT — the paged
adapter is created solely when the compiled backend is available
(Metal), so a paged-config checkpoint on a non-Metal/CUDA backend runs
flat and stays on the legacy load (no per-turn dequant regression). The
projection change is guarded by is_packed_quantized(), so every
non-packed checkpoint is byte-identical.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…opt-in, default off)

The MoE MTP stepper carries a persistent drafter KV cache across decode
cycles within a turn (commit_mtp appends the committed tokens' exact K/V;
begin_cycle trims to the committed cursor) instead of rebuilding a fresh
cache every cycle, mirroring the dense stepper. Gated behind
MLX_QWEN35_MOE_MTP_COMMITTED_HISTORY (default off) so the default path is
byte-identical to the prior cycle-history v1; the flag doubles as the
same-binary A/B instrument. The prompt-prefix seed is ported but inert (no
MoE call site emits prompt hiddens yet).

Validated end-to-end by new synthetic tests: a tiny random-init MoE
checkpoint with a real MTP head (random save now emits mtp.* and round-trips
the layer count as mtp_num_hidden_layers) decodes crash-free with cycles>1,
stable acceptance metrics, and deterministic repeat output in BOTH flag
states (byte-identity vs AR is asserted on the real-weights deep gate; on
random weights it measures kernel rounding, not correctness). Real MoE-MTP
checkpoints on hand are all VLM (forced block-paged, where the eager MTP
stepper is unreachable), so the real-weights test skips gracefully there;
the perf A/B / default-flip is deferred until a text MoE-MTP checkpoint
exists.

Co-Authored-By: Claude Fable 5 <[email protected]>
Attention (q/k/v/o), GDN linear-attention (in_proj_qkvz/ba/out_proj), and
shared-expert MLP body already route through the same LinearProj/
QuantizedLinear/try_build_ql machinery as dense qwen3_5's working sym8
path — only a blanket loader-level guard and a stale convert-time
allowlist entry were blocking `--q-mode sym8` for qwen3_5_moe. Relax
both, keep the per-expert switch_mlp gather path (no sym8 kernel) and
the router/shared-expert gate (accuracy-forced affine-8, matching
mlx-lm's quant_predicate) on affine as before, and disable speculative
MTP for sym8 checkpoints (the MTP module's own weight-builder closures
have no sym8 arms wired, so the loader fail-softs to plain AR)
mirroring dense qwen3_5.

Sym8 keeps the family text-only, mirroring dense: the loader also skips
the vision encoder under sym8 (loud warn, image turns fail loud) until
sym8+VLM prefill is validated.

Co-Authored-By: Claude Fable 5 <[email protected]>
The dense loader reads the MTP layer count only from the HF-convention
config keys (mtp_num_hidden_layers / num_nextn_predict_layers); the serde
field name n_mtp_layers is ignored on load. The dense saver never injected
the HF key, so a saved dense-MTP checkpoint reloaded with n_mtp_layers = 0
and its speculative MTP head silently dropped. Inject the key next to
model_type, exactly mirroring the MoE saver.

Adds a save-then-reparse unit test on a tiny dense config (fails without
the injection, passes with it).

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_013gnhVxdYQQs6Nkw2sX7aKk
coquant_group_members had tables for LFM2_MOE, LFM2_FFN, and DENSE_MLP
only, and its doc still claimed qwen3_5_moe "has no sym8 dispatch and
fails loud up front on any sym8 config" — stale since the MoE non-expert
sublayers gained real sym8 dispatch. A sym8 default now reaches the MoE
loader's all-or-none trios: the switch_mlp experts (3-D, forced affine-8)
and the shared_expert MLP body (2-D, sym8 or forced affine-8). A member
that also fails the affine K % group_size alignment would silently stay
dense next to quantized siblings, and the loader drops a partial trio to
its dense setters — packed payloads down the dense route.

Add the two verified trios (switch_mlp + shared_expert) to the table; the
router .mlp.gate and .mlp.shared_expert_gate stay per-tensor, matching the
loader's independent try_build_ql arms. Extend the exact-tail-match doc
for the new suffixes and refresh the stale rationale.

New odd-geometry test proves one alignment-ineligible member forces its
whole trio dense (warn + drop, matching the existing groups) while the
per-tensor gates and fully aligned control trios still quantize.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_013gnhVxdYQQs6Nkw2sX7aKk
The dense qwen3_5 loader wraps every dense fallback of a quantizable
projection in ensure_dense_weight_floating; the MoE loader had no guards
at all. A packed weight with stripped/missing quant sidecars makes
try_build_ql/try_build_qsl return Ok(None), dropping the whole group to
the dense setters — the switch_mlp setters are infallible and none of the
others validate dtype, so packed Uint32/int8 bytes entered dense expert
math silently (garbage logits, no error).

Mirror the dense loader completely: guard the switch_mlp and
shared_expert trios, the router gate and shared_expert_gate, attention
q/k/v/o, GDN in_proj_qkvz/in_proj_ba/out_proj (including the split
qkv+z / b+a pairs), the non-MoE dense MLP trio, embedding, and lm_head —
in both the quantized and the unquantized (fully-stripped checkpoint)
arms. Norms, biases, conv1d, dt_bias, and A_log are never quantized and
stay unguarded per the ensure_dense_weight_floating contract.

Also update the coquant_group_members doc clause to state the loader now
rejects packed members on the dense route.

New negative test: a packed Uint32 switch_mlp (and shared_expert) member
without sidecars fails loud naming the key, instead of silently
installing and surfacing only the unrelated missing-mandatory-weights
error.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_013gnhVxdYQQs6Nkw2sX7aKk
…ault

try_build_qsl's Sym8 arm returned Err unconditionally, with no
{prefix}.scales-presence check. A checkpoint with top-level mode "sym8"
whose switch_mlp trio was legitimately forced DENSE by convert's
group-coherence pass (no .scales sidecar, no per-layer override, so the
prefix resolves to the default Sym8 PLQ) therefore failed to load with
the "re-convert the checkpoint" error before it could reach the
dtype-guarded dense fallback.

Treat an absent .scales sidecar as the "this layer is not quantized"
signal and return Ok(None), matching try_build_sym8_quantized_linear's
documented contract (and the dense loader + the MoE 2-D try_build_ql,
which already behave this way). When .scales IS present the loud Err is
kept verbatim: 3-D stacked experts have no sym8 kernel, so quantized
bytes under a sym8 PLQ are corrupt metadata and must never silently
fall back.

Pre-existing at 95fc078; surfaced by the coherence-table extension,
which makes forced-dense trios a normal convert emission. Composes with
the new ensure_dense_weight_floating guards: the dense fallback still
validates the trio's dtypes after the Ok(None) hand-off.

Adds a loader regression test building a faithful post-coherence sym8
emission (genuinely sym8-quantized q_proj + dense f32 odd-K switch trio
with no .scales and no override) and asserting the load succeeds with
the trio landing dense. The existing fail-loud negative test
(.scales present under a sym8 override) passes unmodified.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01BcztCkraQ7SsHu3kPGh8G3
…p without sidecars

d8c2770 made try_build_qsl's Sym8 arm return Ok(None) whenever
{prefix}.scales is absent, so forced-dense trios load via the
dtype-guarded dense fallback. But Sym8 reaches a switch prefix two ways
through effective_plq_for — the top-level DEFAULT falling through, or a
DIRECT per-layer entry — and only the default has a legitimate dense
reading. An EXPLICIT sym8 override for a switch prefix cannot come from
convert (sym8_eligible rejects 3-D tensors and forces every quantized
switch_mlp.* member to an affine-8 override; the group-coherence pass
emits forced-dense trios with NO override; recipes reject sym8 outright;
sym8-mode entries always equal the default so no sym8 override is ever
recorded for any key), so it is by construction hand-edited/stale
metadata — and the old arm silently installed the float weights dense
instead of surfacing the lie.

Restore provenance to the decision: absent .scales resolves Ok(None)
ONLY when no explicit per-layer entry exists for the prefix (mirroring
effective_plq_for's direct lookup — the gate/GDN-merge fallbacks never
key on switch prefixes, so contains_key is exact); an explicit sym8
entry keeps the loud no-sym8-kernel Err with or without sidecars.
Present .scales fails loud as before. No convert-emitted checkpoint is
affected — this is hardening against lying metadata only; the packed/
int8 storage variants already failed loud via
ensure_dense_weight_floating.

Adds a regression test: explicit sym8 override + float 3-D expert
.weight + no .scales + another genuinely-quantized tensor must fail the
load with the switch_mlp sym8 error (RED: the load fully succeeded
before this fix). The d8c2770 default-derived forced-dense test and the
.scales-present negative test pass unmodified.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01BcztCkraQ7SsHu3kPGh8G3
PR #70 deleted the qwen3_5 dense/MoE compiled C++ forwards, the shared
C++ weight registry (mlx_common_weights.cpp), and the lfm2 compiled TUs;
qwen3_5 dense + MoE now run pure-Rust eager paths everywhere (flat,
paged, MTP). A sweep of comments still described the deleted world.
Rewrite each to match the verified current control flow:

- qwen3_5/persistence.rs: the dense sym8 flat-pin block no longer claims
  the paged decode graph is mlx::core::compile'd — the pin is documented
  as retained conservatively (sym8 under dense paged decode is simply
  unvalidated; MoE/gemma4 already ship sym8 under paged). Reword the
  warn! string to match — the ONLY non-comment change in this commit.
  The MTP-under-sym8 skip now cites the real reason (no sym8 arm in the
  MTP quant builders) and the Stage-1 comment drops g_compiled_caches.
- qwen3_5/model.rs: paged stepper/core docs describe the pure-Rust
  run_paged_decode_step dispatch (no C++ paged session, no
  CompiledResetGuard, no use_cpp_paged/cpp_session_ready); Qwen35Decode
  doc drops the forward_compiled arm; MTP gate docs drop
  init_mtp_compiled/prefill_mtp_commit in favor of begin_mtp_decode's
  prompt-prefix seed; phantom "compiled-path locks" comment deleted
  (compiled_lock now only hosts the shared model-id counter).
- qwen3_5_moe/model.rs + persistence.rs: paged prefill/stream docs point
  at the pure-Rust paged decode; MoE-MTP weight-normalization comment
  drops the compiled MTP graph and g_weight_transposes_3d.
- engine/backend.rs: DecodeStep::forward needs_squeeze attribution,
  forward_with_token PERF-SEAM family list, TurnSetup field-consumer doc
  (end_decode is a universal no-op), and the committed_history_active
  doc (describes the real MtpCommitAnchor / begin_cycle chained-anchor
  wiring; "chain_start = 0 draft mask" no longer exists).
- engine/mtp_turn.rs / qwen3_5/mtp_decode.rs: g_compiled_caches ->
  main layer caches; "compiled verify/forward/graph" -> eager wording;
  native sparse-verify gate documented as currently inert.
- engine/persistence.rs: compiled_forward_backend_available doc is now a
  plain Metal-availability probe description (name noted as historical).
- engine/session.rs: relabel/end_decode hook comments follow suit.
- mlx-sys mlx_paged_dispatch.h: the C++ PagedKVWrite/PagedAttention
  Custom primitives are the graph-native default for every paged family
  via PagedKVCacheAdapter (native write / graph gather); the Rust
  dispatcher is the synchronous fallback — not the other way around.
  mlx_common.h + mlx_na_int8.cpp drop the deleted linear_proj consumer.
- gemma4/persistence.rs: model_id attribution corrected to gemma4's
  private MODEL_ID_COUNTER (it does not draw from the qwen35 counter).

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01BcztCkraQ7SsHu3kPGh8G3
- v1 (flag-off baseline): defensively remove
  MLX_QWEN35_MOE_MTP_COMMITTED_HISTORY at startup — the stepper reads
  the flag once per process, so an inherited environment must not flip
  the v1 baseline ON. Converted from #[tokio::test] to the v2 shape
  (plain #[test] + manual runtime build) so the unsafe remove_var runs
  before the tokio workers/model threads spawn, mirroring v2's set_var.
- v2: make the set_var SAFETY comment claim exactly what holds — this is
  the binary's only #[test] (one libtest thread, no concurrent env
  access) and the flag's only in-process readers spawn after the set —
  instead of the overstated "single-threaded at this point".

Both binaries re-run green (1 passed each, GPU, one at a time).

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01BcztCkraQ7SsHu3kPGh8G3
Comment/doc-only sweep completing the comment-honesty batch: fix the
stale leftovers that still described the deleted qwen3.5 compiled C++
forwards, the removed prefill_mtp_commit, and the pre-native paged
K/V write path.

- qwen3_5_moe prefill lead-in: K/V write is update_keys_values_native
  (graph-native default) with sync update_keys_values as fallback
- ChatBackend::begin_decode doc: describe what implementations do now
  (dense decode-entry trace + relabels; lfm2/gemma4 ignore the setup;
  end_decode is an unoverridden no-op)
- backend.rs paged/MTP trait docs, types.rs enable_mtp,
  adaptive_depth.rs header: drop compiled-graph/compiled-paged phrasing
  (everything is pure-Rust eager)
- qwen3_5 model.rs / paged_forward.rs: replace prefill_mtp_commit
  references with the prompt_hidden -> begin_mtp_decode seed flow
- gemma4 persistence: sym8 paged rationale now cites qwen3_5's
  conservative validation-scope pin, not a compiled registry
- mlx_paged_dispatch.h: qualify gather_kv_for_prefill_chunk as
  family-dependent (opt-in default-OFF on lfm2, absent on qwen3)
- parity test headers: both sides are Rust eager forwards; no
  "compiled C++ production fast path" claim

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01BcztCkraQ7SsHu3kPGh8G3
…imports

Gemma-QAT (wNa8o8) imports never run the quantize block, so the top-level
quantization / quantization_config values in the written config.json were
the generic --quantize CLI defaults (affine / 4-bit / group_size 64) while
every affine sidecar the importer emits is a 128-group repack. The value is
unread in-repo (the loader always uses the complete per-layer overrides),
but an external mlx-lm-style loader that trusts the top-level default for a
tensor without an override would dequantize at the wrong group size.

Derive the top level from the importer's own override map instead
(top_level_quant_metadata): mode and group_size are asserted uniform across
all overrides (they are by construction — 128/affine everywhere) and bits,
which genuinely varies per module (E2B mixes 2- and 4-bit), records the
modal width with ties broken wider. The block is written from the new
quant_bits_effective alongside the existing effective mode/group_size.

Test-first: the new synthetic end-to-end test (real convert_model pipeline,
tiny fabricated wNa8o8 checkpoint) failed on the old code with
group_size=64 in both blocks; bits=4 and mode=affine only matched by
coincidence with the CLI defaults.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01BcztCkraQ7SsHu3kPGh8G3
Every .scales-bearing tensor the gemma-QAT importer writes must carry a
per-layer quantization override, or external loaders would resolve it
through the top-level config default and mis-dequantize. The emitters
uphold this by construction (affine triplet + override are inserted
together; the bf16-dequantized I8 modules emit a dense .weight only, so no
exclusion is needed), so the guard is a tripwire against a future emitter
change decoupling the two.

Deliberately scoped to the gemma-prequant import path: the generic
quantize paths record overrides sparsely (only non-default decisions), so
".scales without override" is their normal case and a general guard would
either be vacuous or need mode-specific packed-layout shape re-derivation
that risks failing working conversions (inline MoE MTP tensors also keep
.scales while their overrides are deliberately excluded from config.json).

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01BcztCkraQ7SsHu3kPGh8G3
fast::rope varies the rotation position along axis -2 of its input, so
it must see the [B, H, T, D] layout — matching mlx-lm's
qwen3_next.py (rope applied after .transpose(0, 2, 1, 3)) and this
repo's own M-RoPE arm, gemma4, lfm2, and qwen3 paths. The qwen3.5
scalar arms (flat forward + forward_paged) applied it on [B, T, H, D],
which rotates along the HEAD axis: every token in a multi-token forward
got the same angle (offset + head_index), collapsing per-token
positions within any prompt/prefill chunk. Decode masked the bug
because RoPE is relative and a per-head constant bias cancels in
same-head QK products across 1-token forwards.

Affects the whole qwen3.5 family through the shared attention struct
(dense, qwen3_5_moe re-export, MTP, VLM text-decode scalar arm).
Prefill logits change on every host; chunked and single-shot prefill
now agree on rotation angles.

Op-level probe (f32, isolated fast::rope): [B,H,T,D] chunk-vs-stepwise
diff exactly 0.0; [B,T,H,D] diverges 2.65/3.23/4.35 at t=1/2/3.
New regression test prefills one KV cache with a single 4-token forward
and one with 4 stepwise forwards, then compares a probe-token decode:
0.053 before the fix, 1.4e-4 after (all f32 to stay off this host's
broken half-precision NAX kernels).

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01BcztCkraQ7SsHu3kPGh8G3
Brooooooklyn and others added 18 commits July 2, 2026 19:12
…anary

The vendored MLX pin's NAX steel GEMM (every non-f32 matmul on gen>=17
GPUs under macOS 26.2+) returns deterministic garbage for unaligned-K
tiles: K < 128 corrupts every output element and K remainders in
[128, 256) corrupt N-tiles past the first; the fused full SDPA kernel
is also wrong by O(1) where the vector kernel and a host f32 reference
agree. Stock pre-NAX MLX wheels are correct on the same shapes and
hardware, and the metallib in use is the known-good build — this is a
kernel-source bug at the pin (upstream has post-pin NAX fixes).

The three tiny-config chunked-vs-single-shot parity tests (qwen3
uneven-tail, qwen3_5_moe even-chunk + uneven-tail; hidden 64-128,
head_dim 32) compute almost entirely inside that broken regime, and
chunking changes which kernel class each token's math takes (a 1-token
tail chunk dispatches the CORRECT M=1 GEMV where single-shot rows go
through the broken GEMM; per-chunk context lengths change score/out
matmul shapes) — so the paths deterministically diverge O(0.6-0.9)
with the chunk bookkeeping verified correct (byte-equal for
kernel-uniform geometries, exact patterned pool write/read round-trips
for every geometry). Forced runs on an affected host
(MLX_TEST_FORCE_HALF_PARITY=1) still fail after the qwen3.5 RoPE-axis
fix: qwen3 0.62, moe 0.91/0.72 — the divergence is kernel-class, not
chunking, and not rope.

Add test_support::half_gemm_untrustworthy(): an [8,64]x[64,64] bf16
canary vs host f32. Affected hosts skip with a mechanism-citing
message; healthy hosts (M1-M4, or a future repaired MLX pin) run the
assertions unchanged. No tolerances were changed.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01BcztCkraQ7SsHu3kPGh8G3
…s copies)

The scalar-arm comment claimed the rope Metal kernel handles the
transposed stride without a copy. qwen3.5 uses partial rotary
(rope_dims < head_dim), which always takes the kernel's copying
dims_ < D branch; the transposed layout costs a strided rather than
vector copy — the same price mlx-lm pays. Reviewer-verified against
mlx/backend/metal/rope.cpp.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01BcztCkraQ7SsHu3kPGh8G3
The vendored MLX pin defaults MLX_ENABLE_TF32=1 (mlx/utils.h), and on
gen>=17 GPUs + macOS 26.2+ that default silently routes every f32 GEMM
with M>1 (matmul.cpp:367) and every f32 fused full-SDPA with q_len>8
(scaled_dot_product_attention.cpp:178) to NAX kernels that truncate
inputs to 11-bit TF32 mantissas. Measured on an [8,64]x[64,64] f32
matmul vs a host-f64 reference: max_err 3.1e-3 with the default vs
9.5e-7 with MLX_ENABLE_TF32=0 — a ~3000x precision loss invisible to
dtype inspection.

Three f32 tests calibrated for true-f32 accumulation fail determinis-
tically in that regime with no bug in this repo, and all three pass in
the same binary with MLX_ENABLE_TF32=0 exported:

- array::banded_attention::banded_attention_matches_reference_f32:
  fused-vs-composed parity 9.35e-4 vs the 5e-5 true-f32 oracle bound.
- transformer::attention_vjp_test f32 no-mask + causal finite-diff:
  the central-difference signal (2*eps*grad ~ 1e-6 on a ~0.5 loss)
  drowns in TF32 forward noise (~1e-4); 6/9 samples fail, including
  numerical estimates of exactly 0.0 where f(x+e) and f(x-e) round to
  the same TF32-degraded value. 9/9 pass with TF32 off.

Add test_support::f32_gemm_tf32_degraded() — same runtime-canary
pattern as half_gemm_untrustworthy (skip with mechanism, one shared
MLX_TEST_FORCE_HALF_PARITY=1 bypass) — and gate the three tests on it.
The probe self-adapts: exporting MLX_ENABLE_TF32=0, running pre-gen-17
hardware, or bumping to an MLX pin that flips the default all restore
true f32 and re-enable the assertions automatically. No tolerances
changed.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01BcztCkraQ7SsHu3kPGh8G3
…anary

banded_attention_matches_reference_on_random_inputs failed on gen>=17
hosts at max_abs_diff 0.988 (tol 0.023, output max_abs 0.96) on the
first case (t=64). Bisected against a host-f64 banded-attention truth
computed from the same bf16-rounded inputs: the fast path (fused bf16
full-SDPA, q_len>8 — the NAX kernel class the item-G review measured
0.1-1.9 off per row) errs 2.22 and the reference (composed bf16 matmuls
with K=64 — the NAX unaligned-K garbage class) errs 2.05. Both sides
are kernel garbage on such hosts, so the parity assertion asserts
nothing; skip it behind the existing half_gemm_untrustworthy canary
(same skip-with-mechanism + MLX_TEST_FORCE_HALF_PARITY=1 bypass as the
item-G chunked-prefill gates). Healthy hosts and post-fix MLX pins run
it unchanged. No tolerances changed.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01BcztCkraQ7SsHu3kPGh8G3
…ries

forward_64_index_gather_sort_branch failed on gen>=17 hosts (token 0
dim 0: got 0.009033 want 0.001037). Bisection:

- The 32-token bf16 router gate is a [32,4]@[4,4] GEMM (M>1, K=4) —
  the NAX unaligned-K garbage class. Probed vs host-f64 truth:
  max_err 3.2; token-0's expert-2 logit computes 0 where the true
  value is 1.0. Every token's routing gates are corrupted before the
  experts run; a 31-token variant (unsorted expert dispatch) fails
  identically, and the single-token sibling tests stay green only
  because M=1 dispatches the correct GEMV.
- Independently, the >= 64-index branch's sorted expert dispatch
  (gather_mm_rhs_nax, matmul.cpp:2408) is garbage at EVERY probed K
  vs host-f64 truth — K=4: 2.7, K=64: 5.0, K=128: 3.7, K=256: 3.9,
  K=2048: 2.9 — unlike the plain NAX GEMM (unaligned-K only). With
  the pin's MLX_ENABLE_TF32=1 default, f32 sorted gather_mm ABORTS
  outright (dispatch enters the NAX path whose float32 JIT template
  throws an uncatchable foreign exception).
- The gather-sort Rust logic is exonerated: the identical 32-token
  forward in f32 with MLX_ENABLE_TF32=0 (same gather_sort /
  scatter_unsort code, non-NAX kernels) matches the per-token
  reference to 1.5e-8.

Add test_support::sorted_gather_mm_untrustworthy() as a second probe
class (same pattern + shared MLX_TEST_FORCE_HALF_PARITY=1 bypass;
separate probe because an MLX bump can fix the two kernels
independently) and skip the test when either canary fires. Also
restore half_gemm_untrustworthy's doc comment, which the previous
commit had accidentally merged into the new f32 canary's docs.
No tolerances changed.

Production note (for the MLX pin bump item): sorted gather_mm is the
kernel real bf16 MoE prefill dispatches once a forward carries >= 64
token-expert indices, and it is broken at production-scale K on these
hosts.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01BcztCkraQ7SsHu3kPGh8G3
… canary

packed_affine_as_linear_matches_dense_matmul failed on gen>=17 hosts at
max_err=0.08248 (bound 5e-2). Bisected by checking BOTH sides against a
host-f64 truth computed from the dequantized table and bf16-rounded x:

- as_linear (quantized_matmul, the Task-17 tied-head path under test):
  err 1.6e-4 — CORRECT.
- the reference `x @ dequant(table)^T` (bf16 [2,64]@[64,8] GEMM, K=64 —
  the NAX unaligned-K garbage class): err 0.0825, which IS the entire
  observed failure, on logits whose true max magnitude is only 0.024.

The feature is fine; the oracle is the broken side on such hosts. Skip
behind the existing half_gemm_untrustworthy canary (skip-with-mechanism
+ MLX_TEST_FORCE_HALF_PARITY=1 bypass). Healthy hosts run it unchanged.
No tolerances changed.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01BcztCkraQ7SsHu3kPGh8G3
Bump the mlx submodule 156 commits, v0.31.1-55-ga8776b7b ->
v0.31.2-130-ge9463bbf (fork mlx-node/mlx main, zero local patches).

Motivation: items G/H proved the old pin's NAX kernels are numerically
broken on gen-17 (M5) + macOS >= 26.2 hosts: bf16 unaligned-K steel GEMM
garbage, bf16 causal full-SDPA (q_len > 8) wrong on every row at
production shapes, bf16 sorted gather_mm (gather_mm_rhs_nax) garbage at
every K, and f32 sorted gather_mm SIGABRT under the default env. The
range includes the NAX addmm/split-K fix a6222f53 plus the NAX
build-config fixes (ae3db542 deployment-target gating, 99f040ef metallib
link flags); post-bump probes on this host measure all three bf16
classes at bf16-rounding scale (0.002-0.008 vs 2.5-5.0 before) and the
f32 gather abort is gone.

Canary re-enables: half_gemm_untrustworthy and
sorted_gather_mm_untrustworthy now report HEALTHY, so all six
bf16-gated tests run again and pass - qwen3 chunked uneven-tail at
max_abs_diff = 0, the qwen3_5_moe chunked pair at 0.006/0.028 vs tol
0.25 with matching argmax, banded bf16, lfm2 gather-sort, and the
packed-affine embedding parity. f32_gemm_tf32_degraded still fires:
upstream keeps MLX_ENABLE_TF32=1 (utils.h:196) with unchanged f32 NAX
dispatch gates, so the f32 trio keeps skipping under the default env
(passes with MLX_ENABLE_TF32=0); the TF32 default posture is left as an
explicit user policy decision.

No FFI changes needed; mlx-sys and mlx-core build clean against the new
pin. Full mlx-core lib suite 1929 passed / 0 failed, mlx-paged-attn
220/0, paged/prefix-cache integration set 32/0, real-checkpoint
paged-vs-flat parity + delta-chat green on qwen3.5-0.8b-mlx-bf16, and a
16GB bf16 MoE (lfm2.5-8b-a1b) session gate exercises the previously
broken gather_mm production path with coherent output.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01BcztCkraQ7SsHu3kPGh8G3
…loors

The vendored MLX pin defaults an unset CMAKE_OSX_DEPLOYMENT_TARGET to the
build HOST's macOS version (CMakeLists.txt "Build for the host system"),
and the metal compiler stamps the SDK default min-OS when no
-mmacosx-version-min is passed. mlx-sys set neither, so the deployment
floor of every artifact silently tracked whichever machine (or CI runner
image) happened to build it.

Plumb an explicit floor through:
- forward MACOSX_DEPLOYMENT_TARGET as a -DCMAKE_OSX_DEPLOYMENT_TARGET
  define (a define overrides a stale CMakeCache.txt from a restored CI
  cargo cache; the environment variable alone cannot)
- pass -mmacosx-version-min to the paged_attn.metallib compile
- rerun-if-env-changed so toggling the floor rebuilds

No behavior change when the variable is unset. README now documents the
real floor: prebuilt npm binaries are built on macos-26 runners against
the macOS 26 SDK (MSL 4) and do not load on macOS 15 or older; MLX's NAX
kernels additionally require a >= 26.2 floor at build time and macOS 26.2
at runtime.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01BcztCkraQ7SsHu3kPGh8G3
…gate

copyMetallibs() scanned target/*/release/build/mlx-sys-*/out/lib and
shipped the FIRST directory containing mlx.metallib — unbound to the
addon napi just built, in filesystem readdir order. Stale mlx-sys hash
dirs from earlier toolchains or earlier MLX submodule pins survive next
to the current one (locally and in CI-restored cargo caches), so a pin
bump could silently pair the previous pin's metallib with the new .node
and publish it: mismatched kernels produce garbage inference output with
no load-time error. The scan also never matched the plain
target/release/build layout, only target/<triple>/release/build.

Selection is now deterministic and current-build-bound
(packages/core/metallib-select.ts, unit-tested):
- scan only the tree the napi build used (same targetDir/triple/profile
  as the build options; napi always passes --target), with the plain
  layout as a fallback that is never mixed in
- among mlx-sys-* candidates, the dir cargo touched most recently wins
  (invoked.timestamp / build-script output / metallib mtime)
- hard gate before any copy: minimum-size floor plus expected kernel
  inventory — including the current pin's NAX kernels (affine_qmv_wide,
  steel_gemm_segmented_nax) on hosts where MLX builds them (SDK and
  effective deployment target >= 26.2, mirroring MLX's kernel CMake
  gate). A mismatch fails the build loudly instead of shipping.

Stale dirs are deliberately not deleted (they are live cargo cache;
removal forces a full MLX rebuild). Multiple candidates are logged with
sizes and timestamps.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01BcztCkraQ7SsHu3kPGh8G3
…AX kernels

Deployment-target policy for published artifacts: a single darwin-arm64
metallib/addon with a macOS 26.0 load floor that still carries the NAX
(gen-17 tensor-core) kernels, relying on MLX's runtime dispatch
(is_nax_available: gpu gen >= 17 && macOS >= 26.2) so 26.0/26.1 users
load-and-run on the standard kernels while 26.2+ M5 users get the fixed
NAX paths.

Upstream MLX refuses to BUILD the NAX kernels below a 26.2 deployment
target — and measurement shows that gate is a correctness gate, not
just packaging: below 26.2 the MetalPerformancePrimitives headers bind
the pre-26.2 compatibility tensor-ops intrinsics
(__tensorops_impl_matmul2d_op_cooperative_destination_*), which
miscompute (a uniform-26.0 build fired the half-GEMM canary with the
same unaligned-K garbage signature the MLX bump had just fixed).

Mechanism:
- Submodule pinned to fork branch nax-macos-26-0-floor (de7e3429 =
  upstream e9463bbfc + one upstream-quality patch): new cmake option
  MLX_METAL_FORCE_NAX builds the NAX kernels below a 26.2 floor, always
  compiling them at -mmacosx-version-min=26.2 (their required ABI)
  while the metallib links at the floor, and keeps MLX_METAL_NO_NAX
  undefined so runtime dispatch stays compiled in. The C++ still
  compiles at the floor, so __builtin_available(macOS 26.2) remains a
  real runtime check instead of constant-folding true.
- build.rs always passes -DMLX_METAL_FORCE_NAX=ON (inert when the
  floor is already >= 26.2 or the SDK cannot build NAX).
- ci.yml exports MACOSX_DEPLOYMENT_TARGET=26.0 workflow-wide so the
  published artifact floor stops ratcheting with runner images and the
  test jobs exercise the same floor that ships.
- metallib-select's shouldExpectNaxKernels mirrors the forced gate
  (SDK >= 26.2 AND effective target >= 26.0); the NAX markers stay
  hard-required for CI-built artifacts.

Validated on M5 Max / macOS 26.5: fresh metallib stamps min-OS 26.0
(air-vtool, container + every non-NAX module; NAX modules 26.2),
carries the 26.2-ABI intrinsics only, and the canary-gated chunked
tests + qwen3.5-0.8b greedy parity reproduce the MLX-bump magnitudes
exactly (0 / 0.0063 / 0.0283, argmax matches, 4/4 prompts). A true
26.0-host load test is not possible from this machine; the container
min-OS stamp is the same load-gate mechanism as the previously shipped
26.0-floor artifacts.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01BcztCkraQ7SsHu3kPGh8G3
…thoritative), honor CARGO_TARGET_DIR, gate deployment floor

Codex raised two HIGHs against the metallib packaging heuristics; both
confirmed and fixed together:

1. build.ts derived the fallback target root from --target-dir /
   CARGO_BUILD_TARGET_DIR / repo default and ignored cargo's standard
   CARGO_TARGET_DIR (which the napi CLI honors transitively via
   `cargo metadata`), so `CARGO_TARGET_DIR=... yarn build:native` scanned
   the wrong tree. resolveTargetRoot() now mirrors cargo precedence:
   flag > CARGO_TARGET_DIR > CARGO_BUILD_TARGET_DIR > default.

2. Newest-mtime ranking across mlx-sys-* hash dirs could ship a same-pin,
   marker-passing metallib from a build the addon never linked (e.g. a
   different-feature cargo invocation under a different
   MACOSX_DEPLOYMENT_TARGET leaves a NEWER dir with a higher min-OS stamp;
   a fresh napi rebuild reuses the older dir without touching its mtimes).
   Selection is now authoritative: MLX bakes METAL_PATH (the exact
   mlx-sys OUT_DIR kernels path) into the addon binary;
   extractBakedMetallibBinding() reads it out of the just-built .node and
   selectMetallib() ships exactly that build's out/lib metallibs. A
   missing bound metallib fails loudly instead of falling back; the mtime
   scan survives only for addons that bake no METAL_PATH.

Also adds a deployment-floor gate: parseMetallibMinOs() reads the MTLB
container min-OS stamp (u16 LE major/minor at offsets 12/14, validated
against -mmacosx-version-min=15.0/26.0/26.2 scratch builds) and
assertMetallibFloor() rejects mlx.metallib/paged_attn.metallib stamped
above the intended floor (MACOSX_DEPLOYMENT_TARGET else host version),
with graceful skip on unknown container layouts. The size + kernel-marker
integrity gate stays as the content backstop.

Tests: metallib-select suite 12 -> 26 (CARGO_TARGET_DIR precedence,
baked-path extraction with decoys, same-pin-newer-but-unbound candidate
rejected under the binding, floor parse/gate incl. real artifact header).

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01BcztCkraQ7SsHu3kPGh8G3
…gate only on a recognized MTLB layout

Follow-up to c612336 addressing Codex round-3 findings (1 HIGH, 1 MEDIUM,
both confirmed):

HIGH: selectMetallib extracted the addon's baked METAL_PATH (the cmake
kernels build-tree file the addon references at runtime) but then shipped
its out/lib cmake-install COPY — a derived file that a partial cache
restore or manual prune can leave stale or missing. Now the invariant is
"shipped bytes = the file the addon references": when both files exist
they must be byte-identical (size + Buffer.equals) or the build fails
loudly, and the baked file itself is shipped; when out/lib is missing the
baked file ships with a warning instead of failing; when only the install
copy survives (pruned build tree) it ships from the same bound dir with a
warning; when neither exists the build still throws rather than falling
back to another dir. paged_attn.metallib is now resolved from its
OUT_DIR-root origin first (what build.rs writes) with the out/lib copy as
fallback, so the out/lib-missing case works end to end.
MetallibBinding.metallibPath is renamed installCopyPath and bakedPath is
path-normalized (collapses the kernels// double slash).

MEDIUM: parseMetallibMinOs accepted any MTLB with a plausible u16 at
offset 12 and assertMetallibFloor then hard-failed on it — future
container-header drift could reject good builds. The parser now requires
the fully recognized layout (platform tag 0x8001 @4, container version 2
@6, library type 0x00 @10, macOS tag 0x81 @11 — each validated against
the -mmacosx-version-min=15.0/26.0/26.2 fixtures and shipped artifacts)
before returning a stamp; anything else makes assertMetallibFloor warn
and skip instead of enforcing.

Tests: metallib-select suite 26 -> 30 (divergent install copy rejected,
missing install copy ships the baked file, identical pair ships the baked
file, future-layout fixtures skip with a warning and never hard-fail).

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01BcztCkraQ7SsHu3kPGh8G3
…tegrity gates as mlx.metallib

Follow-up to a17a040 addressing the Codex round-4 HIGH: the paged_attn
resolution was asymmetric — it shipped the first readable candidate
(OUT_DIR origin preferred), never byte-compared the origin against its
out/lib install copy when both existed, and had no integrity gate, so a
stale or truncated origin could ship while out/lib held the good copy
(the min-OS floor gate cannot catch that: unrecognized headers downgrade
to warn+skip by design and heavy truncation never reaches the stamp).

selectPagedMetallib (metallib-select.ts) now mirrors the mlx.metallib
contract exactly: both copies present must be byte-identical
(Buffer.equals, which covers size) or the build fails loudly naming both
files; a match ships the build.rs origin; a single surviving copy ships
with a warning; neither existing keeps the loud mlx_paged_dispatch
not-found error. assertPagedMetallibIntegrity runs before any copy:
MTLB container magic plus a 4 MiB size floor — every healthy
paged_attn.metallib measured on this machine (8 samples across worktree
and main checkout, debug and release profiles, old and new MLX pins) is
exactly 19,490,342 bytes (~19.5 MB), so 4 MiB catches truncation with
generous headroom, including the identically-truncated-pair case that
byte-equality alone would pass. build.ts drops the ad-hoc first-readable
loop and runs select -> integrity -> floor -> copy.

Tests: metallib-select suite 30 -> 36 (both-present mismatch rejected,
truncated origin next to a good install copy rejected loudly, single
survivor ships with a warning from either location, not-found throw,
size-floor and magic gates).

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01BcztCkraQ7SsHu3kPGh8G3
…nreadable-artifact errors

Follow-up to a0be04e addressing the final Codex MEDIUM: readIfExists
(paged selection) and statSize (mlx baked/install probes) swallowed EVERY
fs failure as "absent", so EACCES/EPERM/EISDIR/transient errors on a
present artifact degraded selection to the single-survivor branch and
shipped the other copy without the byte-identity comparison. For the mlx
path the realistic trigger is an untraversable parent directory: stat on
a mode-000 file still succeeds, but a mode-000 kernels dir turns the
baked-path stat into EACCES, which previously read as absence.

A shared isAbsenceError now recognizes only ENOENT/ENOTDIR as absence;
statSize and readIfExists re-throw anything else as
"[build.ts metallib gate] cannot stat/read <path>: <cause>". The mlx
both-exist byte-compare already used raw readFileSync (errors propagate
with the path in the message) and needed no change.

Tests: 36 -> 38, both chmod-based and skipIf(root)-guarded with perms
restored in finally: an unreadable present paged origin next to a good
install copy THROWS "cannot read" with zero warnings emitted, and an
untraversable kernels dir with a good install copy makes selectMetallib
THROW "cannot stat" instead of shipping the copy uncompared.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01BcztCkraQ7SsHu3kPGh8G3
…tallib scan

Follow-up to 91fb383 addressing the last Codex MEDIUM: the same
error-class hole survived in collectMetallibCandidates — it caught every
readdirSync/statSync failure and continued, so on the no-baked-path
fallback path an unreadable current candidate (or unlistable build root)
was skipped as if absent and an older readable candidate won the mtime
ranking; an unreadable invoked.timestamp/output probe could silently
corrupt the ranking too.

All stats in the module now route through a shared statIfExists that
returns undefined only on ENOENT/ENOTDIR and otherwise throws
"[build.ts metallib gate] cannot stat <path>: <cause>" (statSize is a
thin wrapper over it); the build-root readdirSync continues only on
absence and otherwise throws "cannot list <buildRoot>". Full-module
sweep: exactly three catch sites remain (statIfExists, readIfExists,
and the build-root readdir), each absence-only-continue plus loud
re-throw with path context; the two bare readFileSync calls in the
byte-compare run after both files statted present and propagate
naturally. No catch-and-continue around fs remains in the module.

Tests: 38 -> 40, chmod-based and skipIf(root)-guarded with perms
restored in finally: an untraversable newest candidate makes the scan
THROW "cannot stat" instead of picking the older readable dir, and an
unlistable build root THROWS "cannot list".

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01BcztCkraQ7SsHu3kPGh8G3
…l rejects mixed-dtype K/V)

A sym8-converted qwen3_5_moe checkpoint on the default block-paged KV
path aborts its first generation with "update_keys_values: keys/values
dtype mismatch (Float32 vs BFloat16)". sym8 convert stores norm weights
as f32 (the affine twin stores bf16); fast::rms_norm promotes k_norm's
output to result_type(x, weight), so K leaves k_norm as f32 while V
(no norm) stays bf16. The paged pool hard-rejects mixed K/V dtypes.

Mirror the dense qwen3_5 sym8 pin: force use_block_paged_cache=false
when sym8 is active (has_sym8_mode), before Qwen35MoeInner::new builds
the paged adapter. The flat KVCache has no dtype-parity gate.

Co-Authored-By: Claude Fable 5 <[email protected]>
Codex round 7 raised two MEDIUM findings: the metallib packaging gates
warn-and-continue in edge paths that a publish/release build should fail
closed. Both verified against real code + the actual publish flow.

Finding 1 (no baked METAL_PATH -> stale directory scan): confirmed mechanism
(MLX_DISABLE_METAL on darwin builds a Metal-less addon that bakes no
METAL_PATH, and build.ts still runs packaging), but unreachable in the publish
pipeline (ci.yml never sets MLX_DISABLE_METAL; the build job always builds
Metal). Fail-closed-for-publish is correct defense-in-depth.

Finding 2 (unparseable MTLB min-OS stamp -> floor check skipped): confirmed
and publish-reachable; a future container-layout change would silently ship a
package that fails on the 26.0 floor.

Fix: add an explicit MLX_METALLIB_STRICT publish-mode signal (set at the ci.yml
workflow env level, mirroring MACOSX_DEPLOYMENT_TARGET). In strict mode
selectMetallib throws instead of scanning stale dirs when the addon bakes no
METAL_PATH, and assertMetallibFloor throws instead of warn-skip when the min-OS
stamp is unparseable. Local yarn build:native leaves it unset and keeps the
lenient warn-and-continue behavior verbatim.

Tests 40 -> 45: strict no-baked-path throws (zero warnings), strict
unparseable-floor throws (zero warnings), non-strict still scans/warns for
both, strict still enforces a recognized above-floor stamp.

Co-Authored-By: Claude Fable 5 <[email protected]>
@cursor

cursor Bot commented Jul 3, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_f6ed0276-750f-4e96-b614-03ef9ccc7efb)

@coderabbitai

coderabbitai Bot commented Jul 3, 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: ab73c5fd-a1dc-4d79-98cf-1d8f2cc0dd74

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 perf/inference-polish-quality-sweep

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.

@Brooooooklyn Brooooooklyn added the model-e2e Run the heavy Model E2E workflow (per-family real-checkpoint tests) on this PR label Jul 3, 2026
@Brooooooklyn
Brooooooklyn merged commit 4c65f80 into main Jul 4, 2026
15 checks passed
@Brooooooklyn
Brooooooklyn deleted the perf/inference-polish-quality-sweep branch July 4, 2026 01:45
Brooooooklyn added a commit that referenced this pull request Jul 4, 2026
… heal coverage (#84)

## What & why

`cancel_midcycle_then_continue_mtp_matches_ar` was the **only** failure
on main
CI for #83 ([run
28691184880](https://github.com/mlx-node/mlx-node/actions/runs/28691184880),
`e2e qwen3_5-dense`). The
byte-identical PR-head tree (`e2190e36`, tree `6761d493`) **passed** the
same job
on #83's own CI — a flaky oracle, not a product regression. The
RoPE/perf changes
in #83 only shifted the flake odds.

Two root causes, both found by **running** the code rather than
reasoning:

1. **Racy committed count.** The async `handle.cancel()` commits a
host-timing-dependent number of turn-1 tokens (the streaming emit loop
pushes
   each token to `cached_token_history` *before* its cancel check, and a
`"cancelled"` stop — unlike `"length"` — does not force the
trailing-token
drop in `engine/cache.rs`). The old oracle guessed `n_mtp`. Worse, the
committed count isn't observable from the stream:
`ChatStreamChunk.prompt_tokens`
on the streaming delta path is **hardcoded to the delta length** for
both the
warm and the desync-heal arms, and `cached_tokens` is the full prior
history
   either way — neither distinguishes them.

2. **AR is the wrong oracle.** MTP-speculative and plain-AR pick
different tokens
on T=0 argmax near-ties, so an AR reference diverges from the MTP run
regardless
of the heal (a sweep showed byte mismatches at longer budgets even with
matched
   committed length).

## The fix

**Flakiness** — read the real state instead of guessing:
- New read-only `#[doc(hidden)]` hook `mtp_flat_state_for_test() ->
(committed_len,
  flat_mtp_caches_desynced, full_reprefill_count)` (not `#[napi]`).
- `cancel_midcycle_then_continue_mtp_matches_uncancelled` (renamed):
reads the
actual committed history and length-matches an **un-cancelled MTP**
reference's
budget (`b* = n_mtp + (h1_mtp − h1_ref0)`) so both runs commit the
identical
greedy prefix, then asserts the follow-ups are byte-identical. Same
generation
  path on both sides ⇒ equal committed length is an identical prefix.

**Non-vacuous heal coverage** — the cancel test is still vacuous on a
fast host
(the cancel always lands on a clean boundary → turn 2 warm-continues),
so add
`desync_heal_reprefills_to_uncancelled`:
- The flat streaming MTP continue heal is deterministically reachable —
on a flat
(non-paged) model the rebuild gate in
`chat_stream_tokens_delta_sync_inner`
reduces to `flat_mtp_caches_desynced` alone. New
`force_flat_mtp_desync_for_test()`
arms it. The heal re-prefills from `cached_token_history` and discards
the caches,
  so arming the flag on a clean session faithfully exercises it.
- New monotonic `flat_full_reprefill_count` (incremented only in the
streaming-delta
rebuild branch) is the **only** observable proof the rebuild ran. The
test forces
the desync, asserts the counter incremented (heal actually took the
re-prefill
path), and asserts the healed reply equals a byte-identical un-cancelled
MTP
  reference over the same committed history.

## Testing

Verified on M5 (Qwen3.5-0.8B, fresh `mlx convert -m qwen3_5`):

- `cancel_midcycle_then_continue_mtp_matches_uncancelled` — **5/5**
stable
- `desync_heal_reprefills_to_uncancelled` — **5/5** stable
(`healed=true` each run)
- full `qwen3_5_delta_chat` file — **9/9**
- `mlx-core` lib — **1930 passed; 0 failed** (46 ignored)
- `clippy -D warnings` + `cargo fmt --check` clean
- No NAPI surface change (accessors aren't `#[napi]`), so no
`index.d.cts` regen

Two Codex adversarial-review rounds: round 1 `needs-attention` (test
could pass
without exercising the heal) → round 2 **approve** after the
deterministic heal
test + counter.

`model-e2e` label added so the `e2e qwen3_5-dense` job runs the fixed
test on this PR.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Changes are `#[doc(hidden)]` test hooks and e2e test logic only; no
public NAPI surface and no alteration of heal behavior beyond counting
reprefills for observability.
> 
> **Overview**
> Adds **test-only** introspection for flat MTP cache healing: a
monotonic `flat_full_reprefill_count` (incremented when the streaming
delta path discards caches and re-prefills), plus `#[doc(hidden)]`
model-thread commands and async helpers `mtp_flat_state_for_test()` and
`force_flat_mtp_desync_for_test()` to read committed history length,
desync flag, and heal count, or to arm the heal deterministically.
> 
> **`cancel_midcycle_then_continue_mtp_matches_uncancelled`** replaces
the AR oracle with an **un-cancelled MTP** reference whose turn-1 budget
is adjusted from the real `cached_token_history` length (fixing flaky
guesses about cancel vs length stop).
**`desync_heal_reprefills_to_uncancelled`** is new: forces desync,
asserts the reprefill counter increased, and checks turn-2 text matches
a warm MTP run over the same history.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f4c4b21. 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 Opus 4.8 (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