Repository navigation
feat(kv-int8): one memory ledger governs every claim - #374
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: 69c4040455
ℹ️ 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".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 177aff578e
ℹ️ 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".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 08048a1729
ℹ️ 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".
d81f71b to
8478008
Compare
9c3213d to
84e7bb6
Compare
84e7bb6 to
42feea2
Compare
Qwen3.5 dense and MoE memory goes through one process ledger (Splash MemoryLedger / MemoryGovernor). Every allocation point takes a claim: scheduled rows before each step, whole turns at each paged step, GDN cells, draft state, publications and vision. A refused claim frees units in Splash order, then waits, yields its lane or fails. - Host rule and a 500 ms control pass; margin max(1 GiB, 2%) for the qwen3_5 plan, other families keep 15% + 1 GiB. - Scheduled lanes: per-row claims, Splash judge and yield order, Start / InService admission, resume to the suspended KV target. - Serial lane: a host-refused AR or DFlash2 decode step suspends and replays its tail (greedy exact). - Waits end in resource_timeout after 30 s; capacity_exhausted and metal_out_of_memory map to 503 in the server. - GPU OOM fails the model's running rows and resets its caches. - Status: memoryGovernorStatus() and /health memory_governor (accounts, claims, TTFT parts, decode-gap causes, counters). - Stops: a stopped running row ends in its step, never refused; a stop in a serial lane's wait completes on what the turn generated; a suspended request's end wakes the waits. - A DFlash2 lane replayed after a suspend drops its pending GDN rows. - Deleted: engine::reclaim, the in-order L1-L3 reclaim paths, DraftRefusal, MLX_SCHED_RESERVE_FULL_ISL. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A decode turn's num_tokens already counts its pending token, so the decode work end is num_tokens + the draft allowance (Splash Engine::workEndOf). The extra token claimed a block the step never writes at a block boundary, refusing or suspending the lane. Co-Authored-By: Claude Opus 5.5 <[email protected]>
- try_reserve and the start gate sample again when a reservation retired between the sample and the lock (Splash MemoryGovernor::tryReserve reads charged and reserved at once). - The host pass's settle deadline is per model: an empty model's pass no longer spends another model's reclaim. - A DFlash2 verify lends its lane (GDN cells, pending rows, draft window) to the target across its claim, so a suspend's vacate drops it before the wait (Splash QwenStateStorage::releaseLane), dense and MoE. - A take that removed its unit is Met though it measured nothing (Splash Cache::take), so the ledger lists the units again. Co-Authored-By: Claude Opus 5.5 <[email protected]>
- A decode row whose pending token ends its turn (EOS, max_new_tokens, repetition) claims nothing, as Splash Engine::commit ends the lane there. - An MTP lane's admission reserves its draft state's fixed part, and every row, prefill slices included, claims its draft K/V growth. - MTP's AR step runs under paged_step_claimed (dense and MoE): a refused growth waits instead of failing context_length_exceeded. - A qwen3_5 whole turn's GPU OOM is classified at its boundary (run_paged_turn, run_multimodal_turn), as Splash NativeRuntime::executionFailed: metal_out_of_memory and the model reset. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A bytes need takes the pool's dead leaves and cuts the extent they empty (Splash Cache::takeReclaim), keeping the claim's and queued chains. A stop during a suspended lane's replay completes the turn on its tokens. One row's GPU OOM fails every turn its step completed. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A scheduled lane's prefix preparation (GDN replay of a cached prefix) at admission or at a suspended lane's resume that MLX fails for Metal memory now fails the request metal_out_of_memory and resets the model before the next step, like Splash NativeRuntime::executionFailed around Engine::tick. Co-Authored-By: Claude Opus 5.5 <[email protected]>
8478008 to
dd91726
Compare
…375) 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. ``` before: one step = decode rows + prefill rows from ONE 2048-token budget (MLX_SCHED_MAX_BATCHED_TOKENS) a decoder beside a long prompt waits for a whole 2048-row prefill row every step leader = FCFS; admission = FCFS; no prefill timing after: one step = decode rows (outside the unit) + one prefill unit (leader + up to 3 joiners) no decoder -> unit 2048 rows a decoder -> unit = cut_rows(leader): 512 until a unit is timed, then clamp(R_last * 500 ms / T_last * deeper, 512, 2048); a rest < 512 rides along after a contended unit the decoders are owed 0.5 x its wall (decode-only steps) leader = overdue (3 overtakes) oldest, then fewest remaining, then order a start is admitted only when the next unit serves it ``` ## Changes - `engine::scheduler`: `PrefillUnit::{Fixed, Measured}`. `Fixed { budget }` is the old loop. `Measured` ports `cutRows`, `leadsBefore` with `MAX_OVERTAKES` 3, the joiner rule `(remaining − 1) % 2048 + 1` (skipped when it does not fit), at most 4 lanes (`PREFILL_MAX_LANES`), and the attention-pair bound `dense_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. - Measure: the step's prefill-phase wall, taken only when every planned row ran timed. A failed or untimed row sizes nothing. - Decode debt: a contended unit adds `decode_share × wall` to `decode_debt_ms`; decode steps pay it down; it drops when no lane decodes (Splash `dropStaleDecodeDebt`). - `--decode-share <share>` on `mlx serve` and `mlx agent` → host → loader → the qwen3_5 / MoE load option `decodeShare`. Parsed as Splash `parse_decode_share` (finite, ≥ 0). Default 0.5. The loader refuses it for other families. - Admission (`hs`): a start waits until `serves_candidate` says the next unit serves it. A live continuation counts the tokens it keeps. A held start takes Splash `deferWait` + `deferAdmission`: its wait resets and its ledger claim stops waiting. Held starts wait in their own queue in submission order and hold back nothing (Splash `Engine::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 (Splash `Scheduler::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). - Executor: times its decode and prefill phases (`StepResult.decode_wall_micros`, `prefill_wall_micros`). A prefill claim ends at its row's end (`row_work_end`, Splash `Engine::workEndOf`). - One G: `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`). - Status: `memoryGovernorStatus().scheduler[]` and `/health` `memory_governor.scheduler[]`, one entry per model with Splash's names: `queued`, `waiting_resources`, `waiting_prefix`, `prefilling`, `decoding` (by phase, as Splash `Scheduler::snapshot`), `prefill_batches`, `prefill_rows`, `prefill_units`, `bound_cuts`, `decode_batches`, `decode_batches_by_width`, `decode_gap_target_ms`, `contended_prefill_ms` (Splash `FineLatencyHistogram`), `replans`. The counters are atomics the model thread registers once; `/health` joins the served model name. - `LatencyHistogram` moved to `engine::latency` beside the new `FineLatencyHistogram`. ## Deleted - `MLX_SCHED_MAX_BATCHED_TOKENS`, `scheduler_max_batched_tokens`, `Scheduler::max_num_batched_tokens`, `StepPlan::token_budget`, its docs row. `git grep` finds none of them. - `DECODE_GAP_SECONDS` and `PassWork::ran_prefill` (replaced by `DECODE_GAP_MS` and the step's prefill wall). ## Plan numbers No existing plan number moved: no assertion of an existing test changed, and every `Fixed` scheduler test is unchanged. The new numbers below come from the new tests. | case | rows | |---|---| | no decoder, no measure | 2048 | | a decoder, nothing timed yet | 512 | | a decoder, last unit 2048 rows in 2048 ms at position 0, leader at 2048 | 512 (floor) | | a decoder, last unit 2048 rows in 204.8 ms, leader at 2048 | 1667 | | a decoder, 900 left, cut 512 | 900 (the rest rides) | | 3 decoders with draft allowance 4, leader unmeasured | 512 (decode rows outside the unit) | | leader at 16,384, native window 8192 | 512 (pair bound) | | debt after one 512 ms contended unit at share 0.5 | 256 ms, paid by 9 decode-only steps of 30 ms | ## 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). - Plan: Q1 unit always 2048, Q3 `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. - Debt, counters, admission: S2 share 0, C2 every unit in the histogram, H1 bucket = floor ms, A1 every candidate served, AW1 admitted waiters left out of the candidate's plan, W3 a waiting lane counts as waiting for resources. - Held starts (`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). - Wiring (`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. - Status and gaps: S1 one entry for all models, G1 the step's wall not added to the lane. - TS: D1 the parser accepts negatives (`__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.cts` copy, no diff), `yarn typecheck`, `yarn tsc -b --force`, `vp lint --type-aware --type-check` and `vp fmt --check` on 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 in `num_tokens`), so `row_work_end` follows it and `a_prefill_claim_ends_at_its_row_end` now 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`), since `sync_claims` never visits it. fmt, clippy: clean. `engine::` 585 passed, `models::qwen3_5` 567 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_candidate` plans over the running lanes plus the admitted `Waiting` turns not yet promoted (Splash `Scheduler::admit` sets `Phase::Prefill` at 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_5` 567 passed, `models::qwen3::` 46 passed, 0 failed. No `#[napi]` or TS file changed. ## Gaps - The unit is all prefill rows of one step, each its own forward after the decode batch. Splash joins them in one command, so joiners here add their forward's fixed cost. No stage owns a batched prefill forward. - qwen4_exp (Flash Next) prefill is never cut; Splash runs streamed-weight groups in layer passes. - The admission-time GDN prime over a cached prefix, and the same prime on a resume, run uncut between steps (S12 resumes at state boundaries). - A cached prefix a start would hit only in the prefix cache counts as uncached (no admission prefix probe), so such a start is admitted later than in Splash. - Each start is checked against the resident lanes and the starts already admitted (Splash `Scheduler::admit` makes 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). - No priority tier, no Spill lanes or restoring starts in admission. - `MLX_SCHED_LONG_PREFILL_TOKENS`, the pinned grid and `MLX_PAGED_PREFILL_CHUNK_SIZE` stay for the other families; qwen3_5 does not read the grid. - Refused or blocked rows are left out of the sample; joiners already planned still run (Splash replans the command). - Share 0 gives one decode row and one unit per step; Splash alternates whole commands. - Status leaves out `waiting_mask`, `terminal`, pass and index-page counters; `decode_batches_by_width` has one key per width up to `max_num_seqs`. - `prefill_units`, `prefill_batches` and `prefill_rows` count only units with a timed row; Splash counts each committed command and each completion, failed rows included. - A step whose only prefill rows are cancelled, stopped or blocked still has a prefill wall of a few µs, so a gap over 500 ms in that step reads as PrefillUnit with about 0 ms (inherited from S11's classifier). - No tiny Qwen3.5 forward exists, so `the_step_times_its_prefill_phase` runs the real executor on the test model, and the `publish_gauges()` call inside `drive` has no test of its own. ## Not in this PR (live, not run) - L1: qwen3.8-27b, `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. - L3: B alone, TTFT on S33 vs S11 (information). 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: dd91726e00
ℹ️ 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".
| self.grow_shortfall(&self.allocator_guard(), restorable.saturating_add(held)); | ||
| if shortfall > 0 { | ||
| self.try_grow_pool(shortfall); | ||
| } | ||
| } |
There was a problem hiding this comment.
Size restore growth from the actual cold-cache hit
With SSD caching enabled, a long prompt now grows the pool for every block absent from the hot cache before checking whether any corresponding SSD blocks exist. On an empty cold cache, this allocates the entire prompt's KV capacity even though the restore returns a miss and prefill only needs its next chunk. This defeats on-demand pool growth, introduces a large allocation and synchronization before prefill, and consumes memory that concurrent lanes could otherwise use. Probe the restorable cold chain first and grow only for the blocks that will actually be restored.
Useful? React with 👍 / 👎.
| ), | ||
| ) | ||
| })?; | ||
| let built = build()?; |
There was a problem hiding this comment.
Record driver refusals from initial pool construction
If Metal rejects a buffer allocation during initial pool construction, build()? returns without setting START_REFUSAL, so start_under_growth_lock immediately propagates the error instead of applying its driver-refusal retry window. The other paths that set START_REFUSAL only perform registration and logical reservation checks, so they cannot classify this actual driver rejection. Classify allocation failures from the build as DriverRejected at the runway stage while leaving non-allocation construction errors non-retryable.
Useful? React with 👍 / 👎.
…old tier The #374 governor refuses Optional claims on a host short of spare memory (the 7 GB hosted runner). A refused dense GDN ladder rung was dropped, so nothing reached the cold tier and the restart restored nothing. Splash falls back to publishStateToDisk; the rung now stays for this turn's sidecar capture and is dropped at the turn's end. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…he cold tier MoE dropped a ladder rung the #374 governor refused, so on a host short of spare memory no MoE recurrent state reached the cold tier. Mirrors the dense fix (Splash publishStateToDisk): the deepest refused rung is held for this turn's sidecar capture and dropped at every turn end. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…eces and q offset views (#380) Follow-up to #377. Fixes the Codex findings on #377 and the gaps found while fixing them. ``` host short of spare memory (7 GB runner): #374 governor refuses Optional claims GDN ladder rung refused ──► #377: kept for the turn's cold sidecar capture this PR: at most TWO held rungs per scheduled sequence — the deepest, and the deepest within the reach this turn's K/V capture walk can get — cleared at that sequence's turn end; MoE gets the same fix GPU without MPP prefill pipelines ──► portable varlen prefill bf16 rows in pieces ──► each piece is evaluated before the next (workspaces no longer overlap) piece = q view at an offset ──► paged reads accept a q view at a whole-head offset (all callers) ``` ## Changes - `qwen3_5` / `qwen3_5_moe` `gdn_prefix.rs`: a refused rung is held in `gdn_unclaimed_rungs: HashMap<Option<SeqId>, Vec<_>>` (key = `active_scheduled_seq`, `None` = serial lane). `hold_refused_rung` keeps at most two per key: the deepest, and the deepest at or below the predicted capture reach. The reach comes from `ColdTierWalk::capture_reach`, which probes the same K/V chain keys and per-turn block budget as `capture_chain` (blocks already on disk are free); with no cold tier only the deepest is held. The capture reads only the finishing sequence's rung; its turn end removes only that entry; `release_scheduled_recurrent_for(seq)` drops a vacated sequence's rung; `clear_reuse_state` drops all. The bound is two extra rungs per live sequence (was: every refused rung of the ladder, held through decode, outside reclaim). Deepest-only failed the e2e on the runner: the harness captures 12 blocks per turn, so the reach (192–768 tokens) was below the deepest rung (1248) and no sidecar was written. - MoE: a refused rung was dropped, so no MoE rung reached the cold tier on such a host; it now follows the dense rule. - `paged_kv_cache_adapter.rs` `portable_prefill_attention`: every bf16 piece but the last is evaluated before the next is built. Measured on 16 pieces: peak growth 293.7 MB → 34.3 MB (one piece's partials 17.0 MB). - `mlx_paged_ops.cpp`: `PagedAttention`, `PagedAttentionVarlen` and `PagedPrefillAttention` accept a row-contiguous `q` at a non-zero offset that is a whole number of heads. Every kernel binds `q` through `CommandEncoder::set_input_array`, which adds `a.offset()`; no host code does pointer math on `q`. Pools, scales, block tables, seq lens, cu_seqlens and workspace keep the zero-offset rule. A copy in the FFI could not work: the alias appears only inside `Contiguous::eval_gpu`. ## Tests - `qwen3_5_cold_tier_restart_parity` under a local runner simulation (portable prefill, 5,010,305,024 B working set, 7 GiB host with 2.5 GiB spare): FAIL before this fix (`boundary_skips=2`, anchored at 0, as CI run 43378257889), PASS after (cached 64 / 304 / 304, `installed=2`, anchored at 304), PASS without the simulation. - `a_refused_rung_within_the_capture_reach_reaches_the_cold_tier` (+ MoE twin), `a_rung_refused_ram_still_reaches_the_cold_tier`, `moe_rung_refused_ram_still_reaches_the_cold_tier`, `overlapped_sequences_each_send_their_refused_rung_to_the_cold_tier` (+ MoE twin), `portable_prefill_pieces_do_not_hold_their_partials_together`, `portable_verify_pieces_at_long_context_attend` (8 rows at 131,072 tokens, piece 2 at offset 14,336), `paged_q_offset_view` (decode v1/v2, varlen v1/v2, int8 tiled, MPP prefill, off-head-boundary refusal). - One mutation per defect, each red when on and green when off, then removed: f1, f2, f3 (now q_offset), f4, H1, q_align, deepest-only. - `cargo +1.100.0 clippy --workspace --all-targets` with warnings denied: clean. Touched modules' tests green. ## Not in this PR - The scheduler sets `active_cache_owner_id` only at admission, so an overlapped sequence's capture can filter by the wrong owner. S13 replaces this capture path. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
Stage S11 of the Splash int8 KV alignment (stack #344). Base: S37 (#373).
Qwen3.5 dense and MoE memory now goes through one process ledger, as in Splash (
MemoryLedger,MemoryGovernor). Every place that allocates takes a claim first. A refused claim frees units in Splash order. If that is not enough, the claim waits, yields its lane or fails. Splash:Engine::prepare,growLane,judge,suspendLane,admit,MemoryGovernor::controlPass.Changes
engine/governor/:ledger(rule, rights, order, holds, accounts),host(SplashHostRule),governor(charged,try_reserve, MLX limit, start gate),allocate(the allocate loop and judge),wait(ResourceWait, 30 s deadline),monitor(500 ms pressure poll),oom,metrics,status.drive_onceis split intoprepare_stepandfinish_step. Each planned row takes its InService claim before the step, in plan order (SplashEngine::prepare). A prefill row claims up totoken_start + num_tokens(SplashworkEndOf). Draft-state growth is a bytes claim under the same request.judge,laneToYield,yieldsBefore). A yielded lane keeps its KV target. It resumes only when its retry time has come and the scheduler is not draining.droppedLease). A scheduled prepare leaves its refusal to the scheduler, which defers it.Cache::setWantedChains) and the resume point (StateCache::resumePoint) are kept from Start claims.StartupRetryWindow), outside the pool-growth lock.max(1 GiB, 2%). Other families keep 15% + 1 GiB (Margin::Unguarded).resource_timeout,capacity_exhaustedandmetal_out_of_memorymap to 503 in/v1/messagesand/v1/responses(Anthropicoverloaded_error, Retry-After 1).memoryGovernorStatus()(napi) and/healthmemory_governor(authenticated body only): accounts, charged, claims, owed, resource waits, TTFT parts (SplashholderOf), decode-gap causes, counters.With stops (S30) and the deferred GDN fold (S14)
Engine::stop→settle→finish(Stop)).Engine::release: a lane or a suspended request gives its memory back).run_paged_turn,run_paged_dspark_turn).Engine::settleends a request that is not in flight at once).Engine::deferEndkeeps the first end), and the serial waits check the cancel before the 30 s limit. A stop never comes back asresource_timeout(503).generatedTokenscounts that token), not the cancel error.metal_out_of_memoryhowever the request ended).Memory plan
The new margin moves the planned windows (load-plan tests, M3 Pro 27 GiB working set):
Margin on this working set (28,991,029,248 B): 2% is 579,820,584 B, below 1 GiB, so the margin is 1,073,741,824 B (was 15% + 1 GiB = 5,422,396,211 B). The window grows by the freed 4.0 GiB of KV.
Deleted
engine::reclaimand the in-order L1-L3 reclaim paths:KvNeed,KvReclaim,DraftReclaim,SchedReclaim,StepNeed,DraftUnits,reclaim_for_blocked_step,try_grow_pool_by,reclaim_keep,ModelReclaim,retry_after_reclaim.grow_paged_pool_for_prompt,ensure_paged_pool_for_prompt,ensure_paged_pool_keeping,free_for_kv,free_for_draft.DraftRefusal,refuse_draft,take_draft_refusals,kv_need_met,last_grow_room.MLX_SCHED_RESERVE_FULL_ISL(code, test comment, docs row).handle_blocked_alone,reclaim_one_idle_scheduled_with,try_grow_reservation_pool,draft_shortfall(qwen4_exp and the other non-ledger families).Tests
RUST_TEST_THREADS=1. The list is inMUTATIONS.md,rf-mut.txt,rb-mut.txt,rb-fix-mut.txt,cx1-mut.txt,r2-mut.txt,r3-mut.txtandMUTATIONS.mdround 4. Examples:resource_timeoutandmetal_out_of_memory→ 503 (TS1, TS4),capacity_exhaustedis not a context error (TS2),memory_governoronly in the authenticated/health(TS3).resource_timeout(FS1 scheduled, SW1 serial), a stop at the first sampled token ends "stop" (FT1), a stopped slice keeps its GPU OOM (OS1).num_tokens+ its draft allowance, SplashEngine::workEndOf): at a block boundary (31 rows written + 1 pending, 16-token blocks, no budget to grow) the row is granted (DC1,a_decode_row_at_a_block_boundary_claims_only_its_rows).try_reserveand the start gate sample again when a reservation retired between the sample and the lock (SplashMemoryGovernor::tryReservereads charged and reserved at one instant): another model's 80 bytes landing in that window refuse a second 80 under a 100-byte limit (E1m,a_reservation_retired_after_the_sample_is_still_charged);an_empty_model_does_not_spend_another_models_host_pass);Runtime::suspend→QwenStateStorage::releaseLane), dense and MoE (R1m,a_suspended_dflash2_lane_drops_its_cells_and_window,moe_suspended_dflash2_lane_drops_its_cells_and_window);Cache::take), so the ledger lists again and the state that shares the block is taken (R2m,a_take_that_frees_nothing_measurable_lists_again).max_new_tokens, repetition cutoff) claims nothing, so a finished request is never refused, suspended or failedcapacity_exhaustedfor a row it never writes (SplashEngine::commitends the lane at that token) (TB1,a_terminal_decode_row_claims_nothing);CompositeStateLayout::laneBytesunder the start claim), and every row, prefill slices included, claims its draft K/V growth (SplashEngine::growLane) (MB1,a_speculative_start_claims_its_draft_state; MP1,an_mtp_prefill_slice_claims_its_draft_growth);paged_step_claimed, dense and MoE: a refused growth waits in place up to 30 s instead of failingcontext_length_exceeded(MA1,mtp_ar_step_waits_for_its_growth);run_paged_turn,run_multimodal_turn, dense and MoE), as SplashNativeRuntime::executionFaileddoes: an OOM MLX reports outside every claim (a DFlash2 verify at the accept's wait, a serial AR sample) fails the turnmetal_out_of_memory:and arms the model reset (WO1,a_verify_oom_outside_the_claim_arms_recovery).Cache::takeReclaim:releaseExtent, thenevictOne+releaseExtent, one extent per take,Phase::DeadLeavesbefore ordinary states). New unitUnitKey::DeadLeaves(FreeNow, stamp 0, afterExtent); the claim's prompt chain and, without certain reuse, the queued chains are kept (SplashWalk::reused/Walk::restored). A critical host pass on a pool of cached chains with no empty extent now cuts it (R3,critical_host_pass_evicts_dead_leaves_to_cut_an_extent);prefill cancelled(SplashEngine::stopsettles a suspended lane in any phase); the wait also checks cancel after its sleep and control pass (R4,a_stop_during_the_replay_completes, AR and DFlash2);metal_out_of_memoryhowever the request ended) (E4,one_rows_oom_fails_the_peer_its_step_completed).metal_out_of_memory:and restarts the model at once, before the next step: resident lanes fail, idle owners, the ladder, the prefix cache and the DFlash2 store reset (SplashNativeRuntime::executionFailedwrapsEngine::tick, admission included) (E7, E7b,a_prefix_preparation_oom_restarts_the_model).cargo fmt --all -- --checkcargo clippy --workspace --all-targets -- -D warningscargo test -p mlx-paged-attn(16 binaries + doctests)--lib(RUST_TEST_THREADS=1)yarn build:nativeindex.d.ctscopied, no changeyarn typecheckandyarn tsc -b --forcevp lint --type-aware --type-check,vp fmt --check(10 touched TS files)vp test __test__/server packages/server packages/lm/__test__git grep MLX_MUTRe-pinned numbers: none. The memory plan windows (221,177 / 112,473 / 155,641) are unchanged by the rebase: S14's pending GDN tape enters only the decode arm of the lane cost, and these windows are priced by the prefill arm.
After the rebase onto S37 (
69c404045):cargo fmt --check,cargo clippy --workspace --all-targets -D warnings,yarn build:native(noindex.d.ctschange),yarn typecheck,tsc -b --forceclean; mlx-core--lib(RUST_TEST_THREADS=1) 4,743 passed, 0 failed;vp testserver, lm and desktop: 2,125 passed, 7 skipped.Round 2 fixes (08048a1):
cargo fmt --check,cargo clippy --workspace --all-targets -D warningsclean; scoped mlx-core--lib(RUST_TEST_THREADS=1):engine::549,models::qwen3_5(with MoE) 565,models::qwen4_exp242,models::qwen3::46,cold_tier::38, all passed, 0 failed; no#[napi]file changed;git grep MLX_MUT0.Round 3 fixes:
cargo fmt --check,cargo clippy --workspace --all-targets -D warningsclean;cargo test -p mlx-paged-attn --lib block_allocator65 passed; scoped mlx-core--lib(RUST_TEST_THREADS=1):engine::550,models::qwen3_5(with MoE) 567,models::qwen4_exp242,models::qwen3::46,cold_tier::38,transformer::paged_kv_cache_adapter186, all passed, 0 failed; no#[napi]file changed;git grep MLX_MUT0.Round 4 fix (E7):
cargo fmt --check,cargo clippy --workspace --all-targets -D warningsclean; scoped mlx-core--lib(RUST_TEST_THREADS=1):engine::551,models::qwen3_5(with MoE) 567,models::qwen4_exp242,models::qwen3::46,cold_tier::38, all passed, 0 failed; no#[napi]file changed;git grep MLX_MUT0.Gaps
No claim is ever Pending yet:
Returningis zero until the SSD state tier lands (S13), so holds never engage in production.Only our own allocation points are claimed. MLX transients inside eval are a plan reserve, not claims.
One process ledger. Units are taken on the caller's model thread, so another model may change room in between. Each model's control pass has its own 1 s settle, so in one second each loaded model's pass may take up to M (Splash's one engine takes it once).
A suspended DFlash2 lane's buffers are dropped, not pooled: the replay allocates a fresh lane (Splash
activatetakes the pooled buffers back).The serial suspend covers AR and DFlash2 decode steps only. A host-refused serial prefill chunk or MTP step waits in place, up to 30 s. Vision turns never suspend.
A refused DFlash2 cycle lookahead decodes that cycle AR (shared driver), where Splash judges the verify rows.
An MTP lane's draft fixed part is reserved at admission and held only to the turn's first forward. mlx-node allocates the verify-time parts (recurrent snapshots, tapes, hidden rows) at the first verify, and from then on they count through
charged; Splash allocates the lane's buffers inside the start claim. A cached-prefix MTP turn, which then declines MTP, over-reserves that part until its first forward.A turn's finalization (
finish_completed→save_paged_history→ GDN checkpoint) is not checked for GPU OOM. Not fixed: no GPU command is committed between a step's last wait andfinish_completed(a decode wave waits on its sampled tokens, a prefill slice ends insynchronize), and the finalization only evaluates views and clones handles. So a failed command's error is raised in the step that ran it, wherenote_gpu_oomsees it, and that step's OOM fails every turn it completed (E4). Only an error MLX reports in a later step stays gap 10. Only a fresh allocation for the finishing request itself could fail there, and that writes nothing a peer reads. A whole turn's finalization is covered by the turn boundary above.Dead leaves for a bytes need (R3) differ from Splash's walk in four ways. (1) They are one unit at stamp 0, so they go before the ladder rungs too (Splash takes
Phase::Checkpointsfirst). (2) Kept and queued chains are matched by tokens, salt and image keys ignored, so a same-token chain on another salt is kept too. (3) The unit's size counts the blocks a state still marks (they free once the state goes, which the ledger lists next); the bound over-counts by the chains of states the claim may not take. (4) A kept block above the cut stops the cut there, though moving it down would let it go lower. A KV need with blocks takes dead leaves in place (allocate), not through this unit.skip_cachehas no trigger: qwen3_5 restores cold chains synchronously, and a restore the pool refuses is already a start without the cache.Accounts are published between drive passes, so a whole turn's live state reads as
fixeduntil it ends.No request priority; the live GDN unit cap stays 2 (S15); the pressure monitor polls every 500 ms.
Other families keep their margin and allocate outside the ledger. They see it only through
set_memory_limit.The full list (25 rows) is in
S11-design.md§16.A GPU OOM that MLX first reports inside
synchronizeis swallowed by the sharedmlx_synchronizeshim (it only prints[MLX] Exception in synchronize), so the ledger never sees it: no row fails and no cache reset runs. Changing that shim touches every family.A recovered GPU OOM still writes a
native_errortrace line, so the desktop supervisor's olderlyingdetector marks the sidecarlyinguntil it restarts (a false alarm).A turn that waits for a memory claim (up to 30 s) is already in S37's turn journal. Splash journals a turn only once it is admitted (
Engine::completeAdmission), so a crash on another lane during that wait can count against the waiting request (S37 gap 13).Not in this PR (live, not run)
MLX_CONTINUOUS_BATCHING=1,--max-memory 22G): G4 gap (max ≤ 10 s, p99 ≤ 5 s), G8 no failure but context, G9 accounts sum to charged and owed = 0, First token, Churn.🤖 Generated with Claude Code