Repository navigation
feat(kv-int8): paged prefill attends in place on the pool - #368
Conversation
|
Important Review skippedAuto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
|
Codex Review Summary: ✅ CompletedThis 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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 33f5cd80cb
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
8823b28 to
b67a675
Compare
7c8b818 to
96562de
Compare
b67a675 to
1d41f93
Compare
Qwen3.5 dense and MoE paged prefill chunks (fresh, first or cache hit) and MTP / DFlash2 verify blocks store their rows into the pool first, then attend in place over the pool pages through a new split + reduce kernel (paged_prefill_attention.metal) on int8 and bf16 pages, like Splash's chunked prefill: 8-row tiles with the query group fused, tile parts for a group of 16, 32-token pages, Splash 1.6 history splits and an in-order reduce. The chunk's own rows are read back as stored. The gather + MLX SDPA cache-hit route, the first-chunk in-flight SDPA, their pool estimators and mlx_segmented_sdpa_forward are gone. The memory plan charges Splash's prefill attention tensors for one lane: the kernel's workspace bound, query staging, output and the chunk's K / V rows, with no history term. Pools zero-fill on create and grow. A paged Qwen3.5 load needs a kernel geometry and runs on every GPU family (Splash's Apple9 floor is engine-wide, not this kernel's); M1 and M2 take the Apple9 pages-per-split row. A pipeline that does not build fails loudly with the kernel and the Apple GPU family named. The kernel test checks every query head. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
96562de to
5cf9535
Compare
Stage S10f of the Splash int8 KV alignment (stack #344). Base: S10 (#368). On Metal, every Qwen3.5 dense and MoE inference turn now runs on the block-paged pool, as in Splash. Splash has one KV store (pages) and no flat full-attention lane, so this PR deletes ours (RULES #10). ``` before (Metal): load ── use_block_paged_cache / MLX_QWEN35_PAGED_OVERRIDE / sym8 pin / CLEF ├─ pool ──► paged AR, MTP, DFlash2, images └─ no pool ──► flat AR, flat MTP (eager verify), flat int8 KVCache generate(), calibration, MoE training generation ──► flat caches (int8 at head 256) memory plan: pool lane + FlatInput lane after (Metal): load ── a paged kernel for the layout? ── yes ──► pool: AR, MTP, DFlash2, images, eval, calibration └─ no ──► the load fails ("no paged-attention kernel for layout") off Metal (CUDA preview): no pool, bf16 autoregressive turns only, int8 refused training generation: bf16 flat K/V (dense and MoE) memory plan: pool lane only ``` ## Changes - Every Apple GPU family gets the pool. A layout with no paged-attention kernel fails the load (Splash: "no paged-attention kernel for layout"). Shipped layouts fit: 0.8B (8/2, D256), 27B (24/4, D256), 35B-A3B (16/2, D256). - Off Metal the load has no pool. It serves bf16 autoregressive turns. Speculative plans need the pool, so MTP falls back to AR there. int8 and images are refused. - The flat AR hooks refuse a Metal load ("the flat KV lane serves only loads off Metal"). - Paged Q/K/V are cast to the pool's io dtype. sym8, f16 and f32 checkpoints now write the pool. - Images: both media plans admit only what the load has (encoder, processor, pool). A no-pool load refuses images at admission, before render. - Eval and calibration share one prefill helper that runs on the pool. Calibration amax is taken on the pool path. - The int8 default applies only where the pool has kernels. - MoE training generation uses bf16 K/V (it used int8 flat K/V). - `use_block_paged_cache` is gone from both configs. An old `false` in a saved config is an unknown key and is ignored. - The server host no longer clones qwen3_5 configs to force a paging key. `pagedModelTypes` defaults to none. - The layer-cache full-attention snapshot is a placeholder. Replay skips the full-attention shell. - Docs, README, CLI help and CI lists updated. ## Deleted - Flat turn cores (`flat_turn.rs`, dense and MoE), the MoE flat `paged_turn.rs` router, `run_speculative_turn` and the desync overrides. - Flat MTP arms (owner `None`), `eager_verify_step`, the tape forward, `chunked_prefill_with_hidden`. - `generate()` / `generate_sync` and their generation types (dense and MoE), with `qwen3_5-generation.test.ts`. - The int8 flat `KVCache` format, `forward_int8_cached`, `segmented_sdpa_int8` (+ `_with_route`), `segmented_int8_covers`, the int8 schedule variants, the C forced-route entry. - `use_block_paged_cache`, `resolve_qwen35_paged_default`, `MLX_QWEN35_PAGED_OVERRIDE`, the sym8 pins. - Memory plan `FlatInput`, `LaneKv::Flat`, copy bytes, `MemoryPlan.flat`, `flat_lane_transient`. - `QWEN35_PAGED_MODEL_TYPES`, `DEFAULT_PAGED_MODEL_TYPES`. - Tests of deleted code: 4 paged-vs-flat parity binaries (dense, MoE, text, VLM), `kv_int8_tests.rs`, two `stream_progress_tests.rs`, flat cases in `layer_cache` and planner tests. - 104 files, +2,152 / −14,054. ## Tests - New: `metal_load_has_no_flat_lane` (dense + MoE), `geometry_without_a_kernel_fails_the_load`, `off_metal_load_serves_bf16_autoregressive_turns`, `mixed_paged_operands_take_the_pool_dtype`, `f32_checkpoint_chats_on_the_pool`, `sym8_estimate_plans_the_pool`, `calibration_reads_the_pool`, `image_turn_without_a_pool_is_refused_at_admission`, `unset_kv_format_defaults_to_int8_only_where_the_pool_has_kernels`. - Named mutations, each red when on and green when off (`MUTATIONS.md`): N1 pool backend off, N2 flat lane allowed on Metal, N4 geometry error falls back to no pool, N5 MTP plan without a pool, N6 no-pool int8 refusal dropped, N7 mixed Q/K/V uncast, N8 estimate re-pins sym8, N9 calibration through the flat hook, N11 images admitted without a pool, N12 int8 default ignores the pool gate, F1 / D1 uniform f32 Q/K/V uncast, E1 amax collector disarmed before the pool prefill. - Follow-up (local Codex): a calibration row shorter than one block on an f32 / f16 dense checkpoint reached a bf16-only `debug_assert` in `project_last_token_logits_with_full_hidden`. The assert now checks that `final_norm` keeps the residual's dtype. Test `f32_checkpoint_calibrates_a_short_row_on_the_pool`, mutation CA2 (bf16-only assert back) red. `models::qwen3_5` 418, `models::qwen3_5_moe` 133, `calibration` 29 passed; fmt and clippy clean. - Final gate on this head: - `cargo fmt --check`, `cargo clippy --workspace --all-targets -D warnings`: clean. - `cargo test -p mlx-paged-attn`: 17 binaries, 332 passed, 0 failed, 13 ignored. - mlx-core `--lib` (`RUST_TEST_THREADS=1`): 4,730 passed, 0 failed, 220 ignored. - `qwen3_5_moe_mtp_synthetic`: 1 passed, not skipped. - `yarn build:native` (`index.d.cts` unchanged), `tsc -b --force`: clean. - TS: `grpo-qwen35`, `qwen3_5-config`, `paged-config-override`, `inference-host`: 4 files, 93 passed. `vp lint --type-aware --type-check` and `vp fmt --check` on the 10 touched TS files: clean. - `git grep MLX_MUT`: 0. ## Gaps - A CLEF decision load builds no pool (as before) and `decide_clef` runs the flat forward. It serves decisions, not chat; a chat turn on it is refused on Metal. - Off Metal the window is no longer bounded by a memory plan. It falls back to the trained window or `--max-context`. - GRPO / SFT rollout generation keeps a flat bf16 full-attention forward. Splash has no training. - The int8 segmented-SDPA C++ kernels are reached only from `paged_int8_read.rs`, as a reference. - `shared_command_dispatch_orders_family_operations_stats_and_reset` no longer checks the effect of its first command (its `history_len > 0` holds from setup). - One old plan doc (`docs/superpowers/plans/2026-06-16-...`) still names `MLX_QWEN35_PAGED_OVERRIDE` and `MLX_QWEN35_FORCE_EAGER`. ## Not in this PR (live, not run) - L1 27B dense on the pool: AR, DFlash2, MTP, 2-turn chat each (paged, int8, cached tokens, MTP cycles). - L2 35B-A3B MoE MTP on the pool. - L3 image turn on the pool (qwen3.5-0.8b). - L4 GRPO smoke on a tiny qwen3_5, dense + MoE, from the live build. - L5 a `use_block_paged_cache: false` view and `MLX_QWEN35_PAGED_OVERRIDE=0` both load on the pool. - L6 sym8 checkpoint on the pool. - L7 calibration on the pool (`calibrate.test.ts`). - L8 f16 checkpoint on the pool (bf16 pool, no dtype error). - L9 M1 / M2: no such Mac here. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
…out MPP prefills through a portable path (#377) ## Why main CI run 43254067201 (61e72da, after #344 and #348) failed three jobs. | Job | Cause | CI error | |---|---|---| | Clippy, cargo test (mlx-core lib) | #348's `tiny_moe_config` in `utils/functional.rs` builds `Qwen3_5MoeConfig` with two fields #344 removed and misses `rope_scaling` | `error[E0560]: struct Qwen3_5MoeConfig has no field named paged_cache_initial_memory_mb` (functional.rs:2032), same for `use_block_paged_cache` (2034) | | e2e qwen3_5-dense | Since #344 the memory plan refuses an explicit pool above its own. The test pins 512 MiB; on the macos-26 runner the plan allows 181 MiB | `Qwen3.5: paged_cache_memory_mb 512 exceeds the 181 MiB of KV pool the model and this Mac's memory allow; omit it or set at most 181` (p2_paged_thinking_honors_enable) | Cargo stops at the first failing test binary, so the rest of the leg never ran. Two more tests in it had the same problem: | Test | Explicit pool | Result on the runner | |---|---|---| | `p2_paged_thinking_honors_enable` | 512 MiB | failed in CI | | `qwen3_5_session` | 512 MiB | would fail (never ran) | | `qwen3_5_cold_tier_parity` (harness) | 1024 MiB | would fail (never ran) | | `qwen3_5_delta_chat`, `qwen3_5_concurrent_batched_parity` | none | pass | | lib_tests (2 tiny synthetic models, 256 MiB) | inside the plan | pass | ## Fix - `functional.rs`: drop `paged_cache_initial_memory_mb` and `use_block_paged_cache`, add `rope_scaling: None`. `persist_paged_cache` still exists on main and stays. The struct now matches `Qwen3_5MoeConfig` and `tests/common/mod.rs`. - `p2_paged_thinking_honors_enable`, `qwen3_5_session`: stop writing `paged_cache_memory_mb`, so the plan sizes the pool. The 512 was only there to keep the pool small, and the pool now grows by extents. `paged_block_size = 16` stays because the session test's prefix assertion depends on it. - Cold-tier harness: `pool_memory_mb` becomes `Option<u32>`. The default stays `Some(256)`, and the new `with_planned_pool()` leaves the key out. The qwen3_5 gate uses it: the 181 MiB planned pool holds about 15k BF16 tokens, and the gate needs two prompts of about 1,260 tokens each. Measured: `evictions=0`. Other legs, checked: | Leg / test | Explicit pool | Decision | |---|---|---| | qwen3: `qwen3_paged_vs_flat_parity`, `qwen3_cold_tier_parity`, `qwen3-paged-*.test.ts` | 256 | Unchanged. The leg passed on the same runner | | lfm2: `lfm2_paged_vs_flat_parity`, `lfm2_cold_tier_parity` | 256 | Unchanged. The leg passed on the same runner | | gemma4 (PR opt-in): `gemma4_grouped_cold_tier_parity` | 1024 | Unchanged. It needs a full-context lane, and it passes under the runner simulation below | | nemotron_h: `*_paged_vs_flat_parity`, `*_mtp_midcycle_state` | 512 | Unchanged. The leg is skipped on every event (needs a self-hosted runner) | ## Local repro Model: `yarn mlx download model -m Qwen/Qwen3.5-0.8B` + `yarn mlx convert -d bf16 -m qwen3_5`, as in ci.yml. The runner's working set is simulated with an uncommitted, env-switched override of `mlx_max_recommended_working_set_size` and the `recommendedMaxWorkingSetSize` read in `mlx_paged_dispatch.cpp`. A working set of 5,010,305,024 B reproduces the CI message exactly (`... exceeds the 181 MiB ...`). The whole leg ran with the CI env (`CI=true`, `MLX_METALLIB_STRICT=1`, `MLX_TEST_REQUIRE_METAL=1` for lib_tests, `QWEN35_STAGE2_MODEL_PATH` + `MLX_SCHED_MAX_NUM_SEQS=2` for stage2, `--test-threads=1`), with `--no-fail-fast`. | Run | p2 | session | cold tier | delta_chat | lib_tests | stage2 | |---|---|---|---|---|---|---| | simulated runner, before | FAIL (512 > 181) | FAIL (512 > 181) | FAIL (1024 > 181) | 6/6 | 2/2 | 1/1 | | simulated runner, after | ok | ok | ok (hits=42, corruptions=0, evictions=0) | 6/6 | 2/2 | 1/1 | | native M5 Max, after (simulation removed) | ok | ok | ok | 6/6 | 2/2 | 1/1 | ## Gates | Gate | Result | |---|---| | `cargo fmt --all -- --check` | pass | | `cargo clippy --workspace --all-targets -- -D warnings` | pass | | `cargo test -p mlx-core --lib` | 4823 passed, 0 failed, 221 ignored | | `cargo test --workspace --test '*' --no-fail-fast` (`MLX_TEST_REQUIRE_METAL=1`) | 111 binaries, 323 passed, 0 failed | No TS changes. ## Portable prefill path for GPUs that cannot build the MPP kernel (34d5b06) **Problem.** Since S10 (#368) and S10f (#369), every Qwen3.5 dense / MoE prefill chunk and every MTP / DFlash2 verify block attends only through the MPP tensor-op kernel `paged_prefill_attention_{bf16,q8}_split_g*_d*`. The hosted macOS VM cannot build those pipelines, so the e2e `qwen3_5-dense` leg failed: ``` MLX eval failed in paged_prefill_layer_barrier while materializing 1 arrays: paged prefill attention kernel paged_prefill_attention_q8_split_g4_d256 has no pipeline on no known Apple GPU family ``` **Fallback.** `PagedKVCacheAdapter::paged_prefill_attention` now goes one of two ways: ``` device_prefill_mpp_builds()? (asked once per process, OnceLock) yes -> MPP split + reduce (unchanged) no -> gather_kv_for_prefill_chunk_varlen (vLLM varlen kernel, plain Metal, already in the tree) ``` - **How it is chosen:** the new `mlx_paged_prefill_mpp_builds()` tries to build all 24 MPP pipelines. If any build throws, the answer is false. Linux returns false. The answer is never taken from catching an error on a single call. - **Same input as MPP:** the fallback reads the same stored rows, including int8 values times their scale. - **One warning:** the first time the device answers no, it logs `paged_prefill_portable`. - **Departs from Splash on purpose:** Splash has no such fallback. The code comment names its kernel (`kernels/prefill/paged_attention.metal`, `paged_attention_tile.h`). - **About 40 lines of production code.** It adds no new kernel and restores none of the deleted route. **Tests** | Test | Checks | |---|---| | `portable_prefill_matches_the_tile_kernel` | Fallback and MPP against an f64 reference, within Splash's `checkOutput` bound. Pools: int8 and bf16. Geometry: g4/D128, g8/D256, g16/D256. Cases (committed, rows): (0, 40), (40, 24), (600, 9) (past the 512-token switch), and a 5-row verify. Largest difference between fallback and MPP: 0.25 (values carry ×60 outliers). On the VM it runs the fallback half only. | | `prefill_routes_once_and_to_mpp_where_it_builds` | MPP is launched once per chunk wherever it builds, and the device is asked exactly once per process. | | `portable_prefill_turn_matches_the_tile_turn` | Tiny seeded model, 70-token prompt, 16 greedy steps, bf16 pool (D128) and int8 pool (D256). Logits stay within 0.02 (measured 0.0098 / 0.0078). With a tie screen, 16 of 16 tokens are equal. | | `paged_attention_reads_its_own_rows_back` | Refactored onto the shared reference helper; unchanged. | **Mutations** (one build, runtime switches, removed before the commit) | Id | Mutation | Red test | Failure | |---|---|---|---| | PF1 | Always take the fallback | routes test | `one tile launch per chunk`, left 0, right 2 | | PF2 | Fallback at `committed - 1` | parity test | Int8 8/2 D128 P 40 T 24: worst error 121 × bound | | PF3 | Probe skips the OnceLock | routes test | asked 3 times, expected 1 | All three passed with the switch off. **VM simulation** (uncommitted; removed). It forces the working set to 5,010,305,024 B, makes every MPP pipeline throw the CI error text, and makes `mlx_test_gpu_lacks_apple_family` return true. Each run is the full `qwen3_5-dense` leg as `ci.yml` runs it. | Run | Integration (4 binaries) | lib_tests | stage2 | "has no pipeline" lines | |---|---|---|---|---| | sim, before (bf19716) | 0/1, 0/1, 1/6, 0/1 FAILED | 0/2 FAILED | 0/1 FAILED | 11 (the CI error, reproduced) | | sim, with fallback | 1/1, 1/1, 6/6, 1/1 | 2/2, no `skipping` | 1/1 | 0 | | native M5, sim removed | 1/1, 1/1, 6/6, 1/1 | 2/2, no `skipping` | 1/1 | 0 | **Gates** (logs in `/Volumes/PM9A1/claude-scratchpad/7e002cb3-kv-int8/fallback/`) | Gate | Result | |---|---| | `cargo fmt --all -- --check` | ok (`gate-fmt.log`) | | `cargo clippy --workspace --all-targets -D warnings` | ok (`gate-clippy2.log`) | | `cargo test -p mlx-core --lib` | 4826 passed, 0 failed (`gate-lib.log`) | | `cargo test -p mlx-paged-attn` | 334 passed (`gate-paged-attn.log`) | | `cargo test --workspace --test '*' --no-fail-fast` | 323 passed, 0 failed (`gate-int.log`) | | Live T=0 smoke, qwen3.5-0.8b (MPP), serial + scheduler, chunk 64 | byte-equal to before (`smoke-{before,after}-*.json`) | No `#[napi]` change, so no `index.d.cts` update. **Known gaps** - **bf16 scratch is not charged.** On a fallback device with a bf16 pool, the varlen partials are not charged by the memory plan: about `rows × Hq × ceil(ctx/512) × (D+2) × 4 B`. int8 is bounded by the kernel's 2,048 row-partition tiling. - **Not bit-equal to MPP.** Tokens can differ at bf16 ties between a device that builds MPP and one that does not. On one device the route never changes. - **Not yet run on the real VM.** The int8 varlen pipelines have not run on the hosted VM; only CI can confirm it accepts them. - **M1 / M2 still untested.** They take MPP if all 24 pipelines build, otherwise the fallback. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
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.Kernel (
crates/mlx-paged-attn/metal/attention/paged_prefill_attention.metal)SPLASH_ATTENTION_TILE_PARTS(a group of 16 runs as 2 parts), per-tilecausal_endand visible pages, f32 partials, and a reduce that sums splits in a fixed order.clamp(ceil((history+rows)/32)/pagesPerSplit, shared, most). Verify usesclamp(ceil(pages/16), 32, 128). Pages per split comes fromKernelCalibration::of: 32, or 64 on non-M5 GPUs with ≤ 10 cores. With no core count reported, 32 cores are assumed.-stdflag.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
PagedPass {Decode, Prefill, Verify}replacesis_prefill/cached_prefix_len.PrefillSdpaKernels,estimate_paged_pool_sdpa_bytes_with_portable, the int8 varlen estimate, the int8 branch ofgather_kv_dense_range,mlx_segmented_sdpa_forward.RuntimeArenasAttentionPartials):release_requestandclear_native_graph_statedrop it, so a failed turn's unevaluated graph never reaches the next launch.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.
The verify arm also charges the prefill-sized workspace the adapter keeps through every verify (Splash
fixedRuntimeBytessums 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).MUTATIONS.md): own chunk read in flight (O1), off-by-onecausal_end, splits =shared, interleaved head grouping (B1, missed by a first/last-head check), K/V charge dropped (K1), Apple9 floor restored (A1, red underMLX_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.MLX_METAL_GPU_ARCH=applegpu_g13s(M1 routing) onmodels::qwen3_5: 572 passed, 1 failed. The failure isdflash2::tests::merged_draft_projections_match_separate_bits(perf(qwen3.5, kquant): Splash-parity work — tiled K-quant layout, all ggml types, int8 KV, fused verify kernels #183 merged draft projections). S10 does not touch it: its 5% element bound does not hold for the gen-13/14 MLX kernels.Gaps
qwen35_paged_prefill_operator_bench.rsstill benchmarks the deleted routes.docs/mlx-fork.mduses it as an MLX D256 benchmark.Not in this PR (live, not run)
🤖 Generated with Claude Code