Skip to content

feat: Paged sliding-window KV with prefix reuse at any block boundary #3256

Done

Description

@inureyes

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_tokens keeps head blocks that lie wholly before logical_start allocated. 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), and gather_visible slices the same window (paged.rs:1815).
  • PagedKvLayout has one block_size and per-layer bytes_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.rs variant table).

Proposed Solution

Built on #3254's SchedulerOwned backend and LayerStateKind::Sliding { window }.

  1. Window-bounded sliding storage, one backend per sequence. A SchedulerOwned FP16 sequence of a family with any Sliding layer is pool-backed on every layer, full and sliding, whatever --decode-storage-backend says. The backend is one value per sequence, and CachePool::detach refuses mixed storage, so full layers cannot stay dense while sliding layers are paged. Add a per-layer block-base offset to PagedLayerState, so block_ids can drop head blocks. When logical_start crosses a block boundary, the head block leaves the live sequence. Attention: at B=1, every layer runs gather_visible plus 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_view with first_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.
  2. 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) + 1 blocks 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 at d needs 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 each checkpoint_points position when the interval is on, all resolved by resolve_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 before d beyond that.
  3. Donation and lookup. The KV donation point is donate_finished_sequence_cache (src/server/batch/scheduler/prompt_cache.rs:1571-1821). Add a SchedulerOwned arm there that calls CachePool::detach_paged, and carry the retired list in the resulting DetachedPagedCacheSet (mlxcel-core/src/cache/paged_detach.rs:76). Also make resolve_history_boundary (prompt_cache.rs:732) run for SchedulerOwned families with Sliding layers. Today it returns early unless supports_snapshot_reuse(), and it must still compute the anchors without taking snapshots. Lookup takes the trie's longest match m from lookup_longest_prefix. It reuses the largest block boundary d <= 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 through adopt_paged (copy-on-write on the tail block, as today) and sets each sliding layer's logical_start = max(0, d - window). Lift the ModelOwned bail at prompt_cache.rs:360 for SchedulerOwned.
  4. Truncation is block-level. Reuse at d drops the pins past d. No ring arithmetic is involved, which is what makes edit, regenerate and branch reuse work.
  5. Observability. Add PromptCacheRejectReason::SlidingWindowEvicted ("sliding_window_evicted") for a match cut short because a sliding block was evicted. Add sliding_retired_blocks and sliding_retired_bytes to /v1/cache/stats.
  6. 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_paged and 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_sink must stay unreachable for pool-backed sliding layers (it returns 0 for them today).
  • Edge cases: d < window keeps 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) + 1 per layer, asserted from paged_stats.
  • Real checkpoint on gemma-4-12b-it-4bit at the default prompt-cache budget: scripts/bench_prompt_cache_replay.py --edit-target 3 --verify shows 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 in docs/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_evicted and 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

  1. added
    status:blocked
    type:enhancement
    priority:high
    area:models
    on Nov 22, 2026
  2. added
    area:core
    area:inference
    on Nov 22, 2026
  3. added
    status:ready
    status:in-progress
    status:review
    and removed
    status:blocked
    status:ready
    status:in-progress
    on Nov 23, 2026
  4. 20 remaining items

  5. added
    status:done
    and removed
    status:blocked
    on Dec 1, 2026
  6. added a commit that references this issue on Dec 1, 2026
    5e167c2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:corearea:inferencearea:modelspriority:highstatus:donetype:enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions