Skip to content

feat(kv-int8): parked DFlash2 states pin shared prefix pages - #367

Merged
Brooooooklyn merged 1 commit into
mainfrom
feat/kv-int8-s9-states-pin-prefix
Nov 12, 2026
Merged

Brooooooklyn merged 1 commit into
mainfrom
feat/kv-int8-s9-states-pin-prefix

Conversation

@Brooooooklyn

Copy link
Copy Markdown
Contributor

Stage S9 of the Splash int8 KV alignment (stack #344). Base: S32 (#366).

S8 (#364) and S9 must merge together. S8 moved DFlash2 to the int8 pool and dropped parked states. S9 brings them back on pages.

A parked DFlash2 state now holds no target KV. It keeps its prefix chain alive by marking the block it sits on (Splash StateMarks, the same marks the GDN ladder uses). Two sessions that branch from the same replay point share those pool blocks.

before (S8):  no parked state → a prefix hit without the live draft window prefills from 0
before (S7):  parked state = GDN + draft window + private target KV (~2.44 GiB at 78.6K)
after:        parked state = GDN cell + draft window at a whole block, KV stays in the shared pool (marked)

How a state lives

tapped prefill ──chunk ends at R = promptReplayBoundary (Splash workEndOf)──▶ capture GDN cell + window at R
      └─ publish to the store, marked, in use for the turn
finalize: keep it only if block R is in the prefix cache │ abort or discard: drop it
next DFlash2 prime: deepest parked state that beats the live window
      → release the live request → deep-copy cell + window in → KV lookup capped at the state's block
      → block gone → the turn fails ("outlived its target KV block", Splash acquireBlock)
take order: a parked state is one unit; dropping it re-syncs the marks

Changes

  • dflash2_state store: Entry has no KV. A paged backing replaces FlatKv. The KV eviction ladder (compact, lossy steps, evict helpers) and the KV headroom helpers are deleted.
  • As in Splash, a state is published only during prefill, at the replay point (Engine::publishReachedStateBoundaries). No end-of-turn state is parked, so a state is never a partial block. AR, media, reset and session-switch sites stay plain drops.
  • A marked chain counts once, as ordinary pool blocks. State bytes stay in the 3072 MiB budget until S12. At the pool cap, a parked state counts as reclaimable only if no ladder rung marks its block.
  • Installing a state clears the image lineage. A capture is skipped when the GDN state is dirty or the turn carries image positions. A pool swap or weight update clears the store.
  • Deleted (no caller left): MemoryPlan::live_headroom, dflash2_memory_snapshot, KVCache::compact, GdnCell, DFlash2Target::memory_plan.

Tests (13 named mutations, each red when on, green when off)

mutation test shows
MK1 parked_anchor_resume_matches_an_uninterrupted_run park A, run an unrelated turn, resume A: tokens equal an AR reference, resumed on the installed GDN cell
GI1 same test the install must fill the GDN slots (no replay fallback)
CP1 two_sessions_share_the_parked_prefix_blocks B sits on A1's 13 block ids
KV1 parked_state_bytes_have_no_kv_term equal bytes at 1,600 and 78,592 tokens (27B End+Anchor: 397,139,968 B)
LK1 dropping_a_parked_state_returns_its_blocks dropping a state returns its 6 blocks
CA1 tapped_prefill_parks_the_replay_point chunks end at 128/192/208; a twin prompt parks the same bits
CU1, RS1, EV1 park tests cap rule, reset clears, missing block fails the turn
PB1, DD1, BG1 store tests whole block only, one state per block, budget trim
MS1 moe_parked_replay_point_resumes_the_next_session MoE resume
  • After the rebase onto S32 f39eac4: cargo fmt --check, cargo clippy --all-targets -D warnings, yarn build:native, yarn typecheck clean; mlx-core --lib (RUST_TEST_THREADS=1) 4,766 passed, 0 failed. mlx-paged-attn all binaries passed before the rebase.

Gaps (S11 / S12)

  • Only replay-point captures: no capture at the KV hit, no rolling checkpoints. Two sessions with the same document but different questions still prefill from 0 until S12.
  • A cancelled turn keeps no state. Splash publishes after every prefill chunk, so it keeps one.
  • A session switch resumes at the other session's replay point, not at its exact turn end.
  • One extra prefill chunk edge per DFlash2 turn (the cut at the replay point). Not measured.
  • A ladder rung and a state can share one GDN cell on one block. No resume-point keep.

Not in this PR (live, not run)

  • L0 sanity; L1 two sessions on a shared 16K prefix (fork), prefix-hit tokens and pool blocks recorded, with a before row on S8; L2 the S8 L3 speed re-check.

🤖 Generated with Claude Code

@Brooooooklyn
Brooooooklyn added this pull request to stack #344 November 11, 2026 17:47
@coderabbitai

coderabbitai Bot commented Nov 11, 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

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: ca724ec6-66ba-42d1-9257-129771ff9e2d

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
  • Autofix · 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

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-12T15:56:57.113979Z 1d41f93 New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@Brooooooklyn
Brooooooklyn force-pushed the feat/kv-int8-s9-states-pin-prefix branch from 8823b28 to b67a675 Compare November 12, 2026 13:41
@Brooooooklyn
Brooooooklyn removed this pull request from stack #344 November 12, 2026 15:43
@Brooooooklyn
Brooooooklyn force-pushed the feat/kv-int8-s32-gqa16-tile-parts branch from 5c6f1f7 to ac26334 Compare November 12, 2026 15:53
Base automatically changed from feat/kv-int8-s32-gqa16-tile-parts to main November 12, 2026 15:53
A DFlash2 prefill now ends a chunk at the prompt's replay point (Splash
promptReplayBoundary) and parks the GDN cell and draft window there. The
parked state holds no target KV: it marks the block it sits on, so the
prefix chain stays in the pool and sessions that share a prefix share its
blocks. A later DFlash2 turn on that prefix installs the deepest parked
state and looks its chain up capped at that block.

The flat store (KV copies, compaction, demotion, KV headroom) is gone. A
state is one reclaim unit; dropping it re-syncs the marks. A state whose
block did not register at finalize, or whose turn aborted, is dropped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Brooooooklyn
Brooooooklyn force-pushed the feat/kv-int8-s9-states-pin-prefix branch from b67a675 to 1d41f93 Compare November 12, 2026 15:54
@Brooooooklyn
Brooooooklyn merged commit 9bd4dea into main Nov 12, 2026
1 check failed
@Brooooooklyn
Brooooooklyn deleted the feat/kv-int8-s9-states-pin-prefix branch November 12, 2026 15:54
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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant