Repository navigation
fix(prompt-cache): key completion snapshots by the tokens their state holds - #2139
Merged
Merged
Conversation
… holds Decode forwards a sampled token on the following step, so every finish except a merged-EOS stop leaves the last generated token out of the model state. The completion donation still keyed its entry by `prompt ++ generated`, one token past the per-layer offsets (measured on GB10: Gemma 4, Gemma 3 and Llama 3.2 KV for `length` and stop-string finishes). An exact-entry restore then resumed prefill one position past the restored state. The chat routes rarely reach that entry because turn 2 re-renders the reply, which is why the llama-4-scout comment on #1754 saw no skew; the raw completion routes and the warm-up extend do reach it. `SequenceInfo` gains `eos_terminated`, set at the three merged-EOS sites, and `generated_in_state()`, which drops the unforwarded tail otherwise. The classic decode and finished-in-prefill donations pass it. The speculative burst donations are unchanged; their verify rollback was not measured. `lookahead_params` now keys on the model's natural backend. Under the paged override Gemma 3, AFMoE and Llama 4 were allocated `PagedKvCache` with no per-layer caches, so they pipelined decode while `apply_lookahead_trim` reached none of their state. Their snapshots held one or two extra positions, and single-request Gemma 3 output differed from `MLXCEL_FORCE_SYNC=1`. It now matches byte for byte, at a cost of 84 to 75 tok/s on gemma-3-4b decode. Validated with turn-2 warm vs cold at equal forward widths on gemma-4-12b, gemma-3-4b, qwen3.5-0.8b and llama-3.2-1b: identical tokens and bitwise-equal logprobs after the fix, divergent before. New tiny-Gemma 3 tests compare each stored entry with its snapshot offset. Closes #1754
Closed
5 tasks done
4 tasks done
inureyes
added a commit
that referenced
this pull request
Oct 6, 2026
) ## Summary The scheduler trimmed padded-prefill positions only from the `CachePool` entry's `KVCache`s. A family whose own layout is model-owned keeps its K/V inside the model, so that trim reached nothing and `offset` ran ahead of the real token count; PR #1752 opted Gemma 3, AFMoE and Llama 4 out of padded prefill for that reason. This adds `LanguageModel::trim_sequence_state(seq_id, excess)` and routes all four scheduler pad trims (batched, full, chunked first chunk, continuation) through one helper that trims the pool caches and, for a model-owned layout, calls the hook. A failed rewind aborts the request instead of decoding from a desynchronized offset. - Gemma 3 implements the hook (server) and `trim_internal_caches` (CLI) and takes padded prefill again. `RotatingKVCache::rewind_padded_prefill` also cuts the physical ring back: a plain `trim` leaves the pad keys in the slots the next decode step keeps once a padded chunk outgrows the window. - `deepseek_v4` (pooled compression caches), `bailing_moe_linear` (GLA state), `qwen3_next` (gated-delta state) and `PipelineServerModel` (state behind the pipeline runtime) now answer `supports_padded_prefill() -> false` with the reason. AFMoE and Llama 4 stay opted out; their comments say what lifting it takes. - The trait doc states the model-owned exception. The hook default delegates to `trim_internal_caches` for non-batching models and fails closed for batching ones. - Other behavior changes: new `MLXCEL_FORCE_PADDED_PREFILL` forces tile alignment on any hardware (CLI and server); the server now honors `MLXCEL_NO_PADDED_PREFILL`; `LoadedModel` and the VLM wrapper delegate both trim hooks (`LoadedModel` previously dropped `trim_internal_caches` for every family); the continuation-chunk mask offset falls back to the prefill cursor when the pool entry is empty. ## CUDA reachability (negative result) Model-owned families never reach padded prefill on CUDA today. The only model-owned family with `supports_batched_prefill() == true` is qwen3_5, which declines padding, so the longest-row padded batched site is unreachable for them; the single-sequence sites were hardware-gated with no force override. The forced-alignment env is what makes the path testable here. ## Test plan (GB10, CUDA, release) - [x] New `cache::prefill_rewind` tests (5) and `scheduler_model_owned_pad_trim_tests` (4: full prefill inside and past the window on dense and paged backends, chunked prefill, snapshot reuse after a padded turn). With the Gemma 3 rewind disabled the scheduler tests fail: offset 32 vs 13, 96 vs 37. - [x] `server::batch::scheduler` 178 passed, `block_reclaim` 23, `lookahead` 11, `speculative` 175, `generate::tests` 36, `models::gemma3`, `models::afmoe` 28, `muse_glimmer` 109. Clippy (both crates, `-D warnings`) and fmt clean. - [x] `mlxcel-server` with gemma-3-4b-it-4bit, `--prefill-chunk-size 500`, greedy, prompts of 176, 730 and 1852 tokens (none a multiple of 32, the last past the 1024 window). Forced padding vs unpadded, `--parallel 1` sequential and `--parallel 4` concurrent: the short prompt is identical everywhere; the others diverge only where the top-2 logprobs are equal at the reported resolution (0.25), and unpadded `--parallel 1` vs `--parallel 4` diverge at the same long-prompt position with no padding involved. With the rewind disabled, outputs diverge at token 1 (top-2 gap 1.0 and 1.5) and the 730-token prompt degenerates into repeated `texId`. - [x] `mlxcel generate` with gemma-3-4b-it-4bit, forced padding vs unpadded: identical 40-token output. ## Not verified on this host - The M5 manual check from the issue and Metal numerics of the padded path (no Neural Accelerator here). - `cudaStreamEndCapture` aborts hit about one in four repeated runs of several suites, including the comment-only gemma4 suite; every suite passed on rerun. Follow-up: decode lookahead stays off for model-owned families (#2139). The hook cannot serve that teardown as is, because the rewind requires a chronological buffer and a decode write into a wrapped ring is not one. Closes #1755
inureyes
added a commit
that referenced
this pull request
Oct 6, 2026
PR #2139 gated the decode lookahead off for every model-owned family because the teardown trim reached only CachePool caches. Gemma 3 lost about 10 tok/s on GB10. A plain cursor trim cannot serve it either: once the sliding window wraps, each decode write overwrites the K/V of the position that just left the window. RotatingKVCache gains an opt-in undo log (cache/decode_undo.rs) of its newest single-token writes: the starting cursors, plus a copy of the overwritten [B, H, 1, D] rows once the ring has wrapped. rewind_decode_writes(n) restores those rows newest first and the exact offset and idx, and refuses (cache untouched) under speculative buffering, non-FP16 storage, a disabled log, n > offset, or writes the log no longer holds. Any other mutation clears the log. Row copies are lazy, so the model schedules them in one async_eval right after building each forward (flush_decode_undo_rows); otherwise they would pin the pre-write buffer and stop slice_update from reusing it. LanguageModel gains supports_decode_lookahead_rewind and rewind_decode_appends, delegated through LoadedModel and the VLM wrapper. Gemma 3 opts in when every sliding layer is FP16, logs depth 2 on scheduler sequence caches only (the CLI fallback slot keeps none), and rewinds global layers with KVCache::trim. The scheduler admits a model-owned family to the pipeline only with that capability, including the ModelOwned allocation used at --parallel 1, rewinds it on every teardown, and fails the request with an error when a rewind fails. Refs #2159
inureyes
added a commit
that referenced
this pull request
Oct 6, 2026
) ## Summary Gemma 3 decodes on the lookahead pipeline again, now with a teardown that rewinds its model-owned state exactly, including a sliding window the decode has wrapped. On GB10 the issue's protocol (gemma-3-4b-it-4bit, 200 tokens, default flags) runs at 87.3 tok/s, against 87.6 for the pre-#2139 binary and 76.2 for force-sync, with greedy output byte-identical to `MLXCEL_FORCE_SYNC=1`. - `RotatingKVCache` gets an opt-in undo log (`cache/decode_undo.rs`): per single-token write the starting cursors, plus a copy of the overwritten `[B, H, 1, D]` rows when the write lands on a valid slot inside a `DecodeLookaheadAppendScope` (the scheduler's prime forward). `rewind_decode_writes(n)` restores rows newest first and the exact `offset`/`idx`, and refuses with the cache untouched under speculative buffering, non-FP16 storage, a disabled log, `n > offset`, or a write the log does not cover. Any other mutation clears the log. - `LanguageModel::supports_decode_lookahead_rewind` / `rewind_decode_appends`, delegated in `LoadedModel` and the VLM wrapper. Gemma 3 opts in when every sliding layer is FP16, logs depth 2 on scheduler sequences only (the CLI slot keeps none), and trims global layers with `KVCache::trim`. - Scheduler: `lookahead_params` admits a model-owned family only with that capability, including the `ModelOwned` allocation at `--parallel 1`. `apply_lookahead_trim` calls the rewind before `sync_sequence_storage`; on `Err` it logs, finishes the request with an error (overriding a same-tick `length`/`stop` so nothing is donated), and drops the id from the re-dispatch. The row copies are lazy MLX nodes reading the pre-write buffer. Left unevaluated they pin that buffer, so the write's `slice_update` cannot reuse it in place and copies the whole window every step. Measured on a 1906-token prompt (every write overwrites a valid slot): unflushed 64.5 tok/s, below force-sync; flushed in one `async_eval` per forward 72.4; no copies at all (unsound) 76.9. This also rules out the issue's rejected alternative of retaining pre-write handles: it pins the same buffers. Copies are taken only inside the prime forward, so force-sync and requests the pipeline does not admit pay nothing. ## Measurements (GB10, CUDA, `mlxcel-server`, default flags) Interleaved rounds, rotated order, fresh server per arm and round, median of 3 requests per arm, host-idle gate before each arm (CPU busy < 12%; an ungated first pass on a loaded host showed 40-60 tok/s outliers in both lookahead arms). `null` is a byte-identical copy of the `new` binary, `ref` is `12601f86` (pre-#2139), `base` is `0ee13dfe`. | 200 tokens, short prompt (n=4) | new | null | ref | sync | base | |---|---|---|---|---|---| | median tok/s | 87.3 | 87.2 | 87.6 | 76.2 | 75.7 | | paired new vs arm | | -0.2 to +0.6% | -1.1 to -0.2% | +13.8 to +16.7% | +13.1 to +23.1% | | 200 tokens after a 1906-token prompt, window wrapped (n=4) | new | null | ref | sync | base | |---|---|---|---|---|---| | median tok/s | 72.7 | 72.9 | 77.1 | 67.3 | 67.4 | | paired new vs arm | | -0.5 to +0.7% | -6.2 to -5.3% | +7.8 to +8.9% | +7.1 to +15.7% | The issue's bar (within 3% of 84.1-84.5) is met with margin, and the null arm puts the method's floor under 1%. Past the window the restored pipeline costs 5.7% against the pre-#2139 binary: that is the price of the row copies plus their extra `async_eval`, which the unsound `ref` never paid (its output differs there). It is still 8% faster than sync. Llama 3.2 1B (dense KV, gated, n=4): new 270.4, null 268.0, base 270.0, sync 210.0 tok/s; paired new vs base -0.3 to +0.5%; identical output in every arm. ## Correctness - Server, Gemma 3 4B, greedy, every round: short, the 1906-token prompt, and 4 concurrent requests give identical md5 for new, null, sync and base at `--parallel 4` (default) and at `--parallel 1`. `ref` differs on the long and concurrent requests (the #1754 desync). Concurrent requests are queued behind a long blocker prefill so both arms see the same batch history; without that, force-sync alone produced two different outputs across runs. - `scheduler_model_owned_lookahead_tests` (new) uses the pad-trim fixture (one sliding, one global layer), not the `scheduler_model_owned_cache_tests.rs:75` fixture the issue names: that fixture's `sliding_window_pattern: 1` makes its only layer a `Cache::Standard`, so it cannot wrap. A real Gemma 3 with a window of 8 runs pipelined and force-sync in lockstep, single sequence (`ModelOwned` allocation) and four concurrent (paged override), with an admission teardown and two-position finish teardowns after the wrap. At every tick without a live lookahead the offsets, cursor, whole sliding buffer and live global K/V are bit-equal, and tokens match. With the row restore removed both tests fail. Also: the capability gate (INT8 sliding layer stays sync), the trait default, and the error path. - `cache::decode_undo_tests`: rewinds of one and two writes after the wrap, across the cursor rollover, after an over-window prefill, across the warmup boundary, refusals untouched, scope behaviour. - `model_owned_sequence_never_primes_the_decode_lookahead` is replaced by `model_owned_sequence_primes_the_decode_lookahead_only_with_a_rewind`; the #1754 `length`, one-token and EOS snapshot tests pass unchanged on the pipelined path. ## Test plan - [x] `mlxcel-core` `cache::` (556), `server::batch` (495), `models::gemma3`, `vision::` pass with `--test-threads=1` under `gpu-lock` - [x] `cargo clippy --release --features cuda --lib --tests -- -D warnings` (both crates) and `cargo fmt --check` - [x] GB10 server runs above ## Not verified on this host - Metal: the row copy and flush were measured on CUDA only. - The branch is based on `0ee13dfe`; `e466f511` (#2162, CUDA SDPA switch) landed after and was not rebuilt here. Closes #2159
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
The premise holds. A completion-origin donation keyed its entry by
prompt ++ generated, but decode forwards a sampled token only on the next step. Every finish except a merged-EOS stop therefore leaves the last generated token out of the state. Donations now store only the tokens the state consumed (SequenceInfo::generated_in_state), and a second defect that pushed Gemma 3's state the other way is fixed.Why the llama-4-scout comment saw no skew
The chat routes re-render the assistant turn for the next request, so
prompt ++ generatedis usually not a prefix of turn 2. That comment's restore used the 1822-token warm-up entry, not the 1817-token completion entry. The raw completion routes do reach the completion entry exactly. The warm-up extend restores the longest snapshot and forwards only the delta, so it inherits any skew in the snapshot it starts from.Measured at capture (per-layer offset vs. entry tokens, GB10)
length(Gemma 4, Gemma 3 chunked, Llama 3.2 KV)stopstring (Gemma 4, Gemma 3)eos_terminatedset, offset == entry)length, default flags (Gemma 3)Gemma 3 lookahead
lookahead_paramsgated on the allocated backend. Under the paged override a model-owned family is allocatedPagedKvCachewith an empty cache vector, so Gemma 3 (and, by code reading, AFMoE and Llama 4) pipelined decode whileapply_lookahead_trimcould reach none of its state. The gate now keys on the model's natural backend. Single-request Gemma 3 output under default flags differed fromMLXCEL_FORCE_SYNC=1before the fix; it is now byte-identical (same md5). Lookahead is bit-exact against force-sync on Llama 3.2 (KV), so the difference came from the untrimmed appends. Cost: Gemma 3 4B decode drops from 84.1-84.5 to 74.1-75.2 tok/s (n=4 each, 200 tokens). A sequence-aware trim hook (#1755) could re-enable the pipeline.Real-checkpoint validation
Protocol: turn 1 on
/v1/completions, then turn 2 = turn 1 + reply + suffix. Warm turn 2 runs in the same process (exact completion-entry restore); cold turn 2 runs in a fresh process. Both arms use--prefill-chunk-size 1, so forward width cannot differ. The pre-fix arm is the same binary with the old behavior toggled.lengthstoplength/stoplengthlength(--parallel 1 --apc-block-size 1)Tests:
scheduler_completion_snapshot_tests(tiny Gemma 3) checks the stored entry's token count against the offset its snapshot carries for alengthfinish over decode steps, for the one-decoded-token boundary (finish inside prefill) and for an EOS stop. It also checks that a decoding model-owned sequence never gets lookahead params. Three of the four fail with the old behavior. The scheduler suites pass, and clippy and fmt are clean.Not verified on this host
Closes #1754