Repository navigation
feat(kv-int8): a decoding lane waits at most 500 ms behind a prefill - #375
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: 5ce5404afe
ℹ️ 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".
0315514 to
72a4854
Compare
d81f71b to
8478008
Compare
8478008 to
dd91726
Compare
Qwen3.5 dense and MoE cut a prefill that runs beside a decoding lane to the rows the last timed unit says fit in 500 ms (Splash Scheduler::planPrefill, cutRows). Every other family keeps the fixed 2048-row budget. - Plan: Splash leadsBefore (overdue, fewest remaining, order) with 3 overtakes, joiner rows that spare a chunk, at most 4 lanes, the attention-pair bound, cancelled and waiting lanes left out. - Decode debt: a contended unit owes the decoders decodeShare (0.5) of its wall; --decode-share sets it (serve, agent, host, loader). - Admission: the prepared start waits until the next unit serves it (Splash prefillAdmissionOrder); a held start drops its memory wait. - The executor times its prefill and decode phases; a prefill claim ends at its row's end; the decode-gap classifier reads one G and counts the prefill beside a lane (decode_gap_causes.prefill_ms). - Status: memory_governor.scheduler[] per model (prefill units, bound cuts, contended prefill latency, decode batches, gauges by phase). - Deleted: MLX_SCHED_MAX_BATCHED_TOKENS, StepPlan::token_budget. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Starts the scheduler does not want yet (Splash Engine::admitQueued's queue) wait in their own queue in submission order instead of the one refused slot, so a later short start is admitted past a held long one. Only a start refused memory or a lane holds back the rest. A held start keeps its submission order and is overtaken by each prefill unit that serves a later submission, so it turns overdue and leads. A later turn of its owner, a reset, a barrier or an exclusive command does not pass it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… deficit The held retry takes each start from the queue only when it tries it, so a GPU OOM restart in one start's prefix preparation fails the starts not yet tried instead of admitting them without an owner. A held start clears its host refusal (Splash Engine::deferWait), since sync_claims never visits it and its demand would stay in the host deficit. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… candidate serves_candidate plans over the running lanes plus the admitted Waiting turns not yet promoted, as Splash Scheduler::admit makes a start a Prefill lane at once. A burst no longer admits a start its first unit would not serve. Co-Authored-By: Claude Opus 5.5 <[email protected]>
72a4854 to
6b628b5
Compare
…it and on rolling checkpoints (#376) 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](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
Stage S33 of the Splash int8 KV alignment (stack #344). Base: S11 (#374).
Qwen3.5 dense and MoE now cut a prefill that runs beside a decoding lane. The cut is the rows the last timed unit says fit in 500 ms, so a decoding lane waits about 500 ms at most behind a prefill. Splash:
Scheduler::planPrefill,cutRows,leadsBefore, decode debt,prefillAdmissionOrder. Every other family keeps the fixed 2048-row budget and plans exactly as before.Changes
engine::scheduler:PrefillUnit::{Fixed, Measured}.Fixed { budget }is the old loop.MeasuredportscutRows,leadsBeforewithMAX_OVERTAKES3, the joiner rule(remaining − 1) % 2048 + 1(skipped when it does not fit), at most 4 lanes (PREFILL_MAX_LANES), and the attention-pair bounddense_attention_pairs(native − 2048, 2048)(the leader halves down to 64 rows while above it). Cancelled rows and S11 waiters whose retry is not due never lead and never size the unit.decode_share × walltodecode_debt_ms; decode steps pay it down; it drops when no lane decodes (SplashdropStaleDecodeDebt).--decode-share <share>onmlx serveandmlx agent→ host → loader → the qwen3_5 / MoE load optiondecodeShare. Parsed as Splashparse_decode_share(finite, ≥ 0). Default 0.5. The loader refuses it for other families.hs): a start waits untilserves_candidatesays the next unit serves it. A live continuation counts the tokens it keeps. A held start takes SplashdeferWait+deferAdmission: its wait resets and its ledger claim stops waiting. Held starts wait in their own queue in submission order and hold back nothing (SplashEngine::admitQueued: "The others wait for scheduling, and hold back nothing"), so a later short start is admitted past a held long one. Only a start refused memory or a lane holds back the starts after it. A held start keeps the submission order it took when first held, and each prefill unit that serves a later submission overtakes it (SplashScheduler::complete), so after 3 it is overdue, leads and is admitted. A later turn of a held owner, a reset, a barrier or an exclusive command does not pass a held start. Held starts are not retried while a lane is suspended (Splash recovery tries no start of that priority).StepResult.decode_wall_micros,prefill_wall_micros). A prefill claim ends at its row's end (row_work_end, SplashEngine::workEndOf).DECODE_GAP_MS(500) feeds the cut and S11's decode-gap classifier. The prefill wall of a step reaches every decoding lane beside it, so a gap over 500 ms there is counted as PrefillUnit (decode_gap_causes.prefill_ms).memoryGovernorStatus().scheduler[]and/healthmemory_governor.scheduler[], one entry per model with Splash's names:queued,waiting_resources,waiting_prefix,prefilling,decoding(by phase, as SplashScheduler::snapshot),prefill_batches,prefill_rows,prefill_units,bound_cuts,decode_batches,decode_batches_by_width,decode_gap_target_ms,contended_prefill_ms(SplashFineLatencyHistogram),replans. The counters are atomics the model thread registers once;/healthjoins the served model name.LatencyHistogrammoved toengine::latencybeside the newFineLatencyHistogram.Deleted
MLX_SCHED_MAX_BATCHED_TOKENS,scheduler_max_batched_tokens,Scheduler::max_num_batched_tokens,StepPlan::token_budget, its docs row.git grepfinds none of them.DECODE_GAP_SECONDSandPassWork::ran_prefill(replaced byDECODE_GAP_MSand the step's prefill wall).Plan numbers
No existing plan number moved: no assertion of an existing test changed, and every
Fixedscheduler test is unchanged. The new numbers below come from the new tests.Tests
37 new tests (35 Rust, 2 TS), 38 named mutation runs (
MUTATIONS.md). Each test is red under its mutation and green without it. Rust mutations ran as runtime switches on one test binary; the TS ones by edit, then reverted. All switches are gone (git grep MLX_MUT= 0).deeper= 1, Q2 no rest rule, Q4 untimed rows timed, J1 joiner takes what is left, B1 decode rows charged to the unit, L1 FCFS leader, O1 no overtake count, W1 no width break, P1 no halving, C1 cancelled lanes lead, E1 retry clock ignored, K1 a refused lane is skipped in overtakes.hs): AQ1 a held start kept as a refused one (it blocks the later short start), AQ2 held starts never overtaken, HR1 the retry takes all held starts out first (a GPU OOM restart then misses the ones not yet tried), HD1 a held start keeps its host refusal (it stays in the host deficit).hs): M1 the hook never applied, W2 prefill claim ends at the pinned break, T1m prefill wall left 0, G2 the pass keeps no prefill wall, S3 admission skips the gate, H1 kept tokens not counted, D3 a held start keeps its wait, P1 the prepared start left out of the gauges, R1 the scheduler not registered, D2 the dense hook ignores the load's share.__test__/cli/serve.test.ts), the health name join skipped (__test__/server/health.test.ts).Gates on the squashed head:
cargo fmt --all -- --check,cargo clippy --workspace --all-targets -- -D warnings,yarn build:native(+index.d.ctscopy, no diff),yarn typecheck,yarn tsc -b --force,vp lint --type-aware --type-checkandvp fmt --checkon the touched files: clean. mlx-core--lib(RUST_TEST_THREADS=1): 4,773 passed, 0 failed, 220 ignored.vp test(touched tests,__test__/server,packages/server,packages/lm/__test__,packages/cli/__test__): 78 files, 1,865 passed, 8 skipped.After the rebase onto S11 d81f71b: S11's decode work end no longer adds
+1(the pending token is already innum_tokens), sorow_work_endfollows it anda_prefill_claim_ends_at_its_row_endnow expects 21. fmt, clippy,yarn build:native,yarn typecheck,yarn tsc -b --force: clean. mlx-core--lib(RUST_TEST_THREADS=1): 4,787 passed and 1 failed (that test, since fixed);engine::rerun: 581 passed, 0 failed.Review round r1 (held starts queue apart):
cargo fmt --all -- --check,cargo clippy --workspace --all-targets -- -D warnings: clean. mlx-core--lib(RUST_TEST_THREADS=1):engine::583 passed,models::qwen3_5(MoE included) 567 passed,models::qwen3::46 passed, 0 failed. No#[napi]or TS file changed.Review round r2 (held starts stay visible to recovery and leave the host deficit): the held retry takes each start from the queue only when it tries it, so a GPU OOM restart fails the rest. A held start clears its host refusal (Splash
Engine::deferWait), sincesync_claimsnever visits it. fmt, clippy: clean.engine::585 passed,models::qwen3_5567 passed,models::qwen3::46 passed, 0 failed.Review round r3 (a start admitted earlier in the same pass is a lane to the next candidate):
serves_candidateplans over the running lanes plus the admittedWaitingturns not yet promoted (SplashScheduler::admitsetsPhase::Prefillat once). Probe: a 40,000-token start waiting for promotion now holds back a 50,000-token candidate and still lets a 300-token one join. fmt, clippy: clean.engine::586 passed,models::qwen3_5567 passed,models::qwen3::46 passed, 0 failed. No#[napi]or TS file changed.Gaps
Scheduler::admitmakes them Prefill lanes at once), one candidate at a time in submission order; Splash plans all candidates of a pass together and replans without the unserved ones, so here a start admitted earlier in a pass is not re-checked when a later one leads it (Splash would hold the earlier one).MLX_SCHED_LONG_PREFILL_TOKENS, the pinned grid andMLX_PAGED_PREFILL_CHUNK_SIZEstay for the other families; qwen3_5 does not read the grid.waiting_mask,terminal, pass and index-page counters;decode_batches_by_widthhas one key per width up tomax_num_seqs.prefill_units,prefill_batchesandprefill_rowscount only units with a timed row; Splash counts each committed command and each completion, failed rows included.the_step_times_its_prefill_phaseruns the real executor on the test model, and thepublish_gauges()call insidedrivehas no test of its own.Not in this PR (live, not run)
MLX_CONTINUOUS_BATCHING=1; A decodes while B sends about 32K tokens. Pass: A's largest gap ≤ 1000 ms, A still decodes after B's first token,scheduler.bound_cuts> 0. Before row on S11.🤖 Generated with Claude Code