Repository navigation
feat(cache): paged sliding-window KV with prefix reuse at any block boundary - #3334
Merged
Merged
Conversation
This was referenced Nov 24, 2026
inureyes
added a commit
that referenced
this pull request
Nov 24, 2026
## Summary Reduce fused paged-attention execution overhead by avoiding CUDA graph splits caused by counting entire pool slabs, folding Q widening into attention, and creating scale from host data. This removes standalone cast/fill kernels and an intermediate buffer; it does **not** establish fewer arithmetic operations or FLOPs. Dependency tracking and output byte accounting remain intact. Adopt the full change with the owner-approved model-dependent tradeoff (GB10, 8192-token input, B=4): | Model / variant | Decode change | Interpretation | |---|---:|---| | Qwen3 8B, full | +1.16% | All three rounds improve (+0.86%, +1.24%, +1.12%); all six variant samples exceed twelve controls | | Qwen3 8B, budget only | +0.12% | Overlaps controls; no consistent gain | | Qwen3 0.6B, full | -1.16%, rerun -1.36% | Accepted regression; no universal speedup claim | Raw measurements, binary hashes, methodology and limitations are in `docs/benchmark_results/issue-3385-qwen3-8b-gb10-2026-11-24/`. All 144 measured 8B requests completed 3072 tokens and matched control text hashes. Measurements use the retained pre-integration binaries, not a new performance run on latest main. ## Validation and scope - Latest main integrated without changing the six implementation files; focused GB10 CUDA tests: 256 passed, 1 ignored, including fp16/f32-Q byte equality. - Kernel dtype-key and port-dispatch checks and formatting pass. Core clippy passes on the integrated result. - Remote CI is cancelled under the owner's local-validation policy. Metal/HIP execution is unverified; shared Q/scale changes reach beyond CUDA. - This is the isolated optimization from #3334. That draft remains stopped at the sliding-window B=1 gate; #3256, #3257, #3259 and #3250 remain open. Other pool-slab kernels are tracked by #3387. Closes #3385
This was referenced Nov 27, 2026
A scheduler-owned FP16 sequence of a family with sliding layers now lives in the shared paged pool on every layer: full layers are pool-backed KVCaches and sliding layers are the new PagedSlidingKVCache. One backend per sequence, whatever the decode storage setting says. PagedLayerState gains a block base, a window and a retired list. Before each append the pool moves a sliding layer's logical_start to len - (window - 1) and moves head blocks wholly before it out of the live table, so a decode step attends exactly the window and the live table stays within ceil(window / block) + 1 blocks. Retired blocks are released at once except a one-block rewind reserve, which lets the decode lookahead rewind bring the head back; retention for the prompt cache is a pool flag that later commits turn on. Every block-table index goes through block_at / end_block. At B=1 every pool-backed layer gathers its window and runs the dense SDPA; a batched decode step takes the whole-batch paged launch, with the sliding window expressed as the CSR first page offset. Gemma 3 opts in through LanguageModel::supports_paged_sliding_state, and keeps the ring and its snapshots for quantized modes. Tests: block accounting of the settle, retire, reserve and rewind; Gemma 3 paged decode matches the ring past the window, live sliding blocks stay within the bound, and a batched paged step matches each row alone. Refs #3256
The scheduler prompt-cache tests (plan, whole-prompt hit, completion snapshot, model-owned cache, pad trim, lookahead) exercise the snapshot path. Since the previous commit an FP16 Gemma 3 sequence stores its sliding layers as paged blocks and no longer snapshots, so these fixtures now build the wrapper with without_paged_sliding() to keep testing the path they were written for. Refs #3256
… boundaries A paged sliding sequence now goes through the paged prompt-cache path instead of the snapshot path. - Retention: while the prompt cache is on, blocks that leave a sliding window stay pinned on the sequence, capped per layer by the store's byte capacity divided by the pool's sequences; past the cap the oldest unanchored block is released first. The history boundary and the system-prompt root are recorded as anchors, computed by resolve_history_boundary without taking a snapshot. - Donation: donate_finished_sequence_cache takes the paged arm for these sequences; detach_paged builds the dense handles from the layer state, pins the retired blocks too, and the scheduler prunes unanchored retired blocks before the insert. - Lookup: the KV lookup is no longer skipped for this family. A set with sliding layers is adopted by clone at the largest block boundary d whose full layers hold [0, d) and whose sliding layers still hold the blocks covering [d - window, d); the clone sets logical_start = d - window and adopt_paged rebuilds the pool-backed layer state at each layer's length. When no such boundary reaches the minimum prefix while the block-floored match does, the request records sliding_window_evicted. - Release: discarding a detached set releases the allocation reference of its retired blocks as well as its live ones. - Stats: /v1/cache/stats and /metrics report reject_sliding_window_evicted, and /v1/cache/stats reports sliding_retired_blocks and sliding_retired_bytes over live sequences and stored entries. Tested: the stats route test; existing prompt-cache, scheduler and core paged suites. Not yet covered: an end-to-end adopt test on the paged arm (logits against a cold run with the same partition, the evicted negative control), store-level eviction of single retired blocks, block-level truncation, and Gemma 4. Refs #3256
… kernel A pool-backed layer of a scheduler-owned sequence has no dense copy of its keys, so at B=1 every decode step gathered the whole visible range before SDPA. A lone row now goes through paged_single_decode_attention, which takes the fused v2 kernel at any length; the kill switch and the kernel's structural declines still apply and fall back to the gather. The batched entry keeps the batch-size floor. The new tests drive sliding layers whose head blocks have retired and whose window starts mid-page, at B=4 above the batched floor and at B=1 below it, and check every row of every step against attention computed on the host over that row's last window positions. Refs #3256
…floor A window-bounded sliding layer exists only in the pool, so a batched step below the v2 floor gathered every row's window every step. Batches whose layer is windowed on every row now use the fused read at any length; other layers keep the batch-size policy. On gemma-3-1b-it-4bit at four 256-token requests, lowering the floors moved the branch from 14.7% below main to 4.7% above it. Refs #3256
…=4 diagnosis B=1 on gemma-3-1b-it-4bit stays 8% to 15% below main at 256 tokens and 14% to 18% below at 8192 after the fused single-row read, so the B=1 gate still fails. Both B=4 cells now fall inside main's sample range. The B=4 row that diverged is a greedy tie flip after the window crossing, not a window error: logprobs match main bit for bit until decode step 256, paged and ring logits on the tiny fixture differ by at most 7e-7, and the divergence persists with the fused kernel switched off. Its early stop is an end_of_turn token that ignore_eos does not suppress on main either. The bench copy gains BENCH_ALLOW_EARLY_STOP so such a row shortens the measured window instead of aborting the cell. Refs #3256
Keeps the reference helper of the fused sliding tests under the argument limit the core crate lint enforces. Refs #3256
The +4.7% at 256 x 4 came from lifting the floor for every layer, not from the windowed-only change, which measured -3.0% (about four null spreads) and is left unresolved. The logprob deltas after the window crossing are stated as measured, and their attribution to summation order is marked as an inference. Refs #3256
Adds the per-step Nsight breakdown of B=1 decode for main and the branch at 256 and 8192 tokens, with the scripts that produced it, and the gate reruns at commit ea2036e. The bench script gains BENCH_LOGIT_BIAS so the 256 x 4 cell decodes the same context range on both arms. B=4 is at or above main in both cells. B=1 moved from 8% to 18% below main to about 6% below and is still outside the null spread. Refs #3256
The synthetic Gemma 3 fixture uses VOCAB = 8 (valid ids 0..8), while a_batched_paged_decode_matches_each_row_alone generated decode tokens with (step % 37) + 2 and hit token 8 on step 6 row 1. On Metal, out-of-bounds embedding lookups read different buffer memory between single-row and batched takes and diverged. Wrap the decode step tokens modulo VOCAB - 1 so both rows stay in bounds across backends; verified on Metal under both v1 and MLXCEL_PAGED_ATTENTION_V2=1. Refs #3256
scheduler_warmup_boundary_tests landed on main after the earlier scheduler fixture commit and builds tiny_sliding_gemma3() to assert wrapped-ring history-boundary snapshot behavior. Pin that fixture with without_paged_sliding() so it continues exercising the snapshot path it was written for; verified with all 124 scheduler tests passing on Metal. Refs #3256
Enable supports_paged_sliding_state on Gemma4Wrapper and forward it through Gemma4VLModel and Gemma4UnifiedModel so FP16 Gemma 4 sequences store full and sliding layers in the shared PagedBlockPool while keeping KV-shared layers as LayerState::Empty and quantized modes on RotatingKVCache snapshots. Route single-row and batched decode over pool-backed LayerState through the fused paged decode path, wire linear speculative rollback for LayerState::PagedSliding, pin existing ring-snapshot tests to ring storage, and add Gemma 4 paged sliding unit tests. Refs #3256
… paged-sliding tests Add store-level eviction of single retired sliding blocks (unanchored oldest-first before anchored blocks, with deferred pool-pin release via drain_pending_paged_block_releases and CachePool::release_detached_block_ids), allow partial block-aligned prefix matches for paged sliding entries when APC is off, and prevent Engine::sync_sequence_storage from truncating pool-backed LayerState sliding lengths down to visible_len. Add the 32k live-block bound unit test and server-level paged-arm prompt-cache tests for Gemma 3 and Gemma 4 (divergence past ring wrap with cold-partition parity and negative control, cross-session system-prompt reuse, sliding_window_evicted, retained-block release, and anchor-preserving eviction under tight budget). Refs #3256
Update ADR 0010 and CONTINUOUS_BATCHING.md to document window-bounded paged sliding-window storage for FP16 Gemma 3 and Gemma 4, retired-block prompt-cache retention, anchor-aware eviction, and /v1/cache/stats reporting. Refs #3256
inureyes
force-pushed
the
feature/issue-3256-paged-sliding-kv
branch
from
December 1, 2026 18:51
bd13bf7 to
95a2557
Compare
…chors under eviction Protect retired sliding-window blocks required to adopt an entry at its own block-aligned tail floor_to_block(len) from both prune_retired and evict_one_retired_block so non-aligned entries remain adoptable on exact next-turn continuations. Reorder PromptCacheInner::enforce_caps to evict stale whole entries before stripping anchored retired blocks from the remaining active entry, allow PromptCacheStore::insert to trim non-root anchored retired blocks before rejecting a single long entry as oversized, carry forward anchored retired blocks across clone_detached_paged_prefix and set_sliding_anchors, and wire HTTP history-boundary and system-root rendering for paged sliding-window families so multi-turn and cross-session anchors survive tight budgets. Refs #3256
Dividing `store.capacity_bytes()` by the static `max_sequences()` slot table (36+ with queued slots) shrank the per-layer retired sliding block cap on Gemma 4 12B (10 MiB per retired block across 40 sliding layers) to 5 blocks (160 tokens), smaller than a single 1024-token anchor window (32 blocks). Size the per-sequence retired block cap by `active_count().max(1)` instead so a live sequence can retain its system-root and history-boundary anchor windows within the prompt-cache budget, while the store continues enforcing `capacity_bytes` across all retained entries on donation. Refs #3256
Records the gemma-4-12b-it-4bit prompt-cache replay (15/16 hits, 4.28x TTFT speedup) and gemma-3-1b-it-4bit interleaved B=1/B=4 decode throughput measurements on Apple Silicon Metal for #3256.
inureyes
marked this pull request as ready for review
December 1, 2026 20:42
inureyes
added a commit
that referenced
this pull request
Dec 1, 2026
#3334 committed `docs/benchmark_results/paged-sliding-decode-gb10-2026-11-23/gemma3-1b-first-run-partial.jsonl`, a partial raw record stream. `scripts/ci/check_benchmark_raw_logs.py` rejects JSONL under benchmark data, so the `binary assets` job fails on main and on every PR based on it. Nothing references the file; the directory keeps its README and JSON results.
inureyes
added a commit
that referenced
this pull request
Dec 1, 2026
* fix(server): pass swa_full through the diffusing-interval constructor main does not compile since #3658 and #3624 landed together. #3658 threads `swa_full` through `ModelProvider` and passes it to `new_with_full_config_and_diffusing_interval`, while #3624 introduced that constructor without the parameter, so `cargo build` fails with E0425 (`swa_full` not in scope) and E0061 (41 arguments where 40 are expected). Add `swa_full: bool` to the constructor after `context_retention`, where the call from `start` already passes it, and forward it from `new_with_full_config`, which takes it but did not pass it on. The body already uses it. Validated with `cargo build --profile test-fast --features cuda` on Linux (the lib, `mlxcel`, `mlxcel-server`, `mlxcel-bench-decode` and `examples/logit_trace`). * chore(docs): drop a raw JSONL record the binary-assets check rejects #3334 committed `docs/benchmark_results/paged-sliding-decode-gb10-2026-11-23/gemma3-1b-first-run-partial.jsonl`, a partial raw record stream. `scripts/ci/check_benchmark_raw_logs.py` rejects JSONL under benchmark data, so the `binary assets` job fails on main and on every PR based on it. Nothing references the file; the directory keeps its README and JSON results.
This was referenced Dec 1, 2026
inureyes
added a commit
that referenced
this pull request
Dec 2, 2026
Since #3334, FP16 Gemma 3 and Gemma 4 scheduler sequences keep sliding layers in window-bounded paged blocks on every backend. On CUDA the paged single-row decode is slower than the ring storage it replaced: a paged-attention plus merge kernel pair per layer instead of one `sdpa_vector`, and four host arrays per layer per step that land in managed memory and force graph updates. Gemma 4 31B NVFP4 on a B200 decoded at 63.1 tok/s before #3334 and 50 to 51 tok/s at it (pp512/tg128, CUDA graphs on). `mlxcel_core::memory::paged_sliding_state_default()` reads MLXCEL_PAGED_SLIDING and otherwise defaults to on everywhere except CUDA; the Gemma 3 and Gemma 4 wrappers use it, and test builds keep paged storage on so the #3334 tests still run on every backend. Metal is unchanged. With it, current main decodes at 63.3 tok/s on the same measurement. Making the paged path allocation-free and graph-stable on CUDA is tracked by #3667 and #3668. Local validation on CUDA: the paged-sliding and Gemma 3/4 lib tests (168 passed) and the new default-resolution unit test; scripts/ci/check_env_var_docs.py lists the new variable as documented. Closes #3675
inureyes
added a commit
that referenced
this pull request
Dec 2, 2026
ModelOpt leaves `self_attn` in bf16 in exports such as nvidia/Gemma-4-31B-IT-NVFP4, which is more than half of the bytes a decoded token streams. MLXCEL_DENSE_ATTN_QUANT=mxfp8|nvfp4 requantizes the dense text q/k/v/o projections at load and records their layout, and Gemma 4 now resolves attention projections through `quant_params_for`, since an 8-bit group-32 plane has the same packed shape as a 4-bit group-64 one. The dequantize + cuBLASLt prefill path also takes MXFP8. On a B200 (pp512/tg128): bf16 84.2 tok/s decode, MXFP8 87.8, NVFP4 90.6, with prefill 4444, 3658 and 3768 tok/s. Against bf16, the teacher-forced trace changes 0.68% of top-1 choices on decided positions for MXFP8 (none above a gap of 3.1) and 14.9% for NVFP4, so the switch stays opt-in and MXFP8 is the one to use. This also restores the environment-variable rows for the CUDA overlay switches that the rebase conflict resolution dropped, and records the #3334 regression bisect (fixed in #3676) in the report. Local validation: the Gemma 4 and sanitize lib tests (617 passed) including a new parse test, and scripts/ci/check_env_var_docs.py.
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.
Part of #3259
Closes #3256
Summary
Implements window-bounded paged sliding-window KV storage and block-boundary prompt-prefix reuse for FP16 scheduler-owned sliding-window families (Gemma 3 and Gemma 4 text/VL/Unified).
mlxcel-core): AddsPagedLayerState.block_base,window,retired, andanchors,PagedSlidingKVCache, andLayerState::PagedSliding. Sliding layers retire head blocks aslogical_startadvances, keeping live memory bounded byceil(window / block_size) + 1blocks per sliding layer while retaining retired blocks up to the prompt-cache byte budget when the prompt cache is enabled.supports_paged_sliding_state()while keeping quantized KV modes onRotatingKVCacheand ring snapshots. E-series KV-sharedLayerStateKind::Nonelayers allocate zero blocks; Gemma 4 linear speculative rollback works overPagedSlidingwhile tree gather declines cleanly.detach_paged, adopts the largest block boundarydwhose sliding blocks cover[d - window, d)(allowing partial prefix matches even with APC off), inherits anchored retired blocks across continuation turns, protects tail-window boundary blocks from eviction, and enforces 3-tier store eviction (unanchored retired blocks -> stale whole entries -> non-root anchored retired blocks). HTTP routes render history-boundary and system-root prefixes viaHistoryBoundaryRender::SlidingAnchors, and/v1/cache/statsexposessliding_window_evicted,sliding_retired_blocks, andsliding_retired_bytes.paged_single_decode_attentionand skips the v2 batch floor for all-windowed layers. Updatesdocs/adr/0010-scheduler-owned-sequence-state.mdanddocs/CONTINUOUS_BATCHING.md.Validation
--profile test-fast):mlxcel-corecache::paged/paged_v2/cache::layer_state(259+ passed),gemma3/gemma4/prompt_cache/routes::cache/scheduler_paged_sliding(558+ passed, including 32k live-block bound, eviction policy, tail-window protection, and Gemma 3/4 divergence parity with[0, window)negative control),cargo fmt --all -- --check, andcargo clippy --lib --bins --tests -- -D warningsall pass.gemma-4-12b-it-4bit, default 2 GiB budget, Apple Silicon Metal):scripts/bench_prompt_cache_replay.py --edit-target 3achieves 15/16 hits (136,000 / 175,605cached tokens, 77.4%), reducing total TTFT from543.79 scold to127.19 s(4.28x speedup), withreject_sliding_window_evicted = 0andreject_oversized = 0. Session A Turn 8 (edited Turn 3) reuses4,544tokens with cold-identical SHA; Sessions B and C Turn 1 reuse4,512system-root tokens (3.76x–3.80xfaster, cold-identical SHAs).gemma-3-1b-it-4bit, release build, Apple Silicon Metal): B=1256+28.68%, B=18192+6.64%, B=4256+16.08%, B=48192-11.01% (2-slab gather fallback above 1024-block default slab). Full record indocs/benchmark_results/paged-sliding-decode-apple-silicon-2026-12-02.md.gemma-4-12b-it-4bitB=1/B=4 interleaved decode cells and GB10 CUDA re-measurement after rebasing onto#3406+ Wave 0 (prior GB10 CUDA measurements remain indocs/benchmark_results/paged-sliding-decode-gb10-2026-11-23/).