Repository navigation
perf(qwen4): batched sparse prefill and run-time kernel sizes for Flash Next - #294
Conversation
|
Important Review skippedAuto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the ⚙️ Run configuration
You can disable this status message by setting the Use the checkbox below for a quick retry:
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. Comment |
40f293d to
bf62766
Compare
qwen4_gather_window took N, BASE, FRESH and POOL as template args, so every decode step and every per-token prefill row compiled a new Metal library that MLX caches forever. Read N and FRESH from the input shapes, POOL from the key pool size, and pass base as a 0-d int32 input. H, D and BS stay template args; the bounds checks are unchanged. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
LayerCache now holds the compressed indexer keys as one [blocks, head_dim] array instead of a Vec of rows. Blocks are appended with concatenate, so snapshot and device-route replay handles stay valid. Sparse selection casts this array instead of concatenating every block on each token. The block math (f32 mean, k_norm, rope at block start) is unchanged. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
… windows Prompt windows past indexer_budget no longer fall back to one token at a time. The window path now selects blocks for every row in one graph (mlx-vlm select_from_projected: f32 head-summed ReLU scores, -inf past each row's complete blocks, argpartition, -1 for invalid picks, sorted) and attends through a port of mlx-vlm's indexed sparse-attention kernel, with chunk length and key length read from runtime shapes. Rows whose complete blocks fit the budget select all of them, so they stay causal. MLX_QWEN4_BATCHED_QSA=0 restores the per-token path. F32, verification, MTP position overrides and head dims not divisible by 32 keep it too. The page gather reads its token count at run time, and the prefill scratch bound covers the batched selection and contiguous K/V prefix. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…SIMD groups The indexed kernel gives each incomplete-block token one SIMD group, and a 1024-thread threadgroup has 32 of them. A row's incomplete block holds up to indexer_compress_ratio - 1 tokens, so ratios above 33 silently dropped the 33rd and later tail keys. Such configs now take the per-token path, and the C entry point refuses block sizes above 33. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The prefill expert kernels took row counts as template args: R and S in qwen4_prefill_indirect_gate_up, R in qwen4_prefill_indirect_down, qwen4_expert_prefill, qwen4_dense_prefill and the route count/scatter pair, R and NT in qwen4_expert_tiles, and TOKENS and ROWS in qwen4_sorted_combine. Each slot group and each prefill window has its own row count, so every one compiled a new Metal library that MLX caches forever. E in the indirect kernels came from the tile table size, which also tracks R. These values only bound loops and guard tails, so read them from the input shapes instead. Tile sizes, bit widths, dtypes and the expert count that sizes threadgroup arrays stay template args. Outputs are unchanged. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
bf62766 to
912eda8
Compare
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
…, MTP draft banks, flag purge, device-route MTP verify, draft-side levers, pack stream pool (Phase 3 + Phase 4 + Phase 5 L2) (#297) > **Ready for review.** Stacked on #294 (`perf/qwen4-sparse-prefill`, `912eda8c9`, 5 commits over main). Head `c1ac42df3`, rebased onto main `61a706829` on 2026-10-22, 80 commits over #294. Stack #309: #294 → #297 → #295, all three ready for review. The timing build is `a706d8058` (pre-rebase). Later commits changed no mapped-path bits: the unit digests and D3 6k were rerun on every later head (P5/X/A, P5/Z, CLEANUP/PART2). Stage III adds L2c (MTP draft bank built at load), #8 (PLE key/value rows four per row-kernel call), #7 (mixer activation K walk over eight simdgroups, split8) and c2 (a cold prompt runs layer-major over the streaming pack). Text is unchanged: the same 6k / 16k shas, AR == MTP. The slot residency path now gives the same tokens as the mapped path (P5-X), which closes the Codex Stage III finding. The indirect expert prefill runs eagerly (closes Codex pass 2, compile-cache growth); five MTP draft-bank tests pass on the 7 GB CI runner; the cleanup drops the finished A/B switches and research-only tests. Stage II (FINAL4, 2026-10-21) is ahead of llama.cpp b11717 on every decode row and every warm or 16k prefill row. With c2 the immediate cold 6k request drops from 11.7-12.4 s to 6.9-7.1 s, at the top of llama.cpp's 6.0-7.0 s band. FINAL5 (2026-10-22, `a706d8058`) ran 10 timing rows + 1 trace row, all still loaded-host (foreign GPU 31.4-44.5 % mean; one row 10.6 %). Stage III cold 6k TTFT: AR 6.92 s (0.87x ; 0.92x, behind), MTP-2 6.92 s (1.01x ; 0.94x, parity). ## Goal Qwen3.8 Flash Next must run from SSD streaming on a single 128 GB Mac at llama.cpp speed or better, with identical text and no experiment flags. ## Design in one picture ``` load: dense banks -> MTP draft bank (L2c) -> pack stream starts (8 workers, 4 MiB preads, layer order) cold turn over a streaming pack (c2): layer 0: window 1 .. window N <- the stream reads layer 1, 2, ... meanwhile layer 1: window 1 .. window N each expert bank binds once per prompt ... tail under 256 rows: its own pass after the group warm turn / resident pack: window-major as before (1024-token windows) decode: mapped banks, R-row exact kernels for MTP-2 verify (#8 PLE rows, #7 split8 mixer) ``` Same windows, kernels and per-window shapes in both orders, so the bits do not depend on the loop order (D3 group vs window: max_ulp 0). ## Result vs llama.cpp b11717 (Stage III `a706d8058`, addon `7ac1d006e53b`, FINAL5; Stage II `9cd299141`, FINAL4) Same machine, page cache evicted before every run (a cold request reads the whole 73 GiB pack), one process per run, empty `MLX_*` environment, no addon swap, 0 in-request Metal compiles in all 12 timing runs. Three requests per process: cold 6k, 16k, warm 6k. Ranges over 2 AR + 3 MTP-2 accepted runs. llama.cpp is not re-run per round: the reference rows are the stored clean runs of 2026-10-20 and 2026-10-21 on this machine (`LLAMA-REFERENCE.md`); each ratio gives the 2026-10-21 row first. In FINAL4 a foreign-load gate (> 300 % foreign CPU or a compiler alive in > 50 % of a request window) re-ran 7 attempts and kept them out of every number. FINAL5 (2026-10-22) adds a wired-drop gate per request, a 20 s GPU sample before launch (idle = every sample < 10 %), and 40 s idle after the last turn with the process loaded. Caveat for Stage III: 0 of 10 rows had an idle GPU (foreign GPU mean 31.4-44.5 %, one row 10.6 %); vm pressure normal and thermal nominal on every sample; 3 load-gate reruns (OrbStack, a foreign rustc, Firefox + XProtect), each rerun passed all gates. | Metric | Stage III (FINAL5), range (mean) | Stage II (FINAL4) | Stage I (`9a8d1e220`) | llama.cpp AR (`FINAL4-llama-off-1` ; `FINAL3-llama-off-1`) | llama.cpp MTP-2 (`FINAL4-llama-on-1` ; `FINAL3-llama-on-2`) | Stage III ratio (2026-10-21 ref ; 2026-10-20 ref) | Stage II ratio (2026-10-21 ref ; 2026-10-20 ref) | |---|---|---|---|---|---|---|---| | Warm 6k prefill, tok/s | AR 1,323.7-1,360.7 (1,342.2); MTP 1,201.8-1,285.0 (1,254.5) | AR 1,197-1,215; MTP 1,231-1,298 | AR 1,112-1,161; MTP 1,116-1,241 | 896 ; 853 | 843 ; 852 | AR **1.50x ; 1.57x**, MTP **1.49x ; 1.47x** | AR **1.35x ; 1.41x**, MTP **1.50x ; 1.48x** | | 16k prefill, tok/s | AR 1,107.0-1,139.0 (1,123.0); MTP 1,079.6-1,116.9 (1,094.0) | AR 1,086-1,122; MTP 985-1,103 (1,070-1,103 without the host-event row, see gaps) | AR 909-1,001 (both rows disturbed by foreign load); MTP 1,088-1,146 | 946 ; 872 | 863 ; 907 | AR **1.19x ; 1.29x**, MTP **1.27x ; 1.21x** | AR **1.17x ; 1.27x**, MTP **1.22x ; 1.16x** | | Cold 6k prefill, tok/s | AR 897.5-899.8 (898.6); MTP 897.6-900.0 (899.1) | AR 539-541; MTP 515-521 | AR 473-476; MTP 442-459 | 1,034 ; 975 | 889 ; 955 | AR 0.87x ; 0.92x (behind), MTP 1.01x ; 0.94x (parity) | AR 0.52x ; 0.55x, MTP 0.58x ; 0.54x | | AR decode, steady tok/s (cold 6k / 16k / warm 6k) | 48.09-49.55 / 47.42-48.69 / 49.79-50.87 (48.82 / 48.05 / 50.33) | 52.5-55.0 / 51.2-52.3 / 52.5-53.4 | 51.2-51.8 / 44.0-49.7 / 50.4-51.7 | 45.0 / 43.5 / 43.6 ; 42.0 / 40.7 / 42.6 | – | **1.08x / 1.10x / 1.15x ; 1.16x / 1.18x / 1.18x** (worst run 1.07 / 1.09 / 1.14 ; 1.14 / 1.16 / 1.17) | **1.19x / 1.19x / 1.21x ; 1.28x / 1.27x / 1.24x** | | MTP-2 decode, steady tok/s (cold 6k / 16k / warm 6k) | 73.71-74.12 / 70.38-71.61 / 74.72-75.68 (73.97 / 70.95 / 75.28) | 72.7-78.4 / 75.9-76.6 / 77.5-79.8 | 74.0-76.3 / 70.5-74.8 / 73.8-79.0 | – | 72.0 / 67.6 / 68.7 ; 71.7 / 69.4 / 71.5 | 1.03x / 1.05x / **1.10x** ; 1.03x / 1.02x / **1.05x** (worst run 1.02 / 1.04 / 1.09 ; 1.03 / 1.01 / 1.04) | **1.05x / 1.13x / 1.15x ; 1.05x / 1.10x / 1.10x** (worst run 1.01 / 1.12 / 1.13) | | Cost per step, ms (AR step / MTP-2 cycle) | 20.4 / 36.6 | 18.9 / 34.9 | 20.1 / 35.2 | 22.7 ; 23.9 | 39.4 ; 38.6 | AR 1.11x ; 1.17x, MTP 1.08x ; 1.06x | | | 16k TTFT, per request | AR 16.47-16.94 s (16.70); MTP 16.79-17.37 s (17.15) | AR 16.7-17.3 s; MTP 17.0-19.1 s | AR 18.7-20.6 s; MTP 16.4-17.2 s | 19.8 ; 21.5 s | 21.7 ; 20.7 s | **1.19x ; 1.29x** / **1.27x ; 1.21x** faster | **1.17x ; 1.27x** / **1.22x ; 1.16x** faster | | Cold 6k TTFT, per request | AR 6.91-6.93 s (6.92); MTP 6.91-6.93 s (6.92) | AR 11.50-11.54 s; MTP 11.94-12.08 s | AR 13.1-13.2 s; MTP 13.6-14.1 s | 6.01 ; 6.38 s | 7.00 ; 6.51 s | AR 0.87x ; 0.92x (behind), MTP 1.01x ; 0.94x (parity) | 0.52x ; 0.55x / 0.58x ; 0.54x | | Warm 6k TTFT, per request | AR 4.57-4.70 s (4.63); MTP 4.84-5.17 s (4.96) | AR 5.12-5.20 s; MTP 4.79-5.05 s | | 6.94 ; 7.30 s | 7.38 ; 7.30 s | AR **1.50x ; 1.58x**, MTP **1.49x ; 1.47x** | | | Cold 6k TTFT, request 8 s after load (1 run per arm) | AR 6.94 s; MTP 6.16 s | AR 7.38 s; MTP 8.41 s | not run | 6.01 ; 6.38 s | 7.00 ; 6.51 s | AR 0.87x ; 0.92x, MTP **1.14x ; 1.06x** (1 run, lighter foreign GPU: 10.6 %) | 0.81x ; 0.86x / 0.83x ; 0.77x | | Cold 6k TTFT, from load start | AR 9.73-9.94 s (9.83); MTP 9.74-9.89 s (9.81) | AR 13.7-14.0 s; MTP 14.0-14.3 s | 15.1-15.2 / 15.5-16.1 s | 36.1 ; 34.4 s | 39.1 ; 35.6 s | AR **3.67x ; 3.50x**, MTP **3.98x ; 3.62x** faster | **2.5-2.6x / 2.5-2.8x faster** | | Peak footprint | AR 10.7-12.1 GiB; MTP 11.3-12.1 GiB (L2c bank in both arms) | AR 7.9-9.2 GiB; MTP 11.3-11.4 GiB | 7.9-9.2 / 11.4-11.7 GiB | 1.5-1.6 GiB footprint + 78 GiB mmap | 2.4-2.5 GiB + 82 GiB mmap | | | | 16k + 40 GiB touching hog, MTP-2 | not run in FINAL5 (c2 gates: slots 225, 64/64) | completes 64/64 on the slot fallback (174 slots at 54.6 GiB available; 11.0 tok/s, 39/46 drafts accepted) | 64/64 (218 slots, 14.7 tok/s) | not run | | | | - Text is identical in every run, AR == MTP (6k `bfb8e8bb3bd0c768`, 16k `6a63463a98644df6`); none of the Stage II changes moved one token. MTP-2 acceptance 0.823 -> 0.847 (2.656 -> 2.684 tokens per cycle; by position 0.905 / 0.787 at 6k, 0.926 / 0.766 at 16k). FINAL5: the same two shas on all 30 requests of the 10 rows, MTP 95 / 189 / 160 on every MTP request, the same acceptance by position. - Stage III vs llama: ahead on warm 6k and 16k prefill / TTFT in both arms and on AR decode (1.08-1.18x). MTP-2 decode: cold 6k and 16k parity (1.03x ; 1.03x and 1.05x ; 1.02x), warm 6k ahead (1.10x ; 1.05x). Cold 6k TTFT: AR behind (6.91-6.93 s = 0.87x ; 0.92x, llama 6.01 ; 6.38 s), MTP-2 parity (1.01x ; 0.94x). - Stage II -> Stage III (FINAL4 -> FINAL5): cold 6k TTFT AR -39.9 % / MTP -42.3 %; warm 6k TTFT AR -10.2 %. AR decode 7-9 % lower (cold 6k -9.2 %, 16k -7.1 %), MTP-2 16k decode -7.1 %; AR step 18.9 -> 20.4 ms, MTP cycle 34.9 -> 36.6 ms. Load AR +25.1 %, MTP +34 % (L2c builds the bank at load). AR peak +2.5-2.9 GiB (the AR arm holds the 2.83 GiB MTP bank). The decode drop is open (see gaps). - Stage I -> Stage II under the same protocol: cold 6k TTFT -1.6 s (AR) / -1.9 s (MTP), MTP-2 decode +0.3 / +4.3 / +2.3 %, MTP cycle 35.2 -> 34.9 ms, load 2.0 -> 2.3 s (the pack stream starts at load). The AR 16k and AR decode differences come from foreign load on the Stage I rows, not from code. - Wired memory: Stage II 87-91 GiB in a turn, 6-8 GiB within 5-55 s after exit (all 8 mapped runs). Stage III (FINAL5): 87.6-90.6 GiB in a turn, 6.7-7.3 GiB 1 s after exit, 6.7-7.4 GiB at turn end + 35 s with the process loaded (no hold). ## Phase 5 Stage III (`c2e7bba65`, `2fc0426c5`, `ca51f4692`, `bfa046494`, `a41bf6a7a`, `2e12d1beb`, `3bdca3614`, `8cfc05371`, `e98d4c733`, `0df94ece6`, `142cff3e0`, `734430a6f`, `299b4defb`, `071588e44`, `12f7fdb74`, `3c0d8a5a1`) Headings and commit columns name commits at `3c0d8a5a1`. Result rows name the measured pre-rebase trees: L2c `313430e52`, #8 `4e7b3608b`, #7 `52611c9d2`, c2 `829f474cf` / `57512c0b9` / `748389987`, T11 `a706d8058`, P5-X `a95cb2492` / `1b90c2e62`, Stage II `9cd299141`, Stage I `9a8d1e220`. All timing below is loaded-host (foreign GPU ~40 % mean before launch; the GPU-idle rule failed on every row, FINAL5 included). Rows marked REJECT also failed the CPU load gate. Text shas 6k `bfb8e8bb3bd0c768` / 16k `6a63463a98644df6` on every mapped run, AR == MTP, MTP 95 / 189 / 160 on every request. | Commit | What | Measured effect (run tag) | |---|---|---| | L2c `c2e7bba65` | The Q8 MTP draft bank (2.83 GiB) is built at load, after the dense banks and before the pack stream. No turn builds anything. A declined build warns and the load goes on. | MTP request 8 s after load: 6k TTFT 8.41 -> 7.32 s, request SSD 5.77 -> 1.07 GiB. MTP immediate: 11.94-12.08 -> 11.62 s, request SSD 77.2 -> 72.5 GiB (FINAL4 MTP rows -> `L2C-after-d8-on-1`, `L2C-after-on-1`, both loadcheck OK). Cost: with the aux attached the AR arm also holds the 2.83 GiB bank and reads 4.7 GiB more at load (+0.5-1.0 s load). | | #8 `2fc0426c5` | A prefill window projects PLE key and value through the exact row kernel in 4-row groups (256 calls per 1024-token window) instead of one M=1 gather GEMV per token. MTP verify projects all rows' PLE in one call. | 16k TTFT AR 17.50 -> 17.08 s (last interleaved pair), MTP 17.68-17.95 -> 17.40-17.47 s; warm 6k TTFT AR 4.97 -> 4.57 s, MTP 4.86 -> 4.60 s (`PLEHC-*`, see the table below). Bit-identical: probe B-8 0 differing values; 2 new bitwise tests. | | #7 `ca51f4692` | The decode mixer activation (HC down, Q8 320 x 10240) runs eight simdgroups per output. Each stores its block terms; simdgroup 0 adds all 40 in the old order. The partial-sum form is not exact and is not used. | MTP-2 decode 70.65 -> 71.51 tok/s, cycle 38.15 -> 37.71 ms (ranges do not overlap). AR decode 49.17 -> 49.39 tok/s: ranges overlap, not measurable (`PLEHC-*`). Kernel alone: 12.21 / 18.25 -> 10.37 / 11.79 us at 1 / 3 rows (probe B-7, 0 differing values). | | c2 engine `bfa046494` | The scheduler can give a cold turn one whole-prompt prefill step (per-family hook, default off). A K/V write entry takes chunks anywhere above a recorded floor; the strict suffix entry stays. Row fetch: 32 readers (was 4), pending limit 1 << 20 (was 1 << 16). | Enables c2; no timing on its own. | | c2 qwen4 `a41bf6a7a` | A turn that opens over a streaming mapped pack prefills as one group: every 1024-token window at layer 0, then at layer 1, and so on. A trip between sweeps evaluates the group first, then leaves the mapped path. | Immediate cold 6k AR 12.43 / 16.03 -> 6.98 / 7.05 s, MTP 11.73 / 11.94 -> 7.09 / 6.89 s (`C2G-G1*`, `C2G-G1b*`). Rebased head: AR 6.93 s, MTP 6.94 / 6.90 s (`C2INT-*`). See the c2 table. | | c2 tests `2e12d1beb` | New unit tests in tests.rs (8), weights.rs (2), scheduler.rs, hybrid_scheduler.rs and paged_kv_cache_adapter.rs; 2 real-model tests (T10 group == window at a time, T11 forced trip), D3 goes through the group path, docs. `draft_history_appends_in_place` now synchronizes after each eval (it failed 25 of 500 runs on a loaded host, 0 of 500 after). | D3 cold 6k / 16k as one group: 256 / 256, group-vs-window max_ulp 0. T10 6k: 221 arrays byte-equal (`C2INT` d3 / t10 logs). | | T11 `3bdca3614` | The forced-trip test no longer compares a slot run's text with the mapped reference (a slot run's text follows its slot count and resident expert set). It keeps the structural asserts on the switch and reruns the prompt on the same decoder, now on slots, printing both texts. | Passes at slots 454 and 461. The two trees `6d86a6ad8` and `748389987` give the same tripped text and the same plain-slot text at 454 slots, so #8 / #7 do not change the bits after a trip (`P5/C2/T11X`). P5-X below makes slot text equal to the mapped text. | Op trace (`FINAL5-trace-on-1`, MTP-2, traced addon `7709d2ec79eb`, not a timing row): PLE GatherQMM count 0 at `a706d8058` (104 at `234f4bdd1`); expert-bank GatherQMM 663. The 2560x2560 dense-decode kernels are not attributed to a projection. ### c2: immediate cold 6k request (every cold request reads the whole 73 GiB pack) | Arm | before (`313430e52` addon) | after (`85874b357` addon) | rebased head (`748389987` addon) | llama.cpp b11717 reference (2026-10-21 ; 2026-10-20) | |---|---|---|---|---| | AR, req0 TTFT | 12.43 s (REJECT) / 16.03 s (REJECT) | **6.98 / 7.05 s** (both OK) | **6.93 s** (OK) | 6.01 s (`FINAL4-llama-off-1`) ; 6.38 s (`FINAL3-llama-off-1`) | | MTP-2, req0 TTFT | 11.73 s (OK) / 11.94 s (REJECT) | **7.09 s** (REJECT) / **6.89 s** (OK) | **6.94 / 6.90 s** (rows REJECT, req0 passed) | 7.00 s (`FINAL4-llama-on-1`) ; 6.51 s (`FINAL3-llama-on-2`) | | Speed vs llama (llama TTFT / ours) | AR 0.48x ; 0.51x (12.43 s row) | AR 0.85-0.86x ; 0.90-0.91x; MTP 0.99-1.02x ; 0.92-0.94x | AR 0.87x ; 0.92x; MTP 1.01x ; 0.94x | | | From load start (load + req0 TTFT) | AR 16.0 s; MTP 14.6 s (12.43 / 11.73 s rows) | AR 10.2 s; MTP 9.8-10.7 s | AR 10.0 s; MTP 9.8-9.9 s | AR 36.1 ; 34.4 s, MTP 39.1 ; 35.6 s (FINAL4 table) | | Request SSD | 71.5-72.4 GiB | 71.9-72.3 GiB | 72.3 GiB | 0.87 GiB (llama reads the 78-82 GiB GGUF at load) | - From load start we lead: AR 3.4-3.6x, MTP-2 3.3-4.0x faster than the llama rows. FINAL5: AR 9.73-9.94 s = 3.67x ; 3.50x, MTP-2 9.74-9.89 s = 3.98x ; 3.62x. - Per request we are at the top of llama's band: MTP-2 at parity, AR 8-15 % behind, on a loaded host. - Other cold cases, after arm (`C2G-G2*`, `C2G-G8*`): request 3 s after load AR 5.95 / 6.63 s (before 8.81 s; all three REJECT); request 8 s after load AR 7.37 -> 6.96 s, MTP 7.00 -> 6.87 s; cold 16k as the first request 16.92 s vs llama 19.82 ; 21.52 s (1.17x ; 1.27x faster). - GATES held: G1 bar 8.0 s met by 0.95-1.02 s; wired back to 6.6-7.8 GiB after exit on every row; load 2.81-3.56 s inside the before range. ### #8 + #7: one interleaved A/B (`PLEHC-*`, before `313430e52` addon, after `52611c9d2` addon, loadcheck-OK rows only) | Mode | Metric | before mean (n) | after mean (n) | after - before | before range | after range | |---|---|---|---|---|---|---| | AR | 16k TTFT s | 18.09 (3) | 17.28 (2) | -0.82 | 17.50-18.98 | 17.08-17.47 | | AR | 16k prefill tok/s | 1,037.8 (3) | 1,085.7 (2) | +47.9 | 988.3-1,071.8 | 1,073.7-1,097.7 | | AR | warm 6k TTFT s | 4.97 (3) | 4.57 (2) | -0.40 | 4.68-5.18 | 4.53-4.61 | | AR | decode tok/s (mean req0-2) | 49.17 (3) | 49.39 (2) | +0.22 (overlap) | 48.96-49.54 | 49.05-49.73 | | MTP-2 | 16k TTFT s | 17.81 (2) | 17.44 (2) | -0.38 | 17.68-17.95 | 17.40-17.47 | | MTP-2 | 16k prefill tok/s | 1,052.9 (2) | 1,075.5 (2) | +22.6 | 1,045.1-1,060.7 | 1,073.3-1,077.6 | | MTP-2 | warm 6k TTFT s | 4.86 (2) | 4.60 (2) | -0.26 | 4.71-5.00 | 4.58-4.63 | | MTP-2 | decode tok/s (mean req0-2) | 70.65 (2) | 71.51 (2) | +0.86 | 70.38-70.93 | 71.44-71.58 | | MTP-2 | ms per cycle | 38.15 (2) | 37.71 (2) | -0.45 | 38.00-38.30 | 37.67-37.75 | - The AR 16k mean includes a slow before row (18.98 s); the last interleaved pair is -0.41 s. Per PLE window that is -19.7 ms (MTP) / -21.7 ms (AR) over 19 windows. - At the rebased head (`C2INT-after-off-1`, loadcheck OK): AR 16k TTFT 17.30 s, 16k prefill 1,083.8 tok/s, decode 48.24 tok/s, all within 2.3 % of the better parent. The two MTP rows at the head are REJECT (foreign compiles): 16k TTFT 18.14 / 19.15 s, decode 67.45 / 71.31 tok/s; not counted. - The decode tok/s here is the mean of each request's decode rate, not the steady rate of the Stage II table. ### P5-X: slot path == mapped path bits | Commit | What | |---|---| | `8cfc05371` test | `slot_groups_match_the_whole_window_bit_for_bit`: slot groups on capacity-row banks vs the whole 512 bank, bf16 value for value. T11 asserts tripped == plain == reference. | | `e98d4c733` fix | `ExpertKernel::for_window` picks the kernel class once per window; every slot group uses it. Hosts keep shape guards and a 1..=65536 row range. | | `0df94ece6` fix | `route_sort` takes 1..=65536 rows (was 256..), so a Tiles group of any size runs `prefill_indirect`. | Root cause: a slot run splits a window's experts into groups of `capacity` (454, 461, ...). The kernel class was chosen per group from its rows and the bank's rows, so a remainder group under 4 rows per slot fell from NAX tiles to QMV (gemv / gather_qmv). QMV sums K over 32 lanes with `simd_sum`; NAX accumulates K in BK steps in `matmul2d`; the bits differ. The mapped path runs one indirect call over all 512 experts. The remainder set follows the slot count, so the slot text did too. ``` ExpertKernel::for_window(rows, 512) // rows = window tokens x 10; 512 = model experts, not bank rows 256 <= rows <= 65536 && rows / 512 >= 4 -> Tiles NAX prefill_indirect, every group rows > 80 -> Gather sorted rows, gather_qmv (right_sorted = false) else -> Rows expert_rows gemv ``` Mapped windows keep their class (<= 80 Rows, 81-2047 Gather, >= 2048 Tiles before and after). | Check | Result | |---|---| | `slot_groups_match_the_whole_window_bit_for_bit`, 21 splits (windows 1024 / 2000 / 200 / 75 / 20 tokens; capacities 454, 461 and one per remainder band) | 13 differ before the fix, 0 after | | Whole-bank FNV digests, old tree vs new tree | unchanged: `61699f30731fef84`, `945858c1ffd5b137`, `42e2d760d60b10cd`, `dcf1e56baefe4fb0`, `de18448f7e14176a` | | D3 cold 6k / 16k, mapped 512 | 256 / 256, max_ulp 0 | | T11 6k | tripped == plain == reference `[22916, 310, 635, ...]` at slots 427 / 420 / 277 | | T10 6k | 221 arrays byte-equal | | Scoped `models::qwen4_exp` | 242 pass / 0 fail / 11 ignored | | `cargo clippy -p mlx-core --all-targets`, `cargo fmt --check` | clean | - Real-model rows ran on the pre-rebase trees (`a95cb2492`; T11 at 277 slots on `81ea6f965`). The rebase is 3 x `=` in range-diff with an empty qwen4 / mlx-sys diff. D3 6k, the unit gates and the digests were rerun on the rebased P5-X head and on every later head. - Timing: interleaved T11, old vs new binary on the same loaded host, plain slot prefill new / old = 1.23x then 0.91x: NOISE. No mapped window changed kernel class. No further slot-mode timing (P5-Y stopped, see gaps). - Codex Stage III finding (slot path bits): closed by `e98d4c733` + `0df94ece6`; the Codex thread is resolved with the commits. ### Compile cache and CI fixes (`142cff3e0`, `734430a6f`) - **Codex pass 2 (medium): compile-cache growth.** `qwen4_indirect_prefill` ran through `mlx::core::compile`, which keeps one trace per input shape and never evicts. Each trace holds its own copy of the two kernel sources, ~309 KB (estimated from the measured 148,980 B header). P5-X sends the slot remainder groups to this path too, so one 32k prompt at 454 slots makes 542 keys instead of 271 (Codex's harness, reproduced), and 814 after 4 prompts. The wrapper and the base growth come from main (#154); the doubling is ours. - **Fix `142cff3e0`:** the indirect expert prefill runs eagerly. Its graph is two custom kernels with nothing to fuse, so the bits are the same by construction (an earlier eager arm was also exact at D3 6k / 16k). 1 file, +3 / -7. Unit digests unchanged, scoped 242 / 0 / 11, D3 6k 256 / 256, max_ulp 0. The Codex bot found nothing on the fixed head. - Out of scope: the dense prefill wrapper on main (`qwen4_dense_prefill_dispatch`) has the same growth, one key per distinct window length. Left for a separate item. - **CI `734430a6f`:** five MTP draft-bank tests failed on the 7 GB macos-26-arm64 runner. The fixture load asks for the fixed 4 GiB first-request working reserve (`WORKING_BYTES`), not for its few-KB bank; the runner had 2.7 GiB free. Production degrades as designed (warn and load on). Test-only fix: fixture helpers pass an always-yes admission; the decline calls pass one that panics, so the decline still comes before any host admission. On a simulated 7 GB host: old tests 0 / 5 with the CI message, new 5 / 5, scoped 242 / 0 / 11. CI green on `e3503adc0` (this commit before the final rebase). ### Cleanup (`299b4defb`, `071588e44`, `12f7fdb74`, `3c0d8a5a1`) - The four decoder A/B switches (`batch_prefill`, `window_carry`, `async_prefill`, `batch_rotary`) are gone with their losing arms. The prefill oracles now compare against `step()`; the rotary test is bit-exact against per-row `rope`. - `fold_rows` is gone, with the research-only tests (row-batched GPU time, forced-stream acceptance, two fold-cost timings). - D3 is cut to the greedy expected-argmax gate: `real_model_greedy_argmax_matches_expected`. Env vars renamed: `D3_*` / `T10_CASE` -> `QWEN4_EXP_REAL_STEPS` / `_CASES` / `_EXPECTED` / `_OUT` (documented in `docs/qwen38-flash-next.md`). - Phase labels, mutation codes, dates and shas are stripped from comments. Docs corrected: 73 GiB pack, 32 readers, cache paths. - Gates (on `4455353de`, this stack before the final rebase; the rebase diff is the openai bump only): scoped 239 / 0 / 9. The delta from 242 / 0 / 11: 2 passing tests removed, 1 moved to ignored (release microbenchmark), 3 ignored research tests removed. Clippy, fmt and typecheck clean; unit digests unchanged; D3 6k `EXPECTED OK: 256 positions`, mapped 512. ## Phase 4 Stage II + Phase 5 L2 + v3 pack policy (`e00bb6e3f`, `f6a35ca4c`, `9f52a1c3d`, `29bff1850`, `67fe0f15c`, `32e7a3faa`, `5a7c5fdea`, `c003150d0`) | Step | Change | |---|---| | M3 `e00bb6e3f` | A draft pass submits the attention hyper-connection rows and their injection gate as soon as they exist, so the GPU starts while the host builds the rest of the pass. Same graph and kernels. Propose wall at 6k 4.86-5.17 -> 4.75-4.80 ms. | | C5 `f6a35ca4c` | The draft K/V history is a capacity buffer written in place instead of six full-history concatenations per MTP cycle (12 MiB each at 6k). Cache clones share the buffer and keep their own row counts. Draft GPU per cycle 6k 4.21 -> 4.04 ms, 16k 4.54 -> 4.14 ms. | | L2 `9f52a1c3d` | Stream pool: eight workers read the whole pack with 4 MiB buffered preads in layer order (12.3 GiB/s over the evicted pack; the old depth-3 walker did 9.3), kernel read-ahead off, one `mincore` per file to skip resident chunks. The stream starts at load after the dense banks and at any turn over a pack that is not fully resident; it yields to the model's row reads and stops within one chunk on the switch to slots or on unload. Cold 6k TTFT -1.6..-1.9 s; a request 8 s after load reaches 7.4 s. | | L3 `29bff1850` | The draft head normalizes the target hidden per hyper-connection stream (as the target's own `hc_norm` and llama.cpp's MTP graph do) instead of one RMS over the joined streams (mlx-vlm's drafter). Teacher-forced on llama.cpp's committed text it reproduces llama's per-position acceptance (0.914, 0.817); f32 head / router, f16 draft K/V and a zero first row moved nothing. Draft side only: verify path and committed text unchanged. | | B1 `67fe0f15c` | Test only: fixture GGUF loads in unit tests resolve to a fresh temp root instead of `~/Library/Caches/mlx-node/qwen4-packed`, so `cargo test` no longer sweeps the developer's real cache; a regression test with a fake HOME proves it. Codex: approve. | | v3 policy `32e7a3faa` `5a7c5fdea` | Pack identity no longer includes `st_dev`, so a volume renumber keeps the 73 GiB pack. The manifest records the canonical path and the mount point of every source file. A pack is removed only on proof: its source is present with another fingerprint, or a source file is gone from a volume that is mounted. An unmounted or unreadable source keeps the pack. A real-model load after the change reused all 144 files and matched the shas. | | manifest fix `c003150d0` | Codex S2 (medium): a truncated `.manifest` read as a fingerprint change and deleted a healthy pack. The manifest ends with an `end=<hex file count>` record and is written to `.manifest.tmp` then renamed; a manifest without a valid end record is incomplete and keeps its pack; the load heals the opened pack's manifest and no other. 4 mutations red, module tests 223/0, real-model load reused the pack and healed its manifest with the shas unchanged. | ## Phase 4 Stage I: MTP-2 cycle (`fffd47666`, `98861f447`, `f765187d9`) Warm 6k MTP-2 cycle 50.6 -> 37.8 ms in the quiet A/B (-25 %); traced cycle 33.1 ms = draft 2.5 + 2.3 + verify 28.0 + accept/commit 0.3. | Step | Change | |---|---| | A1 `98861f447` | On the mapped pack the verify pass keeps its routes on the device: one route tape joined into the final eval and one readback replace 48 per-layer GPU-to-host waits; the tripwire is told after the route commit. Slot mode keeps the host routes. Real-model test: 32 three-row verifies match the AR step bit for bit. | | M1 `f765187d9` | The MTP gate_up draft bank keeps its scales and biases as f32 copies, so `gather_qmm` no longer casts 2 x 52.4 M values on every draft; the f16 layout stays where the f32 one does not fit the mapped charge or the slot allowance. | | v2 retire `fffd47666` | Legacy `.mlx-qwen4-packed-v2-<64 lowercase hex>` directories are removed at load once idle for 1 h and their `budget` lock is free. | ## What Phase 3 adds | Step | Change | |---|---| | M5 | Mapped-or-slots chosen at load from live memory (wired + compressor + anonymous), byte budget exported; thrash tripwire (SSD reads > 2x mapped bytes, or 8 slow passes); decoded-row LRU byte-bounded; no "free memory" advice, no override flag | | M6 | A tripped turn leaves the mapped path at that pass and finishes on slots (13 min -> 50 s under a 40 GiB hog); gate maps while live non-reclaimable <= 42.85 GiB; slot fallback sized after the compressed + swapped debt | | D3 | Same-process teacher-forced A/B of every fusion/schedule flag: none beats the noise band; decode is weight-stream bound; 21 flags and their kernels deleted | | S3-S6 | MTP verify runs the R draft rows layer by layer with shared weight reads; Q8 g32 draft expert bank for the MTP head; draft prefill merged into the first draft pass; 16k MTP admission counts only KV pages | | K16 | Prefill QSA kernel serves two GQA heads per K/V read (-14 %, bit-identical) | | INT2 | Integration; fixes the S3 regression that sent prefill through the row-exact R <= 4 wrappers (1.58 M single-row GEMV dispatches per 6k prompt -> 9.5 k) | | C1 | Flag purge: 89 `MLX_QWEN4_*` names, the runtime flag module, the residency selection knobs and the v2 per-expert chunk cache are gone; one code path | | Review fixes | Slot sizing keeps room for MTP draft banks (`163a0f9c1`, `6698e47b6`) | ## How to verify Cleanup head = `4455353de` (`3c0d8a5a1` before the final rebase). | Check | Command or test | Result at | |---|---|---| | Scoped unit tests | `cargo test -p mlx-core --lib models::qwen4_exp` | 248 run / 239 pass / 0 fail / 9 ignored (cleanup head) | | | `cargo test -p mlx-core --lib engine::scheduler` / `engine::hybrid_scheduler` / `transformer::paged_kv_cache_adapter` | 26/26, 51/51, 174 run / 170 pass / 4 ignored (`a706d8058`) | | Bitwise tests (`--exact`) | `ple_projection_row_kernel_matches_gather_and_single_rows_bit_for_bit`, `ple_window_runs_four_rows_per_row_kernel_call_bit_for_bit`, `mixer_act_split_keeps_the_one_simdgroup_chain_bit_for_bit`, `row_batched_decode_kernels_match_single_row_calls_bit_for_bit`, `a_group_of_windows_matches_one_window_at_a_time_bit_for_bit` | each 1 passed (P5-X); in the scoped run on every later head | | Slot == mapped (`--exact`) | `slot_groups_match_the_whole_window_bit_for_bit` | 21 / 21 splits equal (13 differed before the fix); 5 whole-bank digests unchanged (P5-X, P5-Z, cleanup head) | | Kernel class rule (`--exact`) | `expert_kernel_follows_the_window_not_the_bank` | ok (P5-X, P5-Z, cleanup head) | | Lint | `cargo clippy -p mlx-core --all-targets`, `cargo fmt --check`, `yarn typecheck`, `vp fmt --check docs/qwen38-flash-next.md` | clean (cleanup head) | | Real model, exactness (ignored tests; `QWEN4_EXP_REAL_MODEL`, `QWEN4_EXP_REAL_INPUTS`, `QWEN4_EXP_REAL_CASES`, `QWEN4_EXP_REAL_EXPECTED`; page cache evicted first) | `real_model_greedy_argmax_matches_expected` | cold 6k `EXPECTED OK: 256 positions`, mapped 512 (cleanup head, P5-Z); cold 6k / 16k as one group 256 / 256, max_ulp 0 (`a706d8058`, P5-X) | | Real model, group vs windows | `real_model_group_matches_window_at_a_time_on_a_cold_pack` | 221 arrays byte-equal (`a706d8058`, P5-X) | | Real model, trip | `real_model_forced_trip_between_sweeps_switches_after_the_frontier_eval` | asserts tripped == plain == reference, plus commit -> frontier -> trip -> switch order, store off the mapped path, stream gone, fallback index 0, history == prompt; passes at slots 427 / 420 / 277 (P5-X trees) | | Real model, text | R0 benchmark, cold 6k + 16k + warm 6k, 256 tokens, AR and MTP-2 | shas `bfb8e8bb3bd0c768` / `6a63463a98644df6` on every request, AR == MTP, MTP 95 / 189 / 160 (`a706d8058`) | | FINAL5 measurement | `FINAL5/driver.sh` + `FINAL5/trace.sh` (research dir), R0 benchmark, page cache evicted per run | 10/10 timing rows + 1 trace row; the same 6k / 16k sha on all 30 requests (`rows-all.txt`), AR == MTP; mapped/512 on every row; wired-drop gate 10/10 (largest fall 4.3 GiB); MTP c/d/a 95/189/160 on every MTP request (`a706d8058`) | ## Known gaps and open items - **FINAL5 still loaded-host.** 0 of 10 rows had an idle GPU (foreign GPU mean 31.4-44.5 %, one row 10.6 %). Interleaved A/B deltas hold; absolute rows carry the caveat. The trace row is above (op trace). - **Decode below Stage II.** AR decode 7-9 % and MTP-2 16k decode 7.1 % below Stage II on every Stage III loaded-host row since `313430e52`. Cause not separated: the L2c bank in the AR arm vs foreign GPU load. The interleaved Stage II vs Stage III A/B (P5-Y) was stopped at the user's request after 5 rows, with no analysis. - **Cold 6k per request, AR, behind.** 6.91-6.93 s vs llama 6.01 ; 6.38 s = 0.87x ; 0.92x (FINAL5, loaded host). MTP-2 is at parity (1.01x ; 0.94x). From load start: AR 3.67x ; 3.50x, MTP-2 3.98x ; 3.62x faster. - **#7 on AR.** The AR gain (target -0.5 ms per step) is below the noise; only the MTP-2 decode delta separates. - **c2 follow-ups, accepted and not coded:** SF2 (the row queue's `take()` scans under the lock; late rows 995-1,698 per cold 6k request; trace the wait first), SF3 (no cadence trace; the 3-layer submit cadence stays), SF4 after-trip half (the 1024-row window is not re-sized after a switch; every growing byte is still admitted; tight host untested), SF5 native-state half (a failed group's lazy tail costs the next request GPU time, not bits). - **Slot-mode prefill timing.** Not measured on a quiet host with the window kernel class rule. The only pair (T11, loaded host) is NOISE. - **Dense prefill compile cache (out of scope).** The dense prefill wrapper on main (`qwen4_dense_prefill_dispatch`) keeps one compile trace per distinct window length, the same growth as the indirect one fixed here. Left for a separate item. - **MLX fork item.** The Synchronizer's `retain_inputs` keeps an eval's output buffers until its completion handler runs, so `append_draft_kv` can copy instead of writing in place. It is a copy, never a wrong value. - **First launch after a kernel change** pays in-request Metal compiles once (AR 1.07 s + 0.07 s, MTP 24 compiles in the first process per mode); 0 from the second process on. - **MTP 16k prefill spread.** Slow MTP 16k rows trace to a host event: 40-55 GiB of wired memory released and re-taken within 1-3 s mid-prefill, GPU to ~18 %. FINAL5's wired-drop gate passed 10/10 (largest fall 4.3 GiB); no host-event row this time. - **Busy posture.** Above ~43 GiB of live non-reclaimable memory from other apps the load picks the slot path, which is ~5x slower (11-15 tok/s MTP-2 decode); it completes, it does not crash or thrash. c2 hog row (40 GiB hog, 16k, MTP-2): slots 225, 64 / 64 tokens. - Pre-existing: kquant golden gate fails on the g17s/g17d/g17g NAX routes at the base pin (identical bits on the source and prebuilt builds). ## Submodule `crates/mlx-sys/mlx` -> fork branch `fn-d1` (`e68b9ba77`: two patches on `bcad39304`). `mlx-prebuilt.json` pins the matching prebuilt release `mlx-prebuilt-e68b9ba778fc-6d601cad`; golden gates are digest-identical between the source and prebuilt builds. Stage III does not move the pin; #7's kernel is a new `crates/mlx-sys/src/metal/qwen4/mixer_act_decode.metal.inc`. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Fable 5.1 <[email protected]>
…untimes (#295) ## Summary TypeScript harness and skill for the mlx-node vs llama.cpp benchmarks in #142 (`scripts/perf-tracker/`, `.claude/skills/perf-tracker/SKILL.md`). It always compares the latest mlx-node `origin/main` with the newest llama.cpp prebuilt `bNNNNN` release, and runs speculative decoding in both runtimes. ``` worktree at origin/main ─► build ─► preflight ─► prewarm ─► matrix ─► report │ │ HEAD contains origin/main ──┤ ▼ newest llama.cpp downloaded ┘ compare.md + chart.svg + samples.csv + summary.json ``` ## Suites | Suite | Workload | mlx-node | llama.cpp | |---|---|---|---| | `qwen38` (Qwen3.8 27B UD-Q4_K_XL) | 6,219 / 18,754 / 32,488 tokens, 512 out | DFlash2, 7 drafts, BF16 KV | `--spec-type draft-dflash --spec-draft-n-max 7`, Q4_K_M draft | | `gemma4` (Gemma 4 12B QAT Q4_0) | 7,733 / 40,528 / 66,904 tokens, 256 out | DSpark block 7 (DeepSpec draft) | assistant MTP `--spec-type draft-mtp`, depth 3 | | `flash-next` (Qwen3.8 Flash Next UD-Q4_K_XL) | 6,219 / 18,754 / 32,488 tokens, 256 out | native MTP depth 2, default SSD streaming | `--spec-type draft-mtp`, depth 2, unsloth MTP Q8_0 | - Gemma4 uses different methods: llama.cpp b11717 refuses the DeepSpec draft's `final_logit_softcapping`, and DSpark adds the Markov bias after the softcap, so a softcap-free GGUF would draft other tokens. - Every suite runs llama-server with `-ctxcp 0 -cram 0`, greedy, `cache_prompt=false`, pinned token IDs. - Draft files are pinned by size and SHA-256, checked in preflight and again after the run. - Each sample must prove speculation ran at the protocol depth: `d·cycles − d(d−1)/2 ≤ drafted ≤ d·cycles`, counters present and finite, accepted ≤ drafted. - New fixtures `qwen38-oxc-review-v2`, `gemma4-oxc-review-v2`. The v1 baselines ran without speculation, so they are removed; the first v2 entry has no before value. - `flash-next/mtp-aux.ts` builds the mlx-node MTP folder (31 `mtp.*` tensors from `Qwen/Qwen3.8-Flash-Next@de4b8e4d`) on the internal SSD. ## Status - Type check and `vp lint --type-aware --type-check scripts/perf-tracker` pass. - Codex adversarial review: 2 findings (depth gate, fail-open counters), both fixed in `d1fa18157`; 24 bad inputs refused. - Smoke tests, one request each (not benchmark numbers): | Cell | Prefill tok/s | Decode tok/s | Acceptance | |---|---:|---:|---:| | qwen38 6k mlx-node (64 tokens) | 774.5 | 17.81 | 32.6% | | qwen38 6k llama.cpp (64 tokens) | 616.5 | 20.85 | 14.1% | | gemma4 7.7k mlx-node | 1,232.2 | 36.44 | 32.0% | | gemma4 7.7k llama.cpp | 1,552.8 | 79.28 | 56.2% | - No full suite has run with this protocol yet. Flash Next with speculation has not run end to end. - Flash Next prefill depends on #294 (O(n²) QSA prefill and per-shape shader builds). 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Summary
Qwen3.8 Flash Next (
qwen4_exp) prefill was O(n²) after the indexer budget (2,048 tokens), and it built new Metal kernels for every row, step and expert group. This PR removes both problems.Commits
600bb7a78qwen4_gather_window: N, FRESH, POOL andbaseat run time (only H, D, BS stay template args)de702e0bf[nb, indexer_head_dim]tensor per layer781a5f397MLX_QWEN4_BATCHED_QSA=0rolls backe7c295cacindexer_compress_ratio > 33(the kernel covers 32 tail tokens; found by Codex review)40f293d52Results (M5 Max 128 GB, default auto policy = SSD streaming, busy desktop)
40f293d52)40f293d52)llama.cpp b11717 on the same machine: ~1,066 tok/s prefill, ~45 tok/s decode at 6k. The gap that remains is not in this PR:
decoder.rs:1323). The device-route fast path covers ~18% of tokens.Tests
cargo test -p mlx-core qwen4: 165 passed, 0 failed.gather_window_runtime_shapes_match_selected, five batched-QSA tests,batched_qsa_falls_back_past_kernel_tail_width,expert_prefill_runtime_sizes_match_quantized_matmul.completeoff by one, tail dropped, ratio gate removed, and 8 bound mutations in40f293d52(R, S, NB, TOKENS, tiles, dense, expert_prefill).cargo clippy -p mlx-core --all-targets,cargo fmt,yarn build:native.Not done
40f293d52yet.cargo test -p mlx-coreandvp testnot run.🤖 Generated with Claude Code