Skip to content

perf(qwen3.5, kquant): Splash-parity work — tiled K-quant layout, all ggml types, int8 KV, fused verify kernels - #183

Merged
Brooooooklyn merged 52 commits into
mainfrom
perf/splash-parity-kquant-tiled-int8kv
Oct 9, 2026
Merged

Brooooooklyn merged 52 commits into
mainfrom
perf/splash-parity-kquant-tiled-int8kv

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Closes most of the decode gap to Splash on Qwen3.8-27B + DFlash2 (same GGUF, same draft), and brings GGUF type coverage to parity. 43 commits (rebased on main), each gated end-to-end; every exact change keeps the benchmark output hash, every non-exact one passes a teacher-forced acceptance gate on the same text.

Performance (Qwen3.8-27B UD-Q4_K_M, DFlash2, 1024 tokens, M5 Max, clock-matched pairs)

short 6k 32k
ms/cycle vs Splash, before 1.20× 1.27× 1.49×
ms/cycle vs Splash, after round 1 ~1.14× ~1.09× ~1.10×
ms/cycle vs Splash, after round 2 1.08× ~1.03× 1.08×
dispatches / cycle 1650 → ~845
process footprint @32k 21.5 GB → 20.5 GB (Splash 20.2)
  • Weight layout: 64-row tiled K-quant layout (@t64). Measured against Splash's own kernel on identical shapes, the row-major layout was the entire M=8 matmul gap (1.4–1.8×); tiled lands at 1.02× of their kernel. Written on disk by convert (layout: "t64"), legacy row-major still permutes at load; all families tiled (dense qwen3_5, qwen3_5_moe dense parts, Muse, LFM2/K2, Gemma4).
  • Verify attention: simdgroup-matrix tile kernel, then Metal 4 matmul2d kernel (32K: 1.05 → 0.355 ms/layer); block/vector crossover calibrated per device at first use (no device constants).
  • M=8 matmul: tensor-op kernel ported from Splash's staged tile (attributed); routed for tiled weights and row-major Q3_K/IQ4_NL.
  • KV cache: int8 per-row (Splash's format) default on Metal @ head 256, kvFormat: 'bf16' opt-out. Teacher-forced NLL/KL/top-1 unchanged within noise.
  • Dispatch count: packed ping-pong GDN state blobs + one-kernel all-layer commit, one-dispatch KV row store, fused q/k RMSNorm+RoPE (bit-identical to MLX's ops), buffer-cache bound during decode (grows with context; malloc never refuses on it).

Round 2 (Splash alignment + what the timeline said)

  • GDN recurrent state in FP32 (Splash keeps it f32; y/conv stay bf16). The T=1 AR chain now equals the T=8 verify window bit-for-bit, so a full accept adopts the verify state instead of replaying (Splash's gdn_commit_phase early return). Teacher-forced on the same text the precision change is neutral (each build loses the same ~1.5% of cycles on the other's transcript).
  • One Metal primitive per GDN verify layer (prologue + recurrence + gated RMSNorm + z-gate, Splash's verify_gdn_fused shape), 0 ulps vs the chain; 48-layer kernel time 1.56 → 0.97 ms.
  • Commit/draft glue batched: 16 KV row stores → 1 (address table), draft K/V as a flat window with in-place stores, draft projections row-merged, fused q/k norm + RoPE in the draft. Exact.
  • Affine Q4/g64 on the tiled K-quant kernels (a4g64@t64 …): the DFlash2 draft's matmuls ran through MLX's per-row qmv at 188 GB/s for M=8; now 445 GB/s. Propose 6.2 → 4.8 ms/cycle, draft matches per cycle unchanged (2.32 vs 2.32 on the same text). A Q4_K re-quantization was tried first and rejected (−2% draft matches on 9 prompts).
  • Tooling: teacher-forced acceptance harness (MLX_DFLASH2_TF_RECORD/TF_DIR, tf-acceptance.ts) and a per-cycle timeline ([dspark-span] + timeline.ts, Perfetto export) joining host phases with the Metal command trace. The timeline showed GPU busy 99% of the cycle, which is why device-side accept was not built (ceiling ~1%).
  • Q8_K stays refused by name, as Splash does.

Round 3 (small items, measured one by one)

  • MoE prefill: the sorted K-quant expert matmul (B / E >= 4) ran 16×32 tiles that straddled experts and re-ran the K loop per expert, at 112–220 GB/s. New tensor-op gather_qmm_rhs_nax with one expert per 32/64-row tile: 240–410 GB/s (1.8–2.4×) on LFM2.5-8B-A1B / Qwen3.6-35B-A3B shapes; decode and the 8-row verify keep gather_qmv (measured at 88–90% of the bandwidth floor — a tiled expert path was 2.2× slower and was not built).
  • Loader fix: the transposed K-quant weight loader's row guard compared against the K extent, so unaligned-N tiles read weight rows past N (outputs were masked; the reads were not in bounds). Same fix as upstream MLX.
  • Measured and removed (recorded in the research doc): add_rmsnorm fused into the M=8 matmul (bit-exact but the norm prologue costs 3–30% of the matmul vs 2–4 µs for the separate kernel); merging the 48 ba projections (launch-bound, ~0.15 ms); affine modes without a producer (a4g32/a8g64/a8g32) trimmed to a4g64.
  • Teacher-forced and timeline tooling: tf-acceptance.ts, timeline.ts (+ [dspark-span]), benchmark.ts <case>:<k> prompt cuts, kquant_moe_bench.

Round 4 — MLX-affine linears on the tiled kernels (Splash alignment)

Splash repacks every weight into one tiled layout at start and runs its own kernels for every M. Now so do we for MLX-affine (bf16-companion) linears on Metal: every family's affine arm tiles the weight to a4g64@t64 / a8g64@t64 at load (same bytes; row-major sources released), so MTP verify rows, DFlash blocks and batched decode take new 8/16/32-row tensor-op tiers instead of MLX's per-row qmv; qmv_t64 got 8/16-row sub-tiles for small N at M=1. MLX's row-major route stays where tiling is impossible or not a win (f16 companions, other bits/group, odd shapes, calibration/hadamard sites, tied heads, experts, non-Metal, and N < 6144 / K < 1536 where the tiled kernels only tie or trail — a measured rule with a test).

  • Qwen3.5-4B affine 4/64: AR decode +0..6%, prefill +15–25%, peak memory 5.6 → 4.5 GB, batched M=10/16/24 on the tiers; mlx eval against the row-major route: identical nll/KL/top-1 at M=1 and M=512, KL ≤ 0.001 at M=12/32.
  • Gemma-4-E2B 4-bit: gate|up tile, the rest stays row-major; ABBA 0.997× ms/token.
  • K-quant routes are untouched (Qwen3.8 GGUF AR hash unchanged); the DFlash2 draft follows the affine rules — teacher-forced acceptance unchanged (957 vs 952 cycles on the same text).
  • Gemma4 greedy decode is now reproducible. Found while gating: the paged-attention partition (grouped_stripes) was picked by a timing sweep on production tokens at context > 512, and every partition rounds its bf16 partials differently, so transcripts flipped run to run (and mixed partitions within the first 20 tokens past 512). Replaced by a device rule — next_pow2(16 · gpu_cores / q_heads), bounded by the work tiles and [4, 256]; measured monotone-to-saturation, so the sweep had nothing to find. One hash over 8/9/9 fresh runs at short/4K/8K (before: 2–5 transcripts); decode 156→158, 141→145, 130→144 tok/s. The raw (non-graph) route carries the same count; the static tables and MLX_GEMMA4_DECODE_TUNING are gone.

Round 5 — one transcript per prompt, whichever route serves it

  • Muse-Glimmer had the same timing-sweep partition picker (up to 7 transcripts for one 4K prompt). Now on the shared device rule; the submission-depth sweep stays (it cannot change bits). MLX_MUSE_GROUPED_STRIPES is capped by the live limit, and K2-Horizon takes the same rule — the old context stripe table and mlx_paged_grouped_d128_default_stripes are deleted.
  • Gemma4 raw vs graph read different sliding-window spans (trimmed block table vs full table + mask → different reduction boundaries). One decode_read_span helper now feeds the graph route, the raw route and the batched builder; raw = graph bit for bit, grouped on or off (4K: 3b8ca77f44 / f5c51b41dc).
  • Whole-turn vs scheduled lane differed on both models: scheduled rows had no attention plan (generic V2) and prefill sliced on different boundaries. One-row waves now run the whole-turn step under the same decode_tuning plan, and one shared prefill_slice_ends grid (512-token steps + cold-anchor rungs) feeds admission, SSD restore, preemption resume and the whole-turn chunker — which also fixes whole-turn Muse prompts above ~2.5K failing with context_length_exceeded. Gemma-4-e2b: whole-turn = scheduled at 54-tok/1K/4K, grouped on/off, cold tier on/off; Muse whole-turn = scheduled at 147-tok/1K/2.2K/4K. Multi-row waves stay on generic V2 (the grouped kernels serve one sequence per dispatch) — documented in docs/concurrent-inference.md.
  • Fresh-process hash suites: Muse 1K/4K/8K one hash over 12/12/10 runs (was 4/7/5); route parity tests pin raw-vs-graph and lane-vs-lane equality at windows 0/513/2048 and on Metal. Found while gating: the paged-attention partition (grouped_stripes) was picked by a timing sweep on production tokens at context > 512, and every partition rounds its bf16 partials differently, so transcripts flipped run to run (and mixed partitions within the first 20 tokens past 512). Replaced by a device rule — next_pow2(16 · gpu_cores / q_heads), bounded by the work tiles and [4, 256]; measured monotone-to-saturation, so the sweep had nothing to find. One hash over 8/9/9 fresh runs at short/4K/8K (before: 2–5 transcripts); decode 156→158, 141→145, 130→144 tok/s. The raw (non-graph) route carries the same count; the static tables and MLX_GEMMA4_DECODE_TUNING are gone.

GGUF types — now every type Splash loads (plus Q5_1/Q5_0/dense F16/BF16): Q2_K, Q3_K..Q6_K, IQ1_S, IQ1_M, IQ2_XXS/XS/S, IQ3_XXS, IQ3_S (packed; previously 8-bit expanded), IQ4_NL/XS, MXFP4 (→ MLX native), Q4_0/Q4_1/Q5_0/Q5_1/Q8_0, PQ2_0. Grid formats are packed at ggml's bits per weight with in-kernel grid lookup, bit-identical to vendored llama.cpp decoders. Q8_K remains unsupported (as in Splash).

Discovery: Unsloth UD-Q*_K_M, UD-Q2_K_XL, UD-IQ* names are admitted for Qwen3.5/3.8.

All A/B env switches were removed once measured (losing variants deleted); the one-time route/calibration logs print under MLX_METAL_COMMAND_TRACE.

Ported code from Splash (Apache-2.0) is attributed in THIRD_PARTY_NOTICES.

Test plan

  • cargo test -p mlx-core --release kquant suites (ggml parity bit-exact for all 15 modes, tiled routes, mode guards, metallib names), segmented SDPA suites incl. golden gates, qwen3_5/gdn_blob/kv_cache/cache_limit unit tests
  • yarn build:native, yarn typecheck, discovery/agent/loader vitests
  • End-to-end: Qwen3.8 UD-Q4_K_M benchmark hash stable across every exact step; Qwen3.6-35B UD-Q2_K_XL / IQ2_XXS / IQ2_M / IQ1_M / IQ3_XXS / MXFP4_MOE load at file size and answer correctly
  • Two adversarial review passes; one blocker (biases tiled in the wrong unit) fixed with a 14-mode round-trip test
  • Round 4: kquant_affine_tiled (a4g64 + a8g64, M 1..87, determinism 224 routes × 24 evals), kquant_tiled (every K-quant mode at M 12/24/32/40 stays off the new tiers), kquant_metallib_names, kquant_mode_guards, kquant_ggml_parity, kquant_m8_nax, loader tests per family (tile / decline cases), 539 lib tests; mlx eval same-checkpoint A/B; smokes on 5 checkpoints; two review passes (no blockers, should-fixes applied)
  • Round 3: kquant_mode_guards (new gather route vs CPU reference, all 15 modes), kquant_metallib_names exact counts, kquant_tiled, kquant_ggml_parity, kquant_affine_tiled, --lib dflash2/quantized_linear/quant_dispatch/qwen3_5_moe; smoke hash unchanged (bf80b142…, 321 cycles); review pass on the gather kernel (no blockers)
  • Round 2: teacher-forced gates for the f32 GDN state and the affine-tiled draft (3 fixtures × 1024 tokens, plus 6 extra prompt cuts), paired ABBA per step, four more review passes (no blockers; should-fixes applied), final head-to-head vs Splash 1.2.1 recorded in docs/research/splash-qwen38.md §2c
  • cargo test -p mlx-core --lib full sweep on the final branch: 3928 passed, 0 failed, 135 ignored (the earlier history_checkpoint_publish_asserts_the_paged_frontier caveat did not reproduce)

Generated with Devin

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@coderabbitai

coderabbitai Bot commented Oct 7, 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: Advanced
  • Run ID: b9b039c9-e381-4a1d-9d47-1d2172734079

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
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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 Oct 7, 2026
Brooooooklyn added a commit that referenced this pull request Oct 7, 2026
Adds the per-commit table, the gate history against Splash 1.2.1, the
final full-clock pair and the GPU-downclock finding (we are still more
ALU/issue-bound), and notes that acceptance differs by transcript.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Brooooooklyn added a commit that referenced this pull request Oct 7, 2026
Adds the per-commit table, the gate history against Splash 1.2.1, the
final full-clock pair and the GPU-downclock finding (we are still more
ALU/issue-bound), and notes that acceptance differs by transcript.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@Brooooooklyn
Brooooooklyn force-pushed the perf/splash-parity-kquant-tiled-int8kv branch from 5a697fb to 98a14df Compare October 7, 2026 17:03
Brooooooklyn added a commit that referenced this pull request Oct 8, 2026
Adds the per-commit table, the gate history against Splash 1.2.1, the
final full-clock pair and the GPU-downclock finding (we are still more
ALU/issue-bound), and notes that acceptance differs by transcript.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@Brooooooklyn
Brooooooklyn force-pushed the perf/splash-parity-kquant-tiled-int8kv branch from 98a14df to 6009824 Compare October 8, 2026 02:36
Brooooooklyn and others added 22 commits October 8, 2026 20:21
The dense Qwen3.5/Qwen3.8 discovery filter only admitted `Q<n>_K_XL`
names. The `_M` mixes use the same ggml tensor types (Q3_K..Q6_K, IQ3_S,
IQ4_NL, IQ4_XS, Q8_0, F32) and the native GGUF loader never checked the
filename, so `Qwen3.8-27B-UD-Q4_K_M.gguf` loads and generates unchanged.
Widen the regex to `Q<n>_K_(XL|M)`; other variants stay excluded.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
The segmented verify first pass was a vector kernel: 24 simdgroups each
re-loaded the same K/V row from device memory and applied it to two
(head, row) pairs with scalar FMAs, so its cost over a long prefix was
far above the BF16 read roofline. The new
`segmented_sdpa_verify_tile_2pass_1` treats the rows x GQA queries of one
KV head as one M-row block, loads each K/V tile once into threadgroup
memory and runs Q.K^T and P.V as 8x8x8 BF16 simdgroup MMAs with fp32
online softmax. Stage 2 (MLX `sdpa_vector_2pass_2`) and its partial
layout are unchanged.

Tile size, simdgroup count and partitions derive from the pipeline and
MTLDevice limits at plan time; `MLX_SDPA_BLOCKS` still overrides.
`MLX_SDPA_VERIFY_TILE=0` restores the vector routes, `=N` sets the key
count from which the tile route is taken (default 1024, the measured
crossover). The vector routes stay the strict bit-exact path for the
golden gates; the tile route is held to <= 1 BF16 ulp of the output
magnitude against them.

Kernel at 32768 keys: 1.05 -> 0.61 ms; Qwen3.8-27B + DFlash2 at a 32K
prompt: 81 -> 71 ms per cycle, 35 -> 39.6 decode tok/s, acceptance
unchanged.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Port Splash's staged decode tile (Apache-2.0, see THIRD_PARTY_NOTICES):
each lane dequantizes one column's group of 32 codes to half in a
double-buffered threadgroup stage and the simdgroup runs matmul2d
(8x32x32, fp32 accumulate) on it; K splits publish fp32 partials that the
last-arriving partition adds in split order, so outputs are
scheduling-independent. Split count derives from the IORegistry GPU core
count and K (6 threadgroups per core, >= 512 inputs per partition).

Measured on the Qwen3.8-27B verify shapes it ties or trails `qmv_sg8`
(0.78-1.03x) for Q4_K/Q5_K/Q6_K/IQ4_XS -- dequant ALU and the tensor op do
not overlap at M=8 -- but beats `qmv_wide` 1.25-1.4x for Q3_K and IQ4_NL,
which had no simdgroup-matrix route. The default routes only those two
modes; `MLX_KQUANT_M8_NAX=1` forces all seven, `=0` disables.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
On gen-17+ GPUs the 8x8x8 BF16 simdgroup_matrix MMA runs at FMA rate, so
the tile verify kernel's floor at 32768 keys was its own math (0.47 ms of
0.61). `segmented_sdpa_verify_nax_2pass_1` runs Q.K^T and P.V as Metal 4
`matmul2d` tensor ops over K/V tiles read straight from device memory,
with Splash's page softmax shape (attribution in THIRD_PARTY_NOTICES) and
the two-pass partial layout unchanged, so stage 2 stays MLX's reducer.
M = rows x GQA and the key tile are template parameters (the descriptor
is constexpr); partitions, threadgroup bytes and the 256-thread scope are
checked against the pipeline and device at plan time. Partial tiles use
dynamic slices because static MPP slices ignore tensor extents.

Routes: NAX when available and the Q view is head-major, else the
simdgroup tile, else the bit-exact vector kernels; `MLX_SDPA_VERIFY_NAX=0`
disables it. Kernel at 32768 keys 0.61 -> 0.355 ms; <= 1 BF16 ulp of the
vector route over 327 blocks; 20 runs byte-identical.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Row-major K-quant weights put a 64-column threadgroup's rows K/2 bytes
apart, so every K step of an M=8 matmul touched 10-35 pages per
threadgroup; measured against Splash's kernel on identical shapes the
layout alone accounted for a 1.4-1.8x gap. At load, 2-D K-quant linears
with N % 64 == 0 and K % 256 == 0 are permuted (plain MLX reshape and
transpose) into `[N/64][K/32][64][unit]` codes with per-super-block
companions, tagged by the `@t64` mode suffix that the K-quant primitive
carries through compile. The on-disk format is unchanged.

Ported to the tiled layout, bit-identical to their row-major forms where
the arithmetic order is shared: `qmm_m8_nax`, `qmv_wide`, `qmm_t_nax`,
`qmm_t`, `qmm_t_splitk`, the CPU reference, and a new lane-per-row M=1
`qmv_t64`. Unported routes refuse tiled operands. `MLX_KQUANT_TILED=0`
keeps everything row-major; `MLX_KQUANT_ROUTE_LOG=1` prints the routes
taken.

Qwen3.8-27B UD-Q4_K_M + DFlash2 on an M5 Max, normalized ms per cycle:
short 57.9 -> 54.0, 6K 62.7 -> 54.6, 32K 69.9 -> 60.8 (together with the
tensor-op verify attention); AR decode at parity, prefill +8%.

Known: load-time peak memory is ~2x the resident size because the
row-major arrays stay alive until the loader finishes, and GDN
`in_proj_ba` (N=96) no longer merges with `in_proj_qkvz`.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…t rows into merged tiles

Loading a tiled model kept every row-major K-quant array in the params
map until the loader returned, so the tiled copies doubled the peak
(33.2 GB for a 17.0 GB Qwen3.8-27B). The loader now takes the map by
`&mut`, evaluates each projection's tiled arrays and drops their sources
per layer; peak is 17.04 GB for the same load, output unchanged.

A K-quant projection whose row count is not a multiple of 64 can now be
zero-padded to the next tile and merged with a tiled sibling of the same
mode (the GDN `in_proj_ba` case); the consumer drops the pad columns and
the result is bit-identical to the unmerged path. The Unsloth Qwen3.8
GGUFs store `in_proj_a/b` as Q8_0 (affine), so they never merged with the
q5k `in_proj_qkvz` and are unaffected.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
The verify block kernels (tile / tensor-op) took over from the vector
route at a fixed 1024 keys measured on one M5 Max. Each process now times
the production dispatch of both routes once, on first use, at 256..4096
keys with GPU timestamps (interleaved, min of 7; ~35 ms here) and takes
the smallest count from which the block route stays at least 5% ahead,
so a tie keeps the bit-exact vector route and the choice does not flip on
noise. `MLX_SDPA_VERIFY_TILE` still overrides; `MLX_SDPA_ROUTE_LOG=1`
prints the calibration. On this device the crossover is 512 keys.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…ention env knobs

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…mpared

The measurements behind the tiled K-quant layout, the tensor-op M=8
matmul and the verify-attention block kernels are concluded, so their
env switches go: MLX_KQUANT_TILED, MLX_KQUANT_TILED_QMV,
MLX_KQUANT_M8_NAX, MLX_KQUANT_M8_SPLITS, MLX_SDPA_VERIFY_TILE,
MLX_SDPA_VERIFY_NAX, and the two route-log vars (their one-time lines now
print under MLX_METAL_COMMAND_TRACE). With them go the losing M=1 lane
maps (`qmv_wide_t64` nv_1 at 8/4 K lanes), the row-major tensor-op
instantiations for the four modes that never route to it, the
force-switch bench, and the tests that only exercised a switch. The
vector and simdgroup-tile attention kernels and the row-major K-quant
kernels stay as the fallbacks they are.

Default behaviour is unchanged: same output hash and cycle count on the
Qwen3.8-27B DFlash2 benchmark.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Per-(token, head) symmetric int8 K/V with one fp32 scale per row, after
Splash's format, for the Qwen3.5-family flat cache (the Qwen3.8 + DFlash2
path). Rows are quantized on write; the verify block kernels read int8
operands directly (matmul2d bfloat x int8, key scales on the scores and
value scales on the probabilities), the simdgroup tile and vector
kernels dequantize on load, and a one-row kernel serves AR decode.
Prefill chunks after the first dequantize the prefix into a BF16
temporary (~1% of a 32K TTFT). Paged caches and other families are
unchanged.

Selected per load: `kvFormat: 'int8' | 'bf16'` on `Qwen35Model.load` /
`loadSession` (and `mlx eval score --kv-format`). The default stays
bf16: teacher-forced NLL/KL/top-1 are unchanged within noise with int8
(KL 0.01069 -> 0.01067, top-1 95.08 -> 95.09%), kernel error equals the
int8 rounding noise, but DFlash2 acceptance moved both ways across
prompts (-10% on one), so flipping the default is a product call.

At 32K: KV 2.1 -> 1.07 GB, process footprint 21.5 -> 20.5 GB, cycle
time within noise.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
The decode loop only trimmed the allocator's buffer cache every 256
tokens, so at short prompts ~1.2 GiB of freed buffers stayed resident
(the draft's sliding-window buffers grow each cycle and never match a
smaller freed one). For the length of a DFlash2 turn the cache limit is
now max(2 x the cycle's transient footprint, 128 MiB), where the
transient is derived from the model geometry (logits, GDN tapes, one
layer's scratch, and the two-pass SDPA partials, which grow with the
context) and restored when the turn ends, so prefill and other paths
see the load-time cap.

Only the buffer-cache limit changes: `MetalAllocator::malloc` never
refuses on it (a miss allocates a fresh buffer), so KV growth is
unaffected. Measured in-process ABAB at short/6k/32k: cycle time within
+-1%, TTFT unchanged, resident cache 1.2 GiB -> ~0.2 GiB at short.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…erve

Align the default with Splash: an unset `kvFormat` now means int8 on
Metal with 256-wide heads (the geometry the int8 segmented kernels
cover) and BF16 everywhere else, so no geometry falls onto the
dequantizing fallback by default. `kvFormat: 'bf16'` opts out; an
explicit value always wins.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…folding for the grid types

Q2_K lands as a packed K-quant mode (2-bit codes, (sc, min) pairs per 16,
(d, dmin) per super-block; 3.125 bpw) on every route the other modes
take — CPU reference, qmv/qmv_wide/qmv_t64, qmm_t/_splitk, the prefill
and M=8 tensor-op kernels, row-major and 64-row tiled. Q5_0 maps onto the
symmetric affine 5-bit path like Q4_0/Q8_0 (zero point 16). MXFP4 maps
onto MLX's native mxfp4 mode (E2M1 codes, E8M0 scales), including the
3-D expert tensors of the MXFP4 MoE GGUFs through the existing gather
path. The header reject message now lists the accepted types from one
table.

Kernel identity is now (group size, bits, super ratio, has_min, kind,
scale shift): the QuantKind {linear, codebook, int8, grid} and the
power-of-two scale shift (Splash's quant_formats.h, attributed) are
threaded through the Metal, C++ and Rust mode tables so the grid formats
(IQ1/IQ2/IQ3_XXS) can be added without re-plumbing; per-mode companion
byte counts replace the hardcoded ones in the tiled layout.

Oracles: verbatim llama.cpp dequantize_row_q2_K / q5_0 / mxfp4 added to
the vendored reference; Q2_K and MXFP4 decode bit-identical (MXFP4's e<2
corner included), Q5_0 within the documented f16 affine budget. Local
end-to-end: Qwen3.6-35B-A3B MXFP4_MOE loads and answers; the UD-Q2_K_XL
file still needs IQ2_XS/IQ2_S experts (next stage). Qwen3.8 UD-Q4_K_M
output unchanged (same hash, 241 cycles).

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…dispatch KV row stores

The DFlash2 commit replayed each of the 48 GDN layers with its own
dispatch plus a concat/slice conv rebuild, and each full-attention layer
wrote its new K/V rows with 2-6 slice updates: ~176 dispatches per cycle
for ~26 worth of work. Following Splash's commit structure (attributed in
THIRD_PARTY_NOTICES):

- the DFlash2 stepper packs the GDN conv and recurrent state of all layers
  into two blobs with a current/next pair; per-layer caches become views,
  so the compiled verify tape is unchanged;
- `mlx_gdn_commit_all` replays every layer's kept tokens and recomputes
  the conv carry in one primitive writing into the spare blobs (per-token
  bf16 rounding kept, so results are bit-identical to the per-layer
  replay); Metal's 31-buffer bind limit makes it 10 dispatches today;
- `KVCache::store_block` writes a layer's K, V (and int8 scales) rows in
  one in-place kernel.

Steady cycle on Qwen3.8-27B: 1331 -> 1181 dispatches (bf16 KV),
1395 -> 1213 (int8 KV); output hash, cycle count and acceptance by
position identical; 2-4% faster per cycle in same-session pairs.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
`load_with_thread` parsed the config's (absent) `kv_format` to BF16 and
used that whenever no load option was given, overriding the int8-where-
served default introduced in c27ee03c4. Unset now falls through to
`Qwen3_5Config::kv_format()`; an explicit option or config value still
wins. Verified: active memory at 32K drops to the int8 figure (18.15 GiB).

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…default

- decline the fused commit for keep == 0 instead of erroring, matching
  the per-layer replay's no-op;
- rewind the full-attention offsets before installing the committed blob
  views, so a failed commit leaves slots and `gdn_blobs` consistent;
- pin the MoE family's dense config view to bf16 K/V: its caches are
  built bf16 explicitly, so the view must not advertise int8.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…mports, packed

The six grid formats land at ggml's bits per weight: `.weight` keeps the
native grid-index words, the sign/scale words, qh halfwords and scale
nibbles ride in the per-group companions, and the grids (ggml's tables,
MIT, vendored verbatim) are looked up in-kernel — Splash's QuantGrid
decode (attributed), with one decode source compiled as both Metal and
C++. Every route reads them: CPU reference, qmv/qmv_fast/qvm,
qmv_wide and qmv_t64 (constant-memory tables), the prefill and M=8
tensor-op kernels (table staged in threadgroup memory: 1.8-2.7x faster
than constant reads at M=8), gathers, dequantize, tiled and row-major.

Decode is bit-identical to llama.cpp's dequantize_row_iq* (vendored,
same pinned sha; the 2^shift rescale is exact). Local Qwen3.6-35B-A3B
UD-Q2_K_XL / UD-IQ2_XXS / UD-IQ2_M / UD-IQ1_M load at file size and
answer correctly; discovery admits the Unsloth UD-IQ* names.

Also fixes the Qwen4 JIT kernels for the (kind, scale_shift) template
arity introduced in 73b2f263a, and makes convert's already-quantized
K-quant check derive its mode list from KQuantFormat.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…K-quant linears

`mlx convert --gguf-kquant` and the native-GGUF cache now write eligible
2-D K-quant linears in the 64-row tiled layout and mark each entry
`"layout": "t64"` in `config.json` (the mode string stays bare), so a
converted checkpoint loads with no permute and no transient; legacy
row-major entries are still permuted at load, and both may coexist.
Embeddings, tied lm_head tables, router gates, 3-D experts and odd
widths stay row-major. Readers that need rows un-tile first (MTP draft
head) or refuse the marker (embeddings, re-convert, the Qwen4 row-window
reader). The native cache format is bumped to v6.

The dense parts of qwen3_5_moe, Muse-Glimmer, LFM2/K2 and Gemma4 (its
own QuantizedLinear type) now take the same tiled builder; Gemma4's
DSpark verify (M = 1 + L) lands on the `qmv_wide_t64` / `qmm_m8_nax_t64`
routes. Convert->load round trips are bit-identical to load-time tiling
at M = 1 / 8 / 64.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Three sites permuted `.biases` with the per-group `.scales` unit instead
of `bias_entries_per_super_block`: the on-disk emitter in convert, the
un-tile step the MTP draft head takes, and Gemma4's tiled builder. The
units coincide for q4k/q5k/q2k/iq4nl/iq2xs only; for the other nine
modes a width the wrong unit does not divide failed loudly, and one it
does divide (q6k at K=4096) silently misplaced every super-block's `d`.
A round-trip test now tiles and un-tiles all fourteen modes bit for bit.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
IQ3_S was the one grid format still expanded to int8 codes at import
(8.3 bpw against ggml's 3.44). It now lands like its siblings: three
words per 32-value unit (eight grid-index bytes and the sign bits), the
qh byte and scale nibble as companions, `d` per super-block, decoded
through the vendored ggml iq3s grid on every route — bit-identical to
llama.cpp's dequantize_row_iq3_s. The Qwen3.6-35B UD-IQ3_XXS file (its
experts are IQ3_S) now sits at 13.9 GB resident for a 14.1 GB file,
down from 20 GB.

Artifacts converted with the expanded form keep loading: the same mode
string at bits 8 with int8 scales resolves to the legacy `iq3s8` kernels.
The native-GGUF cache format moves to v7 so existing caches re-import at
native size; the MTP quantization block accepts bits 3 or 8 for iq3s.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…kernel

Each full-attention verify layer ran rms_norm and rope on q and on k as
four MLX ops, which on the strided split views also made two copies
each: eight dispatches per layer. One `fast::metal_kernel` now reads the
strided q/k, normalizes, applies the partial rotary and writes the
head-major block — reproducing `rms_single_row` and `rope_impl`
arithmetic exactly, so the result is bit-identical (tested over rows,
offsets and head pairs; the four-op chain stays only for the contract
misses: M-RoPE, traditional rope, unequal eps, non-Metal).

Steady decode cycle on Qwen3.8-27B: 1197 -> ~1110 dispatches; output
hash and cycle count unchanged.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Adds the per-commit table, the gate history against Splash 1.2.1, the
final full-clock pair and the GPU-downclock finding (we are still more
ALU/issue-bound), and notes that acceptance differs by transcript.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Brooooooklyn and others added 14 commits October 8, 2026 20:27
Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
gather_qmv at the DFlash/MTP verify width runs at 88-90% of the
bandwidth floor and beats a dense M=8 tiled pass over the same rows; a
per-expert tiled dispatch is 2.2x slower. Recorded in the research doc
with the one gap it did find (the sorted gather_qmm_rhs prefill route at
113-132 GB/s).

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…corded as a dead end

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…fill widths

The sorted gather_qmm_rhs route (B / E >= 4: prefill of K-quant MoE
GGUFs) ran 16x32 simdgroup tiles cut at fixed row boundaries, so tiles
straddled experts and re-ran the K loop per expert run, at 113-132 GB/s.
New gather_qmm_rhs_nax (gen-17+, N % 64, K % 64): one expert per 32/64
row tile over gather_mm_offsets, 64x64x64 tensor-op tiles, fetch(k+1)
overlapped with the MMA. The simdgroup kernel stays as the fallback and
gather_qmv still serves decode and the 8-row verify.

  kquant_moe_bench, DRAM-cold      before      after
  LFM2.5 32e, 16 rows/expert       112 GB/s    240-290 GB/s  (2.1-2.4x)
  Qwen3.6 256e, 128 tokens         177-220     350-410       (1.8-2.1x)
  decode / verify rows             unchanged (same kernel)

Parity vs the previous route <= 4.2e-3 relative (one bf16 ulp); vs the
CPU reference within the qmm_t_nax tile tolerances, all 15 modes. Tests
pin the fallback through a test-only FFI instead of an env switch.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
a4g32 / a8g64 / a8g32 had kernels and tests but nothing produces them;
the templates stay parametric so a combination is instantiation lines
away when an MLX-affine checkpoint takes the tiled route.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…w extent

load_safe compared the tile row against the K extent for the transposed
(reduction_dim == 1) loader, so the guard never fired and the last N tile
of an unaligned width read weight rows past N. The store masked them, so
outputs were right; the reads were not in bounds. Same fix as upstream
MLX's quantized loader. Outputs unchanged (kquant suites, smoke hash).

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…the K-quant kernels

Splash repacks every weight into one tiled layout at start and runs its
own kernels for every M. We now do the same for MLX-affine (bf16
companion) linears on Metal: each family's affine arm tiles the weight
to a4g64@t64 / a8g64@t64 at load (same bytes, a permutation; row-major
sources released), so decode blocks, MTP verify rows and batched decode
take the tensor-op tiers instead of MLX's per-row qmv. MLX's row-major
route stays where tiling is impossible or not a win: f16/f32
companions (GGUF affine), other (bits, group), N % 64 / K % 256,
calibration (input_amax, amax keys), hadamard, Q4_0 decode sidecars,
tied heads, 3-D experts, non-Metal, and shapes below N 6144 / K 1536
where the tiled kernels only tie or trail at M=1 (measured, rule in one
place with a test).

Kernels: qmm_m8_nax_t64 gains 16- and 32-row tiers (x rows staged in
threadgroup memory, zero past M) with a grid-fill rule and a split-K
partials cap; qmv_t64 gains 8/16-row sub-tiles so small-N shapes fill
the GPU at M=1; a8g64 is back (routers and lm_head upgrades are 8/64).
K-quant modes keep their shipped routes bit for bit (Qwen3.8 GGUF AR
hash unchanged; the DFlash2 draft, already a4g64@t64, moves with the
affine rules: teacher-forced 957 vs 952 cycles, 2.24 vs 2.22 draft
matches per cycle on the same text).

  a4g64 @t64 vs MLX affine (ring)   M=8 1.9-2.5x on N >= 5120   M=12 2.9-4.2x   M=24/32 1.1-3.1x
  Qwen3.5-4B affine   AR decode +0..6%, prefill +15-25%, peak 5629 -> 4470 MB, batched M=10/16/24 on the tiers
                      mlx eval vs the row-major route: nll/kl/top-1 identical at M=1/512, kl <= 0.001 at M=12/32
  Gemma-4-E2B 4-bit   gate|up tile, attention/down stay row-major; ABBA 0.997 ms/token
  LFM2.5 mxfp4, Nemotron nvfp4   nothing tiles (contract), unchanged

Review follow-ups: tiled affine q/gate blocks still merge; route tests
derive the expected family from the device's qmv batch limit; every
K-quant mode is checked at M 12/24/32/40 to stay off the new tiers.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…tuning finding

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…ot a timing sweep

Gemma4 decode picked `grouped_stripes` for the D512 paged kernel by
timing production tokens at context > 512 (five partitions, three
samples each). Every partition rounds its bf16 partials differently, so
a greedy near-tie could flip run to run — and the first twenty tokens
after crossing 512 were produced under mixed partitions within one run.

The partition is now a rule from the device and the workload:
stripes = next_pow2(16 * gpu_cores / q_heads), bounded by the 16-token
work tiles and [4, 256], never the generic kernel where the grouped one
is admitted (measured on an M5 Max: the grouped kernel is at or above
generic at every context, saturating near 1024 simdgroups, so the sweep
had nothing to find). The raw (non-graph) decode route now carries the
same planned count instead of a static table, and the static tables,
the test-only stripe-count FFI and the MLX_GEMMA4_DECODE_TUNING switch
are gone. The submission-depth sweep stays: it does not touch numerics.

  gemma-4-e2b-it-4bit, fresh processes   short 8/8 one hash   4K 9/9   8K 9/9   (before: 2-5 transcripts per context)
  decode tok/s                            short 156 -> 158   4K 141 -> 145   8K 130 -> 144

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…ter the Gemma4 fix

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
… rule, not a timing sweep

Same defect as Gemma4 (07280b1): Muse-Glimmer picked its D128
`grouped_stripes` by timing production tokens, every partition rounds
its bf16 partials differently, so greedy transcripts varied across
processes (HEAD: 4 / 7 / 5 distinct transcripts in 10-12 runs at
1K / 4K / 8K). It now uses the shared rule
next_pow2(16 * gpu_cores / q_heads), bounded by the work tiles and by
the kernel's temporary-storage cap (mlx_paged_grouped_d128_max_stripes,
still a hard cap; below 4 it stays generic). On the M5 Max that is 32
for Muse, level with generic at 1K and 1.2-2.3x faster in attention from
4K to 60K (kernel replay on real Q/K/V). The helper moved to
engine/decode_tuning.rs and Gemma4 uses it unchanged.

The attention-stage sweep had no caller left and is deleted with its
tests and MLX_MUSE_DECODE_TUNING; the submission-depth sweep stays
(depths 0..51 give one hash).

  muse-glimmer-30b-q4k, fresh processes   1K 12/12 one hash   4K 12/12   8K 10/10
  decode tok/s vs HEAD                    within noise (loaded machine)

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…s a turn

- Gemma4 raw vs graph decode: the raw route attended the sliding-window
  layers over the full block table plus a mask while the graph route
  trimmed it to the live window, so generic V2 split the keys at
  different 512-token boundaries. One `decode_read_span` helper now feeds
  the graph route, the raw route and the batched builder (raw = graph
  bit for bit, test at windows 0 / 513 / 2048).
- Muse-Glimmer whole-turn vs scheduled lane: whole-turn decode used the
  generic route while the scheduler used the grouped D128 kernel; both
  now enter the same single-row plan. Whole-turn prefill also slices on
  the scheduler's 512-token grid (which also fixes whole-turn prompts
  above ~2.5K failing with context_length_exceeded). Batched decode rows
  stay on generic V2 (the grouped kernels serve one sequence per
  dispatch); documented in concurrent-inference.md.
- MLX_MUSE_GROUPED_STRIPES is capped at the live temporary-storage limit.
- K2-Horizon takes the shared partition rule instead of a context table;
  mlx_paged_grouped_d128_default_stripes is deleted.

  gemma-4-e2b 4K   raw = graph = 3b8ca77f44 (grouped on), f5c51b41dc (off)
  muse 1K / 2.2K / 4K   whole-turn = scheduled (4K whole-turn used to fail)
  decode tok/s     unchanged within noise

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…l grid as whole-turn

- a one-row decode wave called run_paged_decode_step_batched's generic
  [N,1] gather with no PlanScope, so D512 layers resolved generic V2
  while whole-turn used the grouped kernel: one-row waves now delegate
  to run_paged_decode_step_for under the same decode_tuning plan
- prefill slicing differed between lanes (scheduler-pinned boundary
  lists vs the whole-turn chunker): one shared prefill_slice_ends grid
  (chunk steps + cold-anchor rungs) now feeds admission, SSD restore,
  preemption resume and the whole-turn chunker
- keeps the unknown-sequence / cross-group-count fail-fast check in the
  one-row arm via request_token_count_all

  gemma-4-e2b-it-4bit   whole-turn = scheduled at 54-tok, 1K, 4K prompts,
                        grouped on/off and SSD cold tier alike; bit-equal
                        logits in a new metal test

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@Brooooooklyn
Brooooooklyn force-pushed the perf/splash-parity-kquant-tiled-int8kv branch from 9741cfc to 08facbe Compare October 8, 2026 12:29
CI's toolchain bump (clippy 1.99) promotes this to an error under
-D warnings; iterate the route names directly.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…to bf16

CI's macos-26 VM GPU has no GPUFamilyApple7/NAX and a smaller threadgroup
budget, so routes and fused kernels that exist on dev silicon are absent
there — the same divergence class as the timing-sweep partitions removed
earlier on this branch.

- qwen3_5_delta_chat::flat_clone_model_dir pins kv_format="bf16": the
  heal/warm byte-parity oracle only holds where committed (M=1/M=8) and
  re-prefill (chunked) K/V rows share bits — NAX gen>=17. Int8 per-row
  quantization amplifies the residual sub-ulp gap past a marginal greedy
  tie on the VM GPU (desync_heal_reprefills_to_uncancelled). Tracks the
  underlying parity gap in #201.
- kquant_tiled_tests: bit-identical arms are calibrated for the gen-17
  kernel pairing (row-major qmv_wide only on gen>=15; tiled always takes
  the t64 variants). Exact on gen-17, close(3e-2) elsewhere; CPU reference
  still exact on every device.
- int8_verify_routes / segmented_verify_tile: block-route asserts now key
  off the tile/nax plan probes instead of requiring routes the device
  cannot launch; the no-Metal MLX_TEST_REQUIRE_METAL guard is unchanged.
- gated_delta fused tests: probe the fused pipelines once
  (fused_step_launches/fused_complete_launches) and SKIP when the device
  declines; the geometry-refusal asserts (Dv!=128, T>16) still run on
  every device by moving them ahead of the capability gate.

Verified locally (M5 Max): all touched tests pass with every route still
exercised (vector/tile/nax blocks 150/150/150, fused asserts 0 ulps);
delta_chat heal/warm passes on native, applegpu_g15s and applegpu_g16s.
…ions

Same M=3 tiled-vs-row-major kernel pairing as the merged-forward assert
two blocks up: on non-gen-17 GPUs the routes differ in ulps, which the
CI VM GPU showed. close(3e-2) there, exact on gen-17.
…ff gen-17

merged_draft_projections_match_separate_bits asserted bitwise equality
for all heights except merged_rows() (M=8). That contract only holds on
gen-17 where the tiled kernels reduce each row identically at any width;
other GPUs pair different kernels at the merged width, and the test's
unseeded random inputs turn the residual ulp gap into flaky failures —
the CI VM GPU showed it at T=1 layer 1 block keys. Reuse the existing
assert_bits_match tolerance arm (max |diff| <= scale/64, <=5% differing)
for every height on non-gen-17 GPUs; CPU stays bit-identical.
… routes

Two problems on the CI VM GPU:
1. Row-major q4k at M=8 asserted qmv_sg8, which only exists on gen-17.
   Gen-15/16 take qmv_wide and older gens plain qmv (or the GEMM at the
   batch limit). The route probe now counts the qmv family too and the
   asserts follow the real dispatch ladder.
2. The file's tests race: cpu_reference parks the default device on the
   CPU between GPU evals, so a parallel route probe can eval on the CPU
   and read all-zero kernel counters — a plausible cause of the all-zero
   route line seen on the VM. A DEVICE_LOCK now serializes the three
   tests in this binary.
@Brooooooklyn
Brooooooklyn merged commit 8b8ae05 into main Oct 9, 2026
11 checks passed
@Brooooooklyn
Brooooooklyn deleted the perf/splash-parity-kquant-tiled-int8kv branch October 9, 2026 01:51
Brooooooklyn added a commit that referenced this pull request Nov 8, 2026
An f16-compute load (mlx convert --dtype float16) got int8 flat K/V at head
256 / GQA <= 8: the int8 segmented SDPA verify takes BF16 queries only, so
the MoE compiled DFlash2 verify failed the turn and dense fell back to the
eager int8 read (whole-prefix dequantize, f32 SDPA). Splash is BF16-only
(bfloat queries in its int8 kernels; f16 weights narrowed at image write).

KvFormat::default_for_geometry now takes the compute dtype, and both loaders
pin the format after the weights give it (the embedding's output dtype,
after the MoE affine-sidecar alignment). An explicit kvFormat still wins.
This also closes the dense hole open since #183.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Brooooooklyn added a commit that referenced this pull request Nov 12, 2026
An f16-compute load (mlx convert --dtype float16) got int8 flat K/V at head
256 / GQA <= 8: the int8 segmented SDPA verify takes BF16 queries only, so
the MoE compiled DFlash2 verify failed the turn and dense fell back to the
eager int8 read (whole-prefix dequantize, f32 SDPA). Splash is BF16-only
(bfloat queries in its int8 kernels; f16 weights narrowed at image write).

KvFormat::default_for_geometry now takes the compute dtype, and both loaders
pin the format after the weights give it (the embedding's output dtype,
after the MoE affine-sidecar alignment). An explicit kvFormat still wins.
This also closes the dense hole open since #183.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Brooooooklyn added a commit that referenced this pull request Nov 12, 2026
…e geometry (S3) (#343)

## What

Stage 3 of the Splash int8 KV alignment. It is stacked on #342 (S2),
which is stacked on #336 (S1).

The flat full-attention K/V of `qwen3_5_moe` now takes the same geometry
default as dense `qwen3_5`. The old MoE-only BF16 override in
`Qwen3_5MoeConfig::to_dense_config` is removed.

```
KvFormat::default_for_geometry(head_dim, q_heads, kv_heads)
  Metal && head 256 && gqa in 1..=8  -> Int8
  else                               -> Bf16

Qwen3.8-27B  dense  24/4  gqa 6   int8 (unchanged)
Qwen3.6-35B  MoE    16/2  gqa 8   int8 (was BF16)   <- this PR
Qwen3.6-122B MoE    32/2  gqa 16  BF16 (gap)
```

Splash (`031a25a6`) uses int8 for every model
(`RuntimeResources.hpp:103`, `RuntimeResources.mm:727-728`). It has one
kernel per geometry, including `_kv2_g16` for 32/2/256
(`PagedAttention.cpp:59-65`).

## Gap: 122B stays BF16

mlx-node has no gqa-16 int8 verify kernel for wide blocks:

```
two-pass stage 1 = 32 x gqa x rows threads <= 1024
gqa 8  -> 4-row chunks -> 8-row verify = 4 + 4      ok
gqa 16 -> 2-row chunks -> 5-8 row verify blocks     error (int8 has no fallback)
```

So the default adds the bound `gqa in 1..=8`. `kvFormat: 'bf16'` (load
option, `--kv-format bf16`, or `kv_format` in `config.json`) opts out on
any model. Lift: a gqa-16 int8 verify kernel, like Splash `_kv2_g16`.

## DFlash2 window (35B-A3B, M3 Pro inputs)

| Case | Row bytes | Window |
|---|---|---|
| 27B int8 (S1) | 33,280 | 139,257 |
| 35B BF16 | 20,480 | 244,217 |
| 35B int8 | 10,400 | **262,144** (trained cap; the pool term is
475,129) |

## Quality (teacher-forced, int8 vs BF16 K/V, 8 x 8192 tokens, M5 Max)

| Model | Run | kvFormat | mean KL | top-1 | KL after 2048 | top-1 after
2048 |
|---|---|---|---|---|---|---|
| 35B-A3B | bf16 control | bf16 | 0 | 1 | - | - |
| 35B-A3B | default (no flag) | int8 | 0.004670 | 0.977460 | 0.006226 |
0.969945 |

- The stop band is top-1 < 0.97 or KL > 0.05. The whole-run numbers
pass. The tail top-1 is 3 positions out of 49,144 under 0.97 (0.07 SE),
so it is noise. NLL moves +0.0013 nats.
- 27B was not measured in this PR. Its score run failed during the
weight load with a GPU timeout. The 27B default does not change here.
- DFlash2 acceptance on 35B was not run, because no local 35B draft
exists.

## BF16 compute only (review fixes)

```
default_for_geometry(head, q_heads, kv_heads, compute)
  Int8 only if Metal && compute == BF16 && head 256 && gqa in 1..=8
load: probe the compute dtype -> pin kv_format -> build caches   (dense and MoE)
an explicit kvFormat still wins
```

- `1bc057823`: an FP16 MoE load (`mlx convert --dtype float16`) got int8
K/V. Its compiled DFlash2 verify then failed the turn, because
`segmented_sdpa_int8` takes only BF16 queries. Now an f16 or f32 load
keeps BF16 K/V. Dense had the same hole since #183 (it fell back to a
slow eager path), and the same rule closes it.
- `1e6662ae1`: the int8 compiled verify casts non-BF16 queries to BF16,
as Splash does (its int8 kernels take `bfloat` queries). No real
checkpoint makes that mix, but no turn can abort now.
- Tests: `kv_format_default_needs_an_int8_verify_kernel`,
`moe_load_pins_the_kv_format_for_the_compute_dtype`,
`dense_load_pins_the_kv_format_for_the_compute_dtype`,
`int8_compiled_verify_takes_f32_queries`. Each one went red under its
named mutation.

## Tests

- `kv_format_default_needs_an_int8_verify_kernel` and
`int8_verify_chunks_bound_the_default_gqa` pin the gqa bound.
- `eager_forward_over_an_int8_cache_tracks_the_bf16_cache` now covers
24x4 and 16x2, and it counts int8 kernel reads.
-
`moe_flat_cache_precision_follows_the_geometry_default_and_explicit_format`
and `moe_dflash2_window_prices_the_default_format` cover the MoE flip
and the window.
- The two MoE paged-vs-flat parity tests pin the flat side to BF16.
- Each new test went red under its named mutation and green after the
revert.
- Gates: `cargo clippy --all-targets -D warnings`, `cargo test -p
mlx-core --lib` on the touched modules (686 passed), `yarn typecheck`,
and the CLI/loader vitest files (232 passed).

CI does not run on this PR until its base is `main`.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Brooooooklyn added a commit that referenced this pull request Nov 12, 2026
Stage S10 of the Splash int8 KV alignment (stack #344). Base: S9 (#367).

Qwen3.5 dense and MoE paged prefill chunks (fresh, first or cache hit)
and MTP / DFlash2 verify blocks now store their rows into the pool
first, then attend **in place** over the pool pages. This uses one new
split + reduce kernel, on int8 and bf16 pages. Splash:
`QwenTarget::addPrefillMixer`, `ops/PagedAttention`.

```
before:  chunk ──► gather pool rows to a dense bf16 copy ──► MLX SDPA ──► store
         first chunk: SDPA over its in-flight bf16 rows
after:   chunk ──► store into pages ──► paged_prefill_attention (splits) ──► in-order reduce
         every chunk reads its own rows back as stored (int8 on an int8 pool)
```

## Kernel
(`crates/mlx-paged-attn/metal/attention/paged_prefill_attention.metal`)
- Splash's tile: 8 rows with the query group fused,
`SPLASH_ATTENTION_TILE_PARTS` (a group of 16 runs as 2 parts), per-tile
`causal_end` and visible pages, f32 partials, and a reduce that sums
splits in a fixed order.
- One 32-token Splash page = two 16-token mlx-node blocks. Keys are
staged per page in threadgroup memory (vLLM key layout). Values are read
in place. Queries are staged KV-head-major before the kernel.
- Splits: prefill uses the Splash 1.6 rule
`clamp(ceil((history+rows)/32)/pagesPerSplit, shared, most)`. Verify
uses `clamp(ceil(pages/16), 32, 128)`. Pages per split comes from
`KernelCalibration::of`: 32, or 64 on non-M5 GPUs with ≤ 10 cores. With
no core count reported, 32 cores are assumed.
- MPP (Metal 4 tensor ops) on every GPU family. 24 instances: groups {4,
6, 8, 16} × D {128, 256} × {int8, bf16}, plus the reduces. Built at the
26.2 target with no `-std` flag.
- No GPU floor. Splash starts at Apple9 for its whole engine
(`DeviceCapabilities::gpuClass`), not for this kernel, and mlx-node
supports M1+. M1/M2 take the Apple9 pages-per-split row. A pipeline that
does not build fails the turn loudly, with the kernel and the Apple GPU
family named.

## Changes in the model
- A new `PagedPass {Decode, Prefill, Verify}` replaces `is_prefill` /
`cached_prefix_len`.
- The workspace is one buffer per adapter, shared by all full-attention
layers (Splash's one arena).
- Deleted: the gather + MLX SDPA cache-hit route, the first-chunk
in-flight SDPA, the cache-hit mode / plan / headroom logic,
`PrefillSdpaKernels`, `estimate_paged_pool_sdpa_bytes_with_portable`,
the int8 varlen estimate, the int8 branch of `gather_kv_dense_range`,
`mlx_segmented_sdpa_forward`.
- The adapter's one workspace is plain scratch (Splash `RuntimeArenas`
`AttentionPartials`): `release_request` and `clear_native_graph_state`
drop it, so a failed turn's unevaluated graph never reaches the next
launch.
- Pools zero-fill their planes on create and on grow, as Splash's
buffers come back zeroed.
- A pool load needs a geometry with a kernel instance (Splash: "no
paged-attention kernel for layout"). Small test fixtures move to 8/2
heads with D 128.

## Memory plan
The prefill attention term is now Splash's tensors for one lane: the
workspace bound + query staging + output + the chunk's K/V rows. It has
no history term.

| plan | before | after |
|---|---|---|
| prefill attention, 2,048 rows / 8-row verify | (gather term, grows
with history) | 109,445,120 / 25,886,720 B |
| M3 Pro bf16 window | 48,601 | 54,425 |
| 27B int8 + DFlash2 window | 94,201 | 98,297 |
| serial MTP window | – | 57,337 |

The verify arm also charges the prefill-sized workspace the adapter
keeps through every verify (Splash `fixedRuntimeBytes` sums the prefill
and decode arenas): 35B-A3B + DFlash2 lane 179,257,344 → 196,165,632 B
at every window; the 27B only moves at window 512.

The window grows because the gather term is gone. Splash has no such
term. The term-by-term check against Splash's arenas
(`RuntimeArenas.cpp`, `PagedAttention.cpp`) found one undercharge, the
chunk's K/V rows, which is now charged. The remaining gaps are
structural and documented: 4-lane query padding (3.5 MB), the fixed
prefill arena vs per-graph MLX scratch, and the lane / staging
differences owned by S4, S13 and S17.

## Tests
- `paged_prefill_attention` (kernel vs an f64 reference over the stored
rows, every query head, int8 and bf16, gqa 4/8/16, (P, T) incl. (0,
2048), (30720, 2048), (70000, 547), (70000, 9));
`paged_attention_reads_its_own_rows_back`;
`verify_takes_the_verify_split_rule` (dense + MoE);
`pool_attention_term_is_the_splash_workspace`;
`pool_needs_a_prefill_kernel_geometry`;
`a_paged_prefill_pipeline_failure_names_the_gpu_family`;
`verify_transient_charges_the_held_prefill_workspace` (V1);
`a_reset_drops_the_held_prefill_workspace` (WS1).
- Named mutations, each red when on and green when off (`MUTATIONS.md`):
own chunk read in flight (O1), off-by-one `causal_end`, splits =
`shared`, interleaved head grouping (B1, missed by a first/last-head
check), K/V charge dropped (K1), Apple9 floor restored (A1, red under
`MLX_METAL_GPU_ARCH=applegpu_g13s`), and re-runs of every re-pinned plan
test (`G`, `A0`, `S0`, `PB`, `CF`, `AU`, `D0`, `T0`, `ST`).
- `cargo fmt --check`, `cargo clippy --all-targets -D warnings`, `cargo
test -p mlx-paged-attn` (all binaries), `bridge_metallib_names` (24
names, 24 pipelines on M5), `yarn build:native`, `yarn typecheck`:
clean. mlx-core `--lib` (`RUST_TEST_THREADS=1`): 4,756 passed, 0 failed.
- With `MLX_METAL_GPU_ARCH=applegpu_g13s` (M1 routing) on
`models::qwen3_5`: 572 passed, 1 failed. The failure is
`dflash2::tests::merged_draft_projections_match_separate_bits` (#183
merged draft projections). S10 does not touch it: its 5% element bound
does not hold for the gen-13/14 MLX kernels.

## Gaps
- The kernel has not run on real M1/M2 hardware (LIVE L6). The
pages-per-split row for M1/M2 is not measured.
- K staging takes about 29 KiB of threadgroup memory, where Splash uses
about 13 KiB. Read the speed gates with this in mind.
- AR decode keeps the old decode kernel, and continuous-batching verify
keeps the varlen kernel. DFlash2 and AR tokens can therefore differ at
bf16 ties. Two DFlash2-vs-AR token checks became cursor checks (MoE
every-keep) or run-vs-run checks (dense parked resume).
- The flat full-attention path is unchanged. It is deleted in the next
stage (RULES #10).
- `qwen35_paged_prefill_operator_bench.rs` still benchmarks the deleted
routes. `docs/mlx-fork.md` uses it as an MLX D256 benchmark.

## Not in this PR (live, not run)
- L1 teacher-forced KL / top-1, int8 vs bf16 pages; L2 cold 8K and 72K
prefill time + peak memory vs S9; L3 one 64-row and one 256-row chunk
after 64K; L4 DFlash2 decode / verify speed (≥ 0.95× S9); L5 M3/M4; L6
M1/M2 pipelines and numbers.

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

---------

Co-authored-by: Claude Opus 5.5 <[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