Repository navigation
Description
Part of #3259
Depends on #3254
Problem / Background
Sliding-window families keep each sliding layer as a model-owned RotatingKVCache ring. Once the ring wraps, logical token t is no longer at slot t (RotatingKVCacheSnapshotState::can_truncate_to, used through kv_snapshot::rotating_truncatable_to, src/models/kv_snapshot.rs:437), so a stored state can be reused only when the new prompt extends it exactly. Measured on GB10 with mlxcel-server 0.8.1, gemma-4-12b-it-4bit, fp16 KV and about 5.8k-token prompts: an exact continuation reuses 5808/5823 tokens, but an edit, a regenerate, or a new chat with the same system prompt reuses nothing (snapshot_diverged). Qwen3, with scheduler-owned paged KV, reuses up to the divergence point. The --swa-full refusal (src/cli/context_args.rs:145) already names the cause: save and restore over SWA layers are gated on the caches being scheduler-owned.
Memory per token in gemma-4-12b-it (40 sliding layers with 8 KV heads x 256, 8 full layers with 1 KV head x 512, K and V both stored) is 320 KiB sliding and 16 KiB full:
| Context | Sliding ring (window 1024) | Full-size sliding | Full-attention KV |
|---|---|---|---|
| 8k | 320 MiB | 2.5 GiB | 128 MiB |
| 32k | 320 MiB | 10 GiB | 512 MiB |
| 128k | 320 MiB | 40 GiB | 2 GiB |
Keeping every sliding token (--swa-full, #3257) is therefore not a default. vLLM's hybrid KV cache manager (design doc docs/design/hybrid_kv_cache_manager.md, written at vLLM commit 458e74, lists gpt-oss, Gemma 2/3 and Ministral) allocates sliding layers per block, frees blocks that leave the window, and treats a prefix as a hit when the last sliding_window - 1 tokens are still cached. It intersects that with the full-attention hit and evicts freed blocks through one LRU.
Current Behavior
- Paged state already tracks a front window:
PagedLayerState.logical_start.PagedBlockPool::trim_tokenskeeps head blocks that lie wholly beforelogical_startallocated. Its comment says reclaiming them "needs a block-base offset and is deferred until a sliding-window paged path exists" (src/lib/mlxcel-core/src/cache/paged.rs:980-987). - The paged batched decode kernel already serves a contiguous
[logical_start, len)window as a CSR range (src/lib/mlxcel-core/src/cache/paged_batch_decode.rs:54-73), andgather_visibleslices the same window (paged.rs:1815). PagedKvLayouthas oneblock_sizeand per-layerbytes_per_block(paged.rs:53).- The default prefix store, a radix trie over tokens, holds paged entries as block pins and shares them through
CachePool::adopt_paged(src/server/batch/scheduler/prompt_cache.rs:469,:622;src/server/prompt_cache/entry.rs:40). APC (ApcConfig,policy.rs:408) is off by default. - Int8 and Turbo sequences are never pool-backed (
paged_batch_decode.rsvariant table).
Proposed Solution
Built on #3254's SchedulerOwned backend and LayerStateKind::Sliding { window }.
- Window-bounded sliding storage, one backend per sequence. A
SchedulerOwnedFP16 sequence of a family with anySlidinglayer is pool-backed on every layer, full and sliding, whatever--decode-storage-backendsays. The backend is one value per sequence, andCachePool::detachrefuses mixed storage, so full layers cannot stay dense while sliding layers are paged. Add a per-layer block-base offset toPagedLayerState, soblock_idscan drop head blocks. Whenlogical_startcrosses a block boundary, the head block leaves the live sequence. Attention: at B=1, every layer runsgather_visibleplus dense SDPA (the gather route the variant table already uses below the token floor). At B>1, the CSR paged kernel runs (build_paged_csr_viewwithfirst_page_offset). If any B=1 no-regression cell (acceptance below) falls outside the null spread, stop and report the numbers in the PR. Do not merge it as the default, and do not add a flag to hide the regression. - Retired blocks go to the prompt cache, not the free list. With the prompt cache enabled, a block that leaves the window moves to the sequence's retired list with its pin held. With it disabled, the block is released at once. Live memory per sequence stays bounded by
ceil(window / block_size) + 1blocks per sliding layer. Retired bytes count against the prompt-cache byte budget (PromptCacheConfig::capacity_bytes, default 2 GiB), never against live pool capacity. That budget holds about 6.5k tokens of gemma-4-12b sliding blocks (320 KiB per token), so retention needs a policy. A hit atdneeds only the sliding blocks covering[d - window, d). Blocks inside the window before an anchor point are anchored: the system-root length, each history boundary, and eachcheckpoint_pointsposition when the interval is on, all resolved byresolve_history_boundary. Under budget pressure, evict unanchored retired blocks first, oldest first, then whole entries by the store's existing LRU. Retention cost is about one window (320 MiB on gemma-4-12b) per anchor, shared by refcount across entries and sessions. Reuse is therefore at any block boundary while the budget allows, and at the nearest anchor at or beforedbeyond that. - Donation and lookup. The KV donation point is
donate_finished_sequence_cache(src/server/batch/scheduler/prompt_cache.rs:1571-1821). Add aSchedulerOwnedarm there that callsCachePool::detach_paged, and carry the retired list in the resultingDetachedPagedCacheSet(mlxcel-core/src/cache/paged_detach.rs:76). Also makeresolve_history_boundary(prompt_cache.rs:732) run forSchedulerOwnedfamilies withSlidinglayers. Today it returns early unlesssupports_snapshot_reuse(), and it must still compute the anchors without taking snapshots. Lookup takes the trie's longest matchmfromlookup_longest_prefix. It reuses the largest block boundaryd <= whole_prompt_reuse_cap(m)for which every full-layer block of[0, d)and every sliding block covering[d - window, d)is pinned. Adoption shares those blocks throughadopt_paged(copy-on-write on the tail block, as today) and sets each sliding layer'slogical_start = max(0, d - window). Lift theModelOwnedbail atprompt_cache.rs:360forSchedulerOwned. - Truncation is block-level. Reuse at
ddrops the pins pastd. No ring arithmetic is involved, which is what makes edit, regenerate and branch reuse work. - Observability. Add
PromptCacheRejectReason::SlidingWindowEvicted("sliding_window_evicted") for a match cut short because a sliding block was evicted. Addsliding_retired_blocksandsliding_retired_bytesto/v1/cache/stats. - Families. Gemma 3 (migrated in refactor: Generalize prompt-cache state ownership from models to the scheduler #3254) and Gemma 4 text, VL and Unified (migrated here onto
SchedulerOwned). Gemma 4 snapshots stop being used for these families once they are paged.supports_snapshot_reuse()stays true only for non-FP16 modes, until feat: support quantized KV cache modes in model-state snapshots for prompt-cache reuse #3250 is re-evaluated against this layer. Other rotating families follow the refactor: Generalize prompt-cache state ownership from models to the scheduler #3254 follow-ups.
Rejected alternatives: extending APC instead of the default trie store, because APC is off by default and would leave the default path unfixed. A wrap-aware ring snapshot, because truncating a wrapped ring is impossible without the retired tokens, which is the same storage as this design.
Scope
In scope: cache/paged.rs (block-base offset, retired list), CachePool sliding allocation, the store's paged entry and lookup rule, prompt_cache/metrics.rs, routes/cache.rs, Gemma 4 migration, and tests.
Out of scope: quantized sliding blocks (#3250), --swa-full (#3257), other rotating families, and recurrent checkpoints (#3255).
Implementation Notes
- Reuse:
logical_start,gather_visible,build_paged_csr_view(cache/paged_csr.rs:224),adopt_pagedand the store's paged pin release (drain_pending_paged_releases). Do not add a second block pool. - Constraints: the window must stay contiguous (
paged_batch_decode.rs:67-73).trim_front_keep_sinkmust stay unreachable for pool-backed sliding layers (it returns 0 for them today). - Edge cases:
d < windowkeeps every sliding block from 0. KV-shared layers allocate nothing. A multimodal request keeps the whole-entry rule (feat(core): shared snapshot serialization for KVCache / RotatingKVCache / ChunkedKVCache so Gemma 3, AFMoE and Llama 4 join exact-prefix prompt-cache reuse #1335). A sequence preempted mid-prefill releases its retired list. Speculative and MTP verify (gemma4_verify_rows.rs) run on pool-backed sliding layers or fall back to dense for that request, stated in the PR. - Errors: a pin that is missing at adoption (a race with eviction) releases the sequence and falls back to the longest still-pinned
d, or to a cold prefill.
Acceptance Criteria
- On a tiny Gemma 3 and a tiny Gemma 4 fixture (window 32, block 16), a request that diverges at token d, after the ring has wrapped, reports
cached_tokens >= floor_to_block(d) - block_size. Its decoded logits equal a cold run with the same prefill partition (qwen4_exp: chained prompt-cache hits diverge materially from a cold prefill #2974 and fix(prompt-cache): restoring a completion snapshot diverges from a cold prefill #3040 rules). Negative control: restoring sliding blocks for[0, window)instead of[d - window, d)fails the test. - Two sessions with the same 2k-token system prompt and different questions: the second reports
cached_tokens >= floor_to_block(system_len) - block_size, on the tiny fixture and on gemma-4-12b-it-4bit at the default 2 GiB budget (anchored root). - Live memory per sequence on a 32k prompt: sliding blocks held by the live sequence stay at or below
ceil(window / block_size) + 1per layer, asserted frompaged_stats. - Real checkpoint on gemma-4-12b-it-4bit at the default prompt-cache budget:
scripts/bench_prompt_cache_replay.py --edit-target 3 --verifyshows the edited turn reusing at least up to the previous history boundary, and up to the edit when the budget allows. Outputs equal cold reruns. Record it indocs/benchmark_results/. - Eviction policy test: with a budget below one sequence's retired blocks, unanchored blocks are evicted before anchored ones, and a hit at an anchor still succeeds.
- No decode regression: B=1 and B=4 decode tok/s on gemma-3-1b-it-4bit and gemma-4-12b-it-4bit at 256 and 8192 tokens, interleaved with a null arm, every cell within the null spread.
-
sliding_window_evictedand the retired-block stats appear in/v1/cache/stats, with a test.
Implement this in one PR, run the verification block once at the end, and keep pushes to a minimum.
Verification
make test-fast FILTER=paged
make test-fast FILTER=prompt_cache
make test-fast FILTER=gemma4
make engine-parity MODEL=models/gemma-4-12b-it-4bit PARITY_ARGS=--expect-identical
make verify-test # macOS; on Linux/NVIDIA: make verify-test-cuda
Activity
20 remaining items
docs(bench): state the windowed-floor and divergence results as measured
docs(bench): record the B=1 decode profile and the gate after its fixes
docs(bench): name the script that summarizes the B=1 profile
test(gemma3): keep batched paged decode tokens within fixture vocab
test(server): pin warmup boundary sliding fixture to ring storage
feat(gemma4): opt FP16 Gemma 4 into paged sliding-window KV storage
feat(prompt-cache): add store-level retired-block eviction and server…
docs: document paged sliding-window storage and retired-block retention
fix(prompt-cache): protect tail-window blocks and preserve sliding an…
fix(prompt-cache): size retired sliding block cap by active sequences
docs(bench): record Apple Silicon Metal validation for paged sliding KV
feat(cache): paged sliding-window KV with prefix reuse at any block b…