Skip to content

feat(kv-int8): DFlash2 states are ledger claims, captured at the KV hit and on rolling checkpoints - #376

Merged
Brooooooklyn merged 6 commits into
mainfrom
feat/kv-int8-s12-state-captures
Nov 12, 2026
Merged

Brooooooklyn merged 6 commits into
mainfrom
feat/kv-int8-s12-state-captures

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Stage S12 of the Splash int8 KV alignment (stack #344). Base: S33 (#375).

A DFlash2 turn now plans and claims its states like Splash. It plans rolling checkpoints, a junction at the KV hit and the replay point (Splash configureDraftStatePlan). Each capture is a ledger claim (Splash Engine::stateClaim). States are published after every prefill chunk. A state is the GDN cell plus a 4-bit draft context window. The live lane between turns is gone: the next turn resumes at the deepest stored state.

before:  prime: live lane (seq 0 kept live) | store hit | cold; no junction
         prefill breaks: GDN ladder rungs + R; one publish after the prefill (abort drops it)
         state = GDN cell + bf16 draft K/V window; 3,072 MiB state budget, oldest first
         draft K/V = sliding buffer, +256-row regrowth
after:   lookup: deepest store state S; probe the whole KV hit K; J = K if a state sits below K
         plan: checkpoints 4096·k (disposable) + J (ordinary) + R (ordinary, in use)
         each chunk: book its KV (growLane), then claim its capture:
                                  R InService CanWait | checkpoint / J Optional Immediate
                                  refused + reclaimable checkpoint -> SettledOnce, from the lane
         publish after every chunk: register blocks, publish, retire the older checkpoint
         state = GDN cell + 4-bit window (5,898,240 B on the 27B); no budget, checkpoints go first
         end: register + release; ring + window -> idle lane; draft K/V = fixed 2,048-slot ring

Changes

  • dflash2_state/plan.rs (new): planned_checkpoints, replay_state_boundary, configure_draft_state_plan, plan_draft_context and command_breaks (Splash reserveCaptures "passed" rule). The checkpoint margin is the constant PREFILL_STEP_SIZE (Splash prefillTokenBudget).
  • Store: StateClass (checkpoint / ordinary), dedup, upgrade on an ordinary publication (keeps the publication, Splash makeOrdinary), use_state / end_use, checkpoint_state, state_below, and lineage bytes in each entry's size.
  • Captures are claims: state_claim + reserve_capture, claimed after the chunk's KV is booked (book_chunk, Splash Engine::prepare: growLane before reserveCaptures), so an optional state is refused instead of taking the room the chunk needs. A refused checkpoint with a reclaimable checkpoint on the lane retries as SettledOnce and snapshots inside the claim (Reached::FromLane, Splash fromLane). A refused capture still runs use, dedup and retire.
  • The restore is a claim too: GDN cell, plus the ring bytes the idle ring lacks, plus a window only when the draft is rebuilt and the idle lane has none (Splash admitIdleLane). Wait retries; Fail makes the turn cold (Splash admit).
  • register_committed_blocks registers a chunk's full blocks before its states are published, so a cancelled prefill keeps what earlier chunks published.
  • 4-bit draft context window: Metal store, load and copy (draft_context.metal.inc, mlx_draft_context.cpp), DraftContextWindow. Rows are cast to bf16 before the store. A restore dequantizes and projects the window, and skips it when the first point is a full window past the resume (Splash restoresDraftState).
  • Resume: junction probe over the whole KV hit, lazy_junctions counted once per admission (Splash recordLookup), plan and restore decision at resolve. A turn without cache reuse keeps its turn state with an empty plan.
  • DFlash2 finalize registers, releases, then ends the replay-point use. save_paged_history skips the frontier check on a released lane, so the GDN dirty latch stays clear.
  • AR turns read GDN from a store entry (in use, restamped at the end).
  • Unit order: a model's checkpoints go first, then the stamp merge of ordinary states and idle owners (Splash Cache::nextUnit Phase::Checkpoints).
  • Draft K/V is a fixed ring of 2,048 slots plus the block rows, with a per-row mask in eager and compiled paths. The ring and window live in an idle lane between turns. Aborts and a dropped stepper also put them back. The idle lane counts in the states account.
  • Serial-lane suspend: a DFlash2 prefill or verify that yields vacates, waits, then claims the lane buffers, then the KV, and replays from its deepest state (Splash admit order). A vacate publishes nothing.
  • Counters in memoryGovernorStatus().dflash2States and /health dflash2_states (Splash keys).

Memory plan

plan before after
27B draft K/V ring (kv_ring_bytes) 47,329,280 (2,311 rows) 42,106,880 (2,056 rows)
27B lane beyond the pool cell 201,273,344 201,949,184 (ring + 5,898,240 window)
27B lane vs Splash laneBytes 905,216 short 229,376 short (conv alignment −393,216, ring rows +163,840)
M3 Pro 27B int8 + DFlash2 pool blocks 14,137 14,136
M3 Pro 27B int8 + DFlash2 window 221,177 221,177
M3 Pro 27B bf16 + DFlash2 window 112,473 112,473
M3 Pro 27B serial MTP window 155,641 155,641
27B state (GDN cell + window) – 159,842,304 + lineage bytes

Deleted

  • MLX_DFLASH2_STATE_BUDGET_MB and the state budget (STATE_BUDGET_ENV, DEFAULT_STATE_BUDGET_MB, parse_state_budget, with_state_budget, trim_to_budget).
  • DFlash2States.unregistered, drop_unregistered, settle_replay_state, publish_replay_state, replay_capture_row, draft_keep_from.
  • The live lane: DFlash2Hit::Live, reusable_paged_dflash2_prefix, StoreHit::beats_live, the keep-live finalize. live_window_prefix stays only in the offline replay.rs, private.
  • DRAFT_KV_STEP and ring regrowth, DFlash2Attention.sliding_window (the mask is per block now), trace::JUNCTION_MIN_GAP.

Tests

  • No model loads. Each test was run once with its mutation on (red) and once off (green), on one test binary (MUTATIONS.md). 44 mutations:
    • plan and store: planned_checkpoints_match_splash (CK1), plan_merges_points_like_configure_draft_state_plan (JG1, PS1), draft_spans_match_plan_draft_context (DS1), ordinary_publication_upgrades_a_checkpoint (UP1), state_bytes_count_the_lineage (TB1), state_below_sees_strict_ancestors_only (SB1).
    • 4-bit window: context_window_quantizer_matches_the_kernel (Q15), state_bytes_27b_geometry (WB1), restore_rebuilds_the_draft_or_starts_empty (RD1), rows_of_a_non_bf16_draft_store_as_bf16 (CB1).
    • publish: rolling_checkpoint_keeps_one_and_the_one_below_r (RC1, RP1), cancelled_prefill_keeps_reached_states (CN1), committed_blocks_register_once (RB1).
    • claims: capture_claims_follow_state_claim (SC1, RB2, RW1), refused_checkpoint_comes_from_the_lane (FL1, FL2), chunk_kv_is_booked_before_its_capture (KV1, review C1).
    • resume: junction_at_the_kv_hit (JN1), dflash2_turns_resume_at_the_deepest_state (LV1, SV1), a_resumed_lane_counts_no_junction (JR1), a_turn_without_reuse_publishes_no_state (RU1), a_paged_turn_without_a_replay_point_keeps_its_junction (TJ1).
    • units and AR: checkpoints_go_before_ordinary_states (CF1), ar_turn_restores_gdn_from_a_composite_state (AR1).
    • ring and lane: ring_after_n_cycles_holds_the_sliding_rows (RG1), ring_attention_matches_the_sliding_window (DM1), lane_buffers_are_reused_between_turns (LB1), length_exit_runs_no_terminal_forward (TF1), idle_lane_counts_in_the_states_account (IA1), aborted_turns_leave_their_lane_buffers_idle (AB1, SD1).
    • suspend: vacate_of_a_dflash2_turn_publishes_nothing (VC1, RK1), moe_suspension_replays_on_the_lane_buffers (MVC1, MVP1).
    • after the rebase: a_suspended_dflash2_lane_drops_its_cells_and_idles_its_ring, dense and MoE (R1m, RI1); a_stop_during_the_replay_completes (R4); dead_leaves_go_after_checkpoints_before_ordinary_states (DL1, new).
    • review round 2: a_failed_window_copy_is_an_error (EV1, EV2: a window copy that fails on the GPU is an error, never a published state or moved bounds), the_idle_lane_holds_materialized_buffers (IR1, IR2: the idle lane keeps only materialized ring and window, so a restore credits only real storage).
  • Re-pinned: draft_kv_ring_bytes_match_the_window_buffer_cap, qwen38_27b_lane_bytes_against_splash, dflash2_takes_the_one_pool_window (numbers above).
  • Gates on the squashed commit: cargo fmt --all -- --check and cargo clippy --workspace --all-targets -- -D warnings clean. mlx-core --lib (RUST_TEST_THREADS=1): 4,798 passed, 0 failed, 220 ignored. cargo test -p mlx-paged-attn --lib: 210 passed, 8 ignored. yarn build:native passed, index.d.cts unchanged after the copy. yarn typecheck and tsc -b --force (23 projects) clean. vp lint and vp fmt on health.ts and health.test.ts clean. vp test __test__/server packages/server packages/lm/__test__: 1,596 passed, 7 skipped.
  • Review round 2 (H1, M1): fmt and clippy clean; scoped engine:: 587 passed, models::qwen3_5 (dense + MoE) 594 passed, models::qwen3:: 46 passed, 0 failed. No #[napi] or TS file changed.
  • After the rebase onto S33 0315514: fmt and clippy clean; mlx-core --lib 4,819 passed, 0 failed, 220 ignored; mlx-paged-attn 210 passed, 8 ignored; yarn build:native passed, index.d.cts unchanged; yarn typecheck, tsc -b --force clean; vp test 1,596 passed, 7 skipped.
  • Rebase mapping: a verify still lends its GDN cells to the target across its claim (S11), so a suspend drops them before the wait; its ring now goes to the idle lane instead of being dropped. The S11 dead-leaves unit now sits after the checkpoints (Splash Phase order), and the stop-during-replay rule moved with the replay into suspended_wait.

Gaps

  • 16-token blocks, so points round to 16 (Splash pages are 32). Ring attention uses MLX SDPA with a per-row mask, so its summation order differs from Splash's tiles (no bit parity).
  • No shared-prefill points (Splash addSharedPrefillBoundaries); one turn plan per model. The idle lane is never taken by a claim, and it is counted in the states account but is not a ledger unit.
  • No restore lease: checkpoint_pinned is always false. No capture is ever Pending (no SSD state tier).
  • unprovenState and lostStateMisses are not ported.
  • Decode registers its blocks only at finalize, so a cancel during decode loses the decode KV.
  • A passed checkpoint is never captured as a fallback when a chunk's KV claim is refused, and stateCaptures is not counted (mlx-node chunks end at every captured point).
  • A block reserve still evicts dead leaves before any checkpoint (the allocator does it inside reserve); only the ledger's dead-leaves unit follows the checkpoints.
  • DFlash2 turns still publish GDN ladder rungs when a cold GDN sidecar policy is on. AR turns keep the ladder, the history entry and the live lane.
  • After a restore claim fails, the cold turn still plans its junction. In Splash the request is skipCache and plans no junction. Outputs stay correct.
  • The serial decode suspend stays in place (S11's suspend_in_place); only the prefill unwinds through DFLASH2_SUSPENDED. The tests force the yield with a test hook, not with host pressure, because a real HostPressure denial first takes the checkpoints.
  • The MoE prefill has no cancel hook, so there is no MoE cancelled-prefill test.
  • The target side of a paged prefill chunk still evaluates with the error-swallowing MxArray::eval (hidden_states.eval() in paged_forward.rs, older than this PR), so a GPU failure there is only logged; the draft window's own copies now fail the turn (Splash NativeRuntime::executionFailed).

Not in this PR (live, not run)

  • L0 sanity on the full release build; L1 teacher-forced acceptance, fresh vs restored turn (4-bit window), S vs base; L2 turn-2 TTFT without the live lane; L3 states after one 64K prompt (rolling checkpoints, no budget); L4 DFlash2 decode at 8K and 64K, S vs base. Commands: LIVE.md.

🤖 Generated with Claude Code

@Brooooooklyn
Brooooooklyn added this pull request to stack #344 November 12, 2026 10:38
@coderabbitai

coderabbitai Bot commented Nov 12, 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: 229447f3-b885-4748-83ff-08035eed6d45

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 12, 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-12T16:03:20.533079Z 481fa1a 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-s12-state-captures branch from bd0b0ef to b7f7b08 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-s33-measured-prefill-cut branch from 72a4854 to 6b628b5 Compare November 12, 2026 15:58
Base automatically changed from feat/kv-int8-s33-measured-prefill-cut to main November 12, 2026 15:58
Brooooooklyn and others added 6 commits November 12, 2026 23:58
…it and on rolling checkpoints

A DFlash2 turn plans its state points like Splash configureDraftStatePlan:
rolling checkpoints every 2 x draft window, a junction at the KV hit, and
the replay point. Each capture is a ledger claim (Splash Engine::stateClaim):
the replay point is InService and can wait, checkpoints and the junction are
Optional and Immediate, and a refused checkpoint can come from the lane.
States are published after every prefill chunk, so a cancel keeps them.

A state is the GDN cell plus a 4-bit draft context window (Metal store,
load and copy). The state budget is gone: checkpoints are the first state
units the ledger takes. The live lane is gone: a DFlash2 turn releases its
lane at the end, keeps its ring and window in an idle lane, and the next
turn resumes at the deepest stored state. The draft K/V is a fixed ring.
A DFlash2 turn suspended by the serial lane replays from its deepest state.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Splash Engine::prepare runs growLane before reserveCaptures. S12 claimed
the capture first, so an optional state's reservation could take the room
the chunk's KV growth needed and a cold prefill failed with
capacity_exhausted. book_chunk now records the chunk, then claims the
capture, in the dense and MoE loops.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…al buffers

A DraftContextWindow snapshot or copy whose GPU eval fails now returns the
error instead of publishing the window or moving its bounds (Splash
NativeRuntime::executionFailed publishes nothing). The idle lane
materializes the ring and window it keeps and drops them if that fails, so
a restore claim credits only storage that exists (Splash
QwenStateStorage::releaseLane pools allocated rings).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The hosted macOS runner is a VM whose GPU reports no Apple GPU family and
whose compiler rejects the tensor ops of the paged prefill kernels, so every
test on that route failed or hung there. A test hook reports the missing
family; the pipeline-build test expects no pipelines then, and each paged
prefill test prints a skip and returns. A real Mac (Apple7 and up) still
runs them.

- Qwen4 fixture load: the fixture-host child also gets the fixture's
  working set (12 GiB), not the VM's 4 GB.
- grouped_deferred_matches_the_prepare_chain: skips when the device
  declines the fused GDN step, as the other fused tests do.
- int8_varlen_prefill_reads_past_the_aux_cap: ignored (heavy GPU, timed
  out on the VM).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e family

The integration suite still ran the paged prefill kernels on the hosted VM
GPU, which has no Apple GPU family and cannot build them. The synthetic
MoE MTP gate failed there with "Failed to extract int32 scalar": the
pipeline error from the prefill eval was swallowed, and only the verify
step's token read reported it. The two paged-attn prefill tests failed at
eval for the same reason; the earlier failing binary hid them.

Both now skip through the mlx_test_gpu_lacks_apple_family hook, as the lib
tests do. A real Mac (Apple7 and up) still runs them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
free_at dropped `at` on a release that left another holder, so kept
tables released out of turn-end order stamped the older end and eviction
took a recently used prefix first. Every Some(at) release now raises the
leaf to max(own, at); a None release still stamps only when the cache is
the sole holder (Splash KvCache::releaseActive).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Brooooooklyn
Brooooooklyn force-pushed the feat/kv-int8-s12-state-captures branch from caea776 to 481fa1a Compare November 12, 2026 15:59
@Brooooooklyn
Brooooooklyn merged commit 49e5e11 into main Nov 12, 2026
0 of 6 checks passed
@Brooooooklyn
Brooooooklyn deleted the feat/kv-int8-s12-state-captures branch November 12, 2026 15:59
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