Repository navigation
refactor(kv-int8): qwen3.5 inference runs only on the paged pool - #369
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. |
7c8b818 to
96562de
Compare
0d46433 to
0982cff
Compare
96562de to
5cf9535
Compare
On Metal every qwen3_5 dense and MoE turn (AR, MTP, DFlash2, images, eval, calibration) runs on the block-paged pool, as in Splash. The flat full-attention inference lane is deleted: the flat turn cores, flat MTP arms and eager verify forwards, generate(), the int8 flat KV cache and its segmented int8 wrappers, the sym8 pin, use_block_paged_cache, MLX_QWEN35_PAGED_OVERRIDE, the flat memory-plan lane and the layer-cache flat replay arm. Every Apple GPU family gets the pool; a layout with no paged-attention kernel fails the load. Off Metal (the CUDA preview) a load has no pool and serves bf16 autoregressive turns only; int8 is refused there. Paged Q/K/V are cast to the pool's io dtype, so sym8, f16 and f32 checkpoints write the pool. MoE training generation uses bf16 K/V. The server host no longer clones qwen3_5 configs to force a paging key they ignore. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Calibration now prefills on the pool, and a row shorter than one block takes the single-shot path. Its kept hidden stays in the load's compute dtype (only Q/K/V are cast to the pool dtype), so the bf16-only debug assert panicked for f32/f16 checkpoints. The assert now checks that final_norm keeps the residual's dtype. Co-Authored-By: Claude Opus 5.5 <[email protected]>
0982cff to
c130078
Compare
Stage S14 of the Splash int8 KV alignment (stack #344). Base: S10f (#369). S14 needs only S8, so it sits right after S10f in the stack (the plan lists it after S13). S11 is rebased onto it. The Qwen3.5 dense and MoE DFlash2 verify now folds the last cycle's kept GDN rows into the lane's other cell before its own 8 rows, and the commit only swaps the two cells. No GDN commit kernel and no replay run per cycle. Splash: `gdn_decode_batch_phase`, `QwenStateStorage::swapDecodeParity`, `GdnTapeLane`. ``` before: verify n: kernel writes the window-final state into the spare cell commit: keep == 8 -> adopt the spare cell else -> mlx_gdn_commit_all replays the kept rows (every cycle on grouped 27B) declined -> per-layer replay from a per-cycle snapshot after: verify n: one deferred kernel per GDN layer fold tape(n-1)[0..keep(n-1)] into the other cell -> run 8 rows -> write tape(n) + raw inputs commit: swap parity, pending := (tape(n), keep(n)) (no kernel) finish: fold the last pending rows once (replay_into) kernel declines -> the turn errors; a load it cannot serve refuses the draft ``` ## Kernel (`gdn_fused_step.metal.inc`, `mlx_gdn_fused.cpp`) - New `tiled_heads` param. Tiled maps value head `hv` to key head `hv % Hk` (llama.cpp GGUF rows). Grouped maps it to `hv / (Hv / Hk)` (Splash `key_head`). The q/k writer is one of the sharers per key head. With Hk = Hv, both maps are the identity. - The deferred entry writes the window's raw conv inputs `[1, T, W]` as one more output (Splash `step_tape.inputs`). The next verify reads that output as its pending tape, so no projection view and no copy at bind. - Only the deferred entry carries the flag. The step kernel and the non-deferred complete entries pass `tiled_heads = true`, so their routes do not change. ## Changes in the model - `GdnStateBlobs` (`gdn_blob.rs`): `pack(caches, tiled)`, `pending(row)` (the tape and keep, or a zero 1-row tape with keep 0 after a prefill), `retain(tape, keep)` and `settle(caches)`. `retain` swaps parity and refuses keep 0, keep > 8, or keep above any layer tape's rows (Splash `GDN::addDecode` checks). `settle` expands grouped keys for `gated_delta_replay`. - Both verify cores (`qwen3_5` / `qwen3_5_moe` `paged_forward.rs`) use 10 cache slots: 2/3 are the other cell, 4..9 hold the pending tape and keep. A wrong cell count is now an error, not a silent filter. - `GatedDeltaNet::forward_complete` lets grouped heads through, but only for a deferred cache. A decline under slot 4 errors: `"deferred GDN complete kernel declined"`. - Both steppers: no per-cycle snapshot, `retain` on every commit, `settle` in `finish` (before the draft-window stash). A GDN state that cannot be packed is an error. - Load: both `require_dflash2_pool` refuse a draft whose GDN layers fail `GatedDeltaNet::deferred_verify_refusal`: 4 taps, 128-wide heads, Hv a multiple of Hk, f32 sidecars, bf16, Metal (Splash `compiledGdn` fails closed). ## Memory plan The lane now charges the pending tape between cycles (Splash `DecodeTensor::GdnTape`, `gdn_tape_layer_bytes`): per linear layer, 8 rows × ((W + Hk·Dk + Hv·Dv) × 2 + Hv × 6). | plan | before | after | |---|---|---| | pending tape, 27B (48 layers × 297,216) | – | 14,266,368 B | | 27B `lane(512)` (`transient_charges_the_decode_free_pool`) | 232,587,264 | 246,853,632 | | 35B-A3B + DFlash2 lane, every window (30 layers × 230,912) | 196,165,632 | 203,092,992 | ## Deleted - `mlx_gdn_commit.cpp`, `gdn_commit.metal.inc` and the `mlx_gdn_commit_all` extern - `GdnStateBlobs::adopt` / `commit`, `GdnLayerTape::final_state` / `final_conv` - the per-cycle `snapshot_all_mtp` + `replay_mtp_snapshot_to` fallback in both steppers - `MLX_DFLASH2_GDN_BLOB`, `PAGED_ADOPTS` - `THIRD_PARTY_NOTICES` and `docs/models.md` updated MTP keeps `gated_delta_replay` and its snapshot (Splash has no MTP). ## Tests Named mutations, each red when on and green when off (`MUTATIONS.md`, Apple M5 Max, gen 17): | test | mutation | |---|---| | `deferred_fold_matches_t1_settle_on_model_shapes`: 27B and 35B shapes, both head orders, both storage schedules, keep 0..=8, tape rows past keep poisoned with NaN; the fold matches the T=1 chain and `replay_into` bit for bit | F1: fold all 8 rows | | `grouped_deferred_matches_the_prepare_chain`: grouped 27B matches `qwen4_gdn_prepare` -> fused tail bit for bit, and the keep-T fold matches the window-final state | G1: deferred maps tiled heads | | `deferred_verify_takes_the_complete_kernel_for_both_orders`: the layer under a deferred cache | G2: gate refuses grouped | | `retain_swaps_parity_and_settle_matches_replay` | R1: keep 0 accepted; E1: no grouped key expansion | | `paged_dflash2_matches_paged_ar_for_every_keep`: three head orders, every keep, one deferred launch per linear layer per cycle; the cells after `finish` match every cycle's kept rows replayed from the start | K1: retain 8 whatever the keep | | `finish_settles_the_pending_rows`: the cells after `finish` match the deferred kernel's own fold | U1: `finish` skips settle | | `paged_moe_dflash2_lands_on_the_ar_cursor_for_every_keep` | MV1: no pending tape in slots 4..9 | | `pool_lane_charges_the_pending_gdn_tape` | X1: term left out | | `dflash2_companion_needs_a_fused_gdn_target` | L2: no GDN check at load | Final gates: | gate | result | |---|---| | `cargo fmt --all -- --check` | clean | | `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,735 passed, 0 failed, 220 ignored | | `yarn build:native` | ok; `index.d.cts` unchanged (no napi file touched) | | `yarn typecheck` | ok | ## Gaps - **35B MoE safetensors rounding (grouped, Hk16 Hv32 W8192).** AR still decodes through the MLX conv chain there, while the verify now uses the complete kernel. Their q/k norm and decay differ by up to one bf16 / f32 step. Measured in the unit fixture: q/k max diff 2e-3, decay 1 ULP on half the heads, v and raw inputs equal, output max diff 2.7e-4. On that model, DFlash2 now matches AR only up to bf16 ties. It was already no bit reference for AR there (verify attention vs the decode kernel). The 27B (both head orders) stays bit-identical. Fix: run grouped AR/MTP on the same kernel; the MTP replay then also needs expanded keys. This is a later stage. - Grouped heads reach the complete kernel only through the deferred entry. AR, MTP and prefill routes are unchanged. - Head order: Splash re-orders GGUF rows to grouped at load and keeps one key map. mlx-node keeps the tiled rows and picks the map per call with `tiled_heads`. - `finish` settles the pending rows once per turn. Splash never settles (`requireCommitted`), because mlx-node resumes the live cells on the next turn and runs the turn tail on them. - Tiny-fixture token checks: tokens are compared with AR only for Hk = Hv. The Hv = 4 fixtures leave the AR tokens on rounding (tiled at token 62, grouped at 52), so they check the cursor, the launches and the replay-chain cells. - Bit-exact gates ran on one GPU family (M5 Max). T1 needs no model and can re-run on any machine. - The load gate (`deferred_verify_refusal`) checks the norm dtype, not each projection. A hand-made checkpoint with bf16 norms and f32 GDN projections would load and then fail its first verify. No supported input has this mix: GGUF imports cast every dense tensor to bf16, and every local safetensors checkpoint has bf16 projections (local Codex finding, checked by three verifiers). ## Not in this PR (live, not run) `LIVE.md`: - L0: builds and sanity on the GGUF 27B (tiled) and the safetensors 27B (grouped) - L1: DFlash2 vs AR output hashes, both head orders - L2: fold vs commit, S14 vs base: same tokens, decode speed ≥ 0.99× (GGUF) / ≥ 1.00× (safetensors) - L3: native MTP unchanged - L4: second turn resumes the live window after a partial accept - The 35B MoE is not live-gated: no such model is on the machine. 🤖 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 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).
Changes
use_block_paged_cacheis gone from both configs. An oldfalsein a saved config is an unknown key and is ignored.pagedModelTypesdefaults to none.Deleted
flat_turn.rs, dense and MoE), the MoE flatpaged_turn.rsrouter,run_speculative_turnand the desync overrides.None),eager_verify_step, the tape forward,chunked_prefill_with_hidden.generate()/generate_syncand their generation types (dense and MoE), withqwen3_5-generation.test.ts.KVCacheformat,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.FlatInput,LaneKv::Flat, copy bytes,MemoryPlan.flat,flat_lane_transient.QWEN35_PAGED_MODEL_TYPES,DEFAULT_PAGED_MODEL_TYPES.kv_int8_tests.rs, twostream_progress_tests.rs, flat cases inlayer_cacheand planner tests.Tests
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.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.debug_assertinproject_last_token_logits_with_full_hidden. The assert now checks thatfinal_normkeeps the residual's dtype. Testf32_checkpoint_calibrates_a_short_row_on_the_pool, mutation CA2 (bf16-only assert back) red.models::qwen3_5418,models::qwen3_5_moe133,calibration29 passed; fmt and clippy clean.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.--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.ctsunchanged),tsc -b --force: clean.grpo-qwen35,qwen3_5-config,paged-config-override,inference-host: 4 files, 93 passed.vp lint --type-aware --type-checkandvp fmt --checkon the 10 touched TS files: clean.git grep MLX_MUT: 0.Gaps
decide_clefruns the flat forward. It serves decisions, not chat; a chat turn on it is refused on Metal.--max-context.paged_int8_read.rs, as a reference.shared_command_dispatch_orders_family_operations_stats_and_resetno longer checks the effect of its first command (itshistory_len > 0holds from setup).docs/superpowers/plans/2026-06-16-...) still namesMLX_QWEN35_PAGED_OVERRIDEandMLX_QWEN35_FORCE_EAGER.Not in this PR (live, not run)
use_block_paged_cache: falseview andMLX_QWEN35_PAGED_OVERRIDE=0both load on the pool.calibrate.test.ts).🤖 Generated with Claude Code