Repository navigation
Conversation
Deadsg
pushed a commit
to Deadsg/llama.cpp
that referenced
this pull request
Dec 19, 2023
fix "missing 1 required positional argument: 'min_keep'"
phuongncn
pushed a commit
to phuongncn/llama.cpp-gx10-dgx-sparks-deepseekv4
that referenced
this pull request
Apr 28, 2026
Co-authored-by: Iwan Kawrakow <[email protected]>
Defilan
added a commit
to Defilan/llama.cpp
that referenced
this pull request
Aug 4, 2026
Wires the pieces together, so MoE prompt processing for a TQ3_1S/TQ4_1S model runs the rotated matmul instead of staging every expert tensor as f16. The getter cases and the rotate orchestration land in one commit on purpose: either alone runs the rotated matmul against an unrotated activation and returns silently wrong numbers. Flow when tq_rotate is set: 1. force staging, so d_Y is ctx->prealloc_y and never aliases src1 2. contiguous f32 copy src1 -> prealloc_y 3. barrier, then tq_rotate_act in place on prealloc_y 4. mul_mm_id reads the rotated f32 copy against centroid*scale weights Details that have to agree or the result is quietly wrong: - `tq_rotate` requires `mmp != nullptr && !x_non_contig`, i.e. that the TQ pipeline was really selected. On the f16 dequant fallback the weights are true weights and must NOT see a rotated activation. - Staging is forced even for a contiguous f32 src1. Otherwise y_f32_kernel is true, qy_needs_dequant is false, and d_Y aliases the graph's own tensor -- the hazard Metal's in-place rotate/un-rotate has to work around. The "not implemented" assert is relaxed for exactly this case. - effective_src1_type and y_sz both switch to f32, matching what the rotate writes. The staging pipeline is an f32 cpy, not the usual f16 one: the butterfly is 5 rounds of adds and f16 would lose precision quantization did not. - The prealloc_y reuse cache is keyed on the ROTATE pipeline pointer rather than the cpy pipeline. prealloc_y now holds rotated data, so a later non-rotated consumer of the same src1 must not reuse it; keying this way forces a re-stage for anyone else. - Only the ne11*ne12*ne13 rows the copy wrote are rotated; the padded_n rows above ne11 are left alone, as in the f16 staging path. - ggml_vk_get_mul_mat_mat_id_pipeline() ends in GGML_ASSERT(support_fp32acc), so listing TQ in its switch would ABORT on a coopmat2 device, where these pipelines are deliberately not created. It now returns nullptr when both acc variants are empty, falling back to the f16 dequant path. Not yet done: the maxStorageBufferRange gate in supports_op still rejects large expert tensors on the old premise that prompt processing must stage them as f16. With this path that premise no longer holds, but relaxing it is a separate commit pending review of ggml-org#264. Assisted-by: Claude
satindergrewal
added a commit
to satindergrewal/llama.cpp
that referenced
this pull request
Aug 12, 2026
…ed by 8 rows; gap 2.91x -> 2.60x The Q-block increment from the champion transfer list: simd group s owns query row tgpig.x*nsg + s; each KV block's K and V tiles are staged ONCE into threadgroup memory by all threads cooperatively and read by every row -- the per-token global traffic that made paged prefill a bandwidth problem is now amortized across 8 rows. Barriers are per BLOCK and threadgroup-uniform by construction (bounds derive from tgpig only); per-row token loops inside a staged block may diverge, which is safe because no barrier lives inside them. Tail rows past n_tokens_total CLAMP instead of returning -- a non-uniform early return would deadlock the staging barriers. Cross-seq packs (rare boundary) fall back to the proven per-row unshared walk, so correctness is exact everywhere. nsg swept, every point 12/12-gated BEFORE its wall (ms, 1,523-token prefill): 2 -> 3,565 4 -> 3,078 8 -> 2,940 16 -> 3,247 Turnover at 16; 8 ships. The sweep also caught a real defect class: nsg lives in THREE coupled places (kargs, nth, grid divisor) and changing one produced a kernel where half the rows were never computed -- caught by the gate, wall discarded as invalid. DURABLE (n=3, one binary, answers IDENTICAL, results/metal-qblock-gate-* + baseline-1645): prefill 2,936-2,948 ms vs static 1,131-1,140 = 2.60x (was 2.91x; scalar start 6.1x) decode 63.2-63.4 tok/s unchanged (1.60x off static) Credits: Q-block/tile structure from llama.cpp's own kernel_flash_attn_ext (ggml-metal.metal, Georgi Gaessler/ggml authors); staged-tile pattern cross-checked against MLX steel_attention.h (Apple, MIT); wide-tile amortization principle measured independently in antirez/ds4 PR ggml-org#264; block-granular gather from vLLM PagedAttention. Co-Authored-By: Claude Fable 5 <[email protected]>
ckti
pushed a commit
to ckti/llama.cpp-consolidated
that referenced
this pull request
Aug 22, 2026
vulkan : add mul_mat_vec_id for the TurboQuant weight types
ckti
pushed a commit
to ckti/llama.cpp-consolidated
that referenced
this pull request
Aug 22, 2026
Wires the pieces together, so MoE prompt processing for a TQ3_1S/TQ4_1S model runs the rotated matmul instead of staging every expert tensor as f16. The getter cases and the rotate orchestration land in one commit on purpose: either alone runs the rotated matmul against an unrotated activation and returns silently wrong numbers. Flow when tq_rotate is set: 1. force staging, so d_Y is ctx->prealloc_y and never aliases src1 2. contiguous f32 copy src1 -> prealloc_y 3. barrier, then tq_rotate_act in place on prealloc_y 4. mul_mm_id reads the rotated f32 copy against centroid*scale weights Details that have to agree or the result is quietly wrong: - `tq_rotate` requires `mmp != nullptr && !x_non_contig`, i.e. that the TQ pipeline was really selected. On the f16 dequant fallback the weights are true weights and must NOT see a rotated activation. - Staging is forced even for a contiguous f32 src1. Otherwise y_f32_kernel is true, qy_needs_dequant is false, and d_Y aliases the graph's own tensor -- the hazard Metal's in-place rotate/un-rotate has to work around. The "not implemented" assert is relaxed for exactly this case. - effective_src1_type and y_sz both switch to f32, matching what the rotate writes. The staging pipeline is an f32 cpy, not the usual f16 one: the butterfly is 5 rounds of adds and f16 would lose precision quantization did not. - The prealloc_y reuse cache is keyed on the ROTATE pipeline pointer rather than the cpy pipeline. prealloc_y now holds rotated data, so a later non-rotated consumer of the same src1 must not reuse it; keying this way forces a re-stage for anyone else. - Only the ne11*ne12*ne13 rows the copy wrote are rotated; the padded_n rows above ne11 are left alone, as in the f16 staging path. - ggml_vk_get_mul_mat_mat_id_pipeline() ends in GGML_ASSERT(support_fp32acc), so listing TQ in its switch would ABORT on a coopmat2 device, where these pipelines are deliberately not created. It now returns nullptr when both acc variants are empty, falling back to the f16 dequant path. Not yet done: the maxStorageBufferRange gate in supports_op still rejects large expert tensors on the old premise that prompt processing must stage them as f16. With this path that premise no longer holds, but relaxing it is a separate commit pending review of ggml-org#264. Assisted-by: Claude
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Nov 1, 2026
…W (Goal A) and an attendance POOL (Goal B), both opt-in Goals A and B of TODO ggml-org#118, promoted from the `wip/kv-residency` campaign. This block is the delivery's "the KV does not have to be O(-c) of VRAM" work: TWO opt-in placements of the same cache, and each one is byte-identical to a build without it when its knob is unset. * the WINDOW (`LLAMA_KV_RESIDENT_CELLS=<cells>|auto`): the newest W cells stay in VRAM, everything older spills to pinned system RAM in the SAME VA reservation -- a positional window, no kernel or op change; * the POOL (`LLAMA_KV_REGION_POOL=<cells>`): the authoritative copy of the WHOLE context in a pinned host mirror, and a compact device pool of the pages a decode step actually attends to, which the QSA sparse read resolves through a page table (`GGML_OP_KV_POOL`). They are mutually exclusive by construction (the pool declines while a window is active) and they answer the same question from opposite ends: the window keeps the *newest* cells hot, the pool keeps the *attended* cells hot. Both report `is_streaming()`, so a streamed cache takes the sparse QSA decode arm (B2, below). ========================================================================== PART 1 -- the WINDOW (Goal A, promoted in r178) ========================================================================== Goal A of TODO ggml-org#118, promoted from the `wip/kv-residency` campaign. WHAT IT DOES. The KV cache's VRAM cost becomes a WINDOW of the newest `W` cells instead of `-c` cells: one VA reservation (a CUDA/HIP VMM region) holds the whole cache, the window's cells are backed by VRAM and everything below them by pinned system RAM. `set_rows`, the in-place rope shift, `state_write/read`, the kq mask and the FA kernels keep addressing one contiguous range, so no kernel and no op changes. The window slides with the watermark in whole map units, so a remap happens once per few thousand tokens and the apparatus itself is free (a zero-spill arm measures the same as plain). WHY. (a) A context that OOMs today runs: 27B Q8_0 `-c 262144` (8704 MiB of KV) now runs on one 32 GiB card at 128 MiB VRAM + 8576 MiB pinned host for the KV. (b) With host-resident MoE experts, the VRAM the KV does not need *yet* goes to the expert-cache arena: measured at `-c 262144`, `-n 2000`, `-ncmoe` = the model's full layer count, 51 433-token prompt, W at or above the run's depth = **+2.2 to +2.9 GiB of arena** (+3.9 to +6.7 points of residency) for free -- 122B-A10B Q4_K_XL +3.8 % decode and +4.7 % prefill, 35B-A3B Q8_0 -0.9 % decode and +3 % prefill; a `W` 35 k cells BELOW the run depth costs 11-26 % (the spill is read every token). OPT-IN, AND ONLY WHEN ASKED FOR. `LLAMA_KV_RESIDENT_CELLS=<cells>` (a number) or `=auto` (`--fit` sizes it, and only spills a context the user pinned with `-c`); unset/0 = no window. With no window the KV takes the PLAIN device buffer, so a run without the knob is byte-identical to a build without this block -- including its OOM (verified). `LLAMA_KV_SPILL_RAM_PCT` (85 % of MemAvailable) caps the pinned spill and widens the window rather than being OOM-killed; `LLAMA_KV_REGION=0` disables the provider; `LLAMA_KV_REGION_QUARANTINE=0` and `LLAMA_KV_REGION_DEBUG/TRACE/CANARY/DUMP` are the diagnosis switches. PURITY (the window). A spilled KV is numerically transparent: prefill-logit **KLD -0.000000 / 100.000 %** on a spilling 27B arm and -0.000000 / 99.994 % on a spilling Flash-Next (two KV caches: the attention KV and the QSA indexer), text byte-identical on 27B (f16 and q8_0), 4B, 35B-A3B and Flash-Next, and the state paths, the context-checkpoint path and the MTP verify widths all green on arms that provably spill. Two driver hazards are held: a kind flip zeroes a neighbouring live host mapping unless the released physical is held across the create (`LLAMA_KV_REGION_QUARANTINE`, default on -- `=0` reproduces the corruption), and every tensor in a windowed region is placed on the driver's map granularity so a slide step coincides with a mapping. An idle-slot park is REFUSED on a region-backed cache (the server then saves the slot to the prompt cache and clears it, which is byte-identical to the parking gate's reference) because a park moves cells above the region's mapped watermark through the copy engine, which faults the GPU. FIT. `--fit` sizes and reports the window (`auto`), or honours and reports a numeric `W`: the resident/spill split, the VRAM saved, and the per-token read cost at the model's full context from the backend's calibrated link rate. The fit identifies the KV's bytes by the region buffer TYPE, and its measurement context is a `no_alloc` probe that declines a window -- so the probe takes the region buffer explicitly (`llama_kv_region_set_probe`); without that the fit cannot see the KV, reports an over-budget config and aborts instead of sizing the window (the r178 regression). GATES (1 GPU, gfx1201): default path byte-identical (`5ba44647188f`) and still OOMs; VMM selftest PASS and FAIL with the hold disabled; windowed arms 305 `e2cea6fa6670` = plain at W=1024/2048/4096 (spilling at 1024: 128 MiB host), `QUARANTINE=0` -> 325 `fb65430049e9` (the hazard); `--fit` sizes `auto` (96680 of 262144 cells, 3210 MiB resident) and reports a numeric W; `gate-ckpt-reuse.sh` / `gate-state-pipe.sh` / MTP verify widths on spilling arms; `test-backend-ops -o FLASH_ATTN_QSA` 26/26; `check-gpu-faults.sh` clean. Not in this block: the campaign's Goal B (a sparse attended set) and Goal C (the MTP drafter ring, `LLAMA_SPEC_DRAFT_WINDOW`) -- both remain campaign work -- and A1 (the superseded two-base FA read). Records: `wip/kv-residency/A2-MIXED-BACKING.md` (§3.7.9, §3.7.11), `HANDOVER.md`. MULTI-DEVICE `--fit` (r181): the KV-region glue is now safe on a Meta (tensor-split) device, and `auto`'s decision reaches the cache as a decision. r178 made default `--fit` abort on ANY `-sm tensor` run with more than one device: the fit's KV probes and the cache's own region lookups call `ggml_backend_dev_backend_reg(dev)` and hand it to `ggml_backend_reg_get_proc_address`, and a Meta device has no backend reg (`device->reg == NULL`), so `GGML_ASSERT(reg)` fired at model load. Three paths asserted: the fit probe (any run), the runtime buft lookup (a numeric W), and the spill budget/link lookups (a numeric W below `-c`). The window is one VMM region per device and a tensor split has no per-device region buffer type, so the backend simply has no answer there -- which is now what it says: a null reg reads as "not provided", the window is declined with one message naming the tensor split (fit and cache), and the KV stays fully resident. A resolved-to-child reg in the fit (the same Meta->simple-device walk the split accounting already does) keeps the identification exact if a multi-device window ever exists. Three wiring defects in the same code, all visible on ONE device: - `auto`'s "no window needed" decision (0) was indistinguishable from "nobody decided", so the cache warned "--fit did not run" immediately after the fit had decided exactly that. `llama_kv_region_set_resident_cells` now records that a decision was made (`llama_kv_region_resident_cells_decided`), and a decided 0 is silent. - every run without the knob logged "the windowed KV is unavailable for this cache (no spilled cells)". That message now only fires when a window was actually requested and declined for a real reason. - the pinned-RAM ceiling clamp could raise W past the VRAM budget and then be reported as "does not make this fit either". It is now only taken while the wider window still meets the VRAM target; otherwise the fit says the ceiling cannot be served at this `-c` and drops the window (which the fit then fits by reducing the context). That ordering is not cosmetic: an intermediate form of this fix accepted a 235 GiB pinned spill plan for a 4B at `-c 8388608`, and creating it OOM-killed the test box. GATES (the window, gfx1201): `--fit on` (default) at 2 and 3 devices, `-sm tensor`, with no knob / a numeric W / `auto`, fit on and off: no assert, tokens produced, exactly one message per requested window. `-sm layer` 2 devices and 1 GPU still take the window per device (numeric W), and `auto` still sizes the 27B Q8_0 `-c 262144` q8_0 arm identically (123265 of 262144 cells, 4092.8 MiB resident / 4611.2 MiB spilling). One device, no knob: no KV message at all. Purity unchanged: plain vs a SPILLING windowed arm prefill-logit KLD 0.000000 / 99.990 % (q8_0 KV), greedy text byte-identical on that arm; 35B-A3B (1 GPU and 2-GPU `-sm tensor`), dense 27B and the canonical 27B Q8_0 prefill-logit gate (0.000000 / 100.000 %) byte-identical to r180; MTP Protocol A unchanged (tensor acceptance 0.60816 = 1937/3185, plain == draft-mtp); no GPU faults. ========================================================================== PART 2 -- the ATTENDANCE POOL (Goal B, promoted in r190) ========================================================================== The attention KV lives twice: its AUTHORITATIVE copy in a pinned host MIRROR (cell-indexed, so the writers, state_write/state_read, the K-shift, defrag and seq_park all work on it unchanged -- the writer rule) and a compact DEVICE POOL of pages of one indexer block (compress_ratio cells) with a page table block -> slot and its inverse. A decode step resolves its top-k selection through the table and fills the pages it missed from the mirror; the QSA reader gathers K/V at the pool slots while the mask stays cell-indexed. LLAMA_KV_REGION_POOL=<cells>, unset/0 = off = byte-identical. Contents. - ggml/src/ggml-cuda/kv-pool.{cu,cuh}: GGML_OP_KV_POOL. MARK sets use[slot] = epoch for every page this launch reads AND every page the batch just wrote (the graph's k_idxs), and queues the written ones for re-fill; CLAIM takes a slot for each DISTINCT missing block (the table CAS is the dedupe) and never takes a slot MARK protected; MAP+FILL writes each selected cell's pool position into the reader's K/V id list and copies the claimed and dirty pages from the mirror, K and V sharing slots. The epoch is a device counter incremented once per launch: the graph bakes pointers, never counters, and nothing is allocated per launch. - ggml-cuda.cu: the pool's pinned host mirror buffer type -- a DEVICE buffer type whose allocation is pinned host memory (`ROCm_Host` reports is_host, which would send the KV's writers and the FA read to the CPU on a discrete device), and its proc-address entry. - llama-kv-cache: the eligibility, the per-layer pool tensors (pool_k/pool_v, tbl, inv, use, one shared counter block), the resolve wiring into the QSA id list, kv_pool_serves() (a batch too wide for the pool takes the cell-indexed path), the teardown accounting (LLAMA_KV_POOL_STATS takes a PATH: a line on stderr sits inside the generated text), and memory_breakdown() charging the mirror to the host bucket so `--fit` does not reserve it as VRAM. - llama-memory-hybrid-idx / llama-memory-hybrid / llama-memory: the second id list (the K/V gather follows the page table while the mask stays cell-indexed), the flag threading, and the pool's byte accounting for `--fit` (llama_get_kv_pool_bytes()). - models/qwen4exp.cpp: a pooled cache reports is_streaming() and the sparse arm uses the pool's id list; the MTP draft's own cache is never pooled (its attention is dense). - llama-context / the async state copies: the mirror's buffer type is accepted by the batched save and restore (its bytes are host memory, staged through the pinned state_stage). - common/fit.cpp + src/llama-ext.h: the pool's split in --fit's arithmetic and report (the mirror is pinned host RAM, the pool is VRAM), and no context-reduction interpolation while the pool is active -- the pool's VRAM is fixed, so reducing -c frees nothing and the interpolation would divide by a near-zero bytes-per-context delta. Invariants, each one caught by the greedy text. 1. MARK then CLAIM: a claim must never evict a page the same launch reads. Without MARK the round-robin victim could be a page another row still needs (the text diverged ~400 chars in, and a pool larger than the whole cache hid it completely). 2. Claim ATTEMPTS are not distinct blocks: a slot per id attempt wrapped the cursor within one 4-row batch, so two blocks shared a slot and a just-resolved block went unresident. The table CAS dedupes first, so only distinct blocks consume a slot and kv_pool_serves() bounds the distinct count. 3. No transient scratch in a captured graph: the fill list lived in a ggml_cuda_pool_alloc that is freed at the end of the op, and a captured graph bakes the pointer, so a replay wrote into whatever op had been handed that block ("values verify clean, text differs run to run"). It lives in the counters tensor. 4. The mirror is AUTHORITATIVE: the writers land in it and a declared page is re-filled from it before the attention reads it, so an eviction costs nothing and nothing has to be invalidated -- except by a path that rewrites cells in place without going through the writers (the K-shift, a state restore), which calls kv_pool_invalidate(). 5. Eligibility is narrow on purpose: one stream, non-MLA, K and V both present, !v_trans, a uniform compress_ratio and cell geometry, no window active, a device-offloaded cache, and only the trunk context of a qwen4exp model. Anything else declines with one message and the KV is unchanged. 6. The pool is floored at one decode band's worth of blocks (8 x ceil(width/page) pages) so a verify batch cannot exhaust the slot budget, and the mirror is bounded at creation by LLAMA_KV_SPILL_RAM_PCT (it is pinned, non-swappable RAM) -- over the ceiling the pool is declined loudly instead of being OOM-killed. Measured (Flash-Next GSQ-IQ3_XXS, 1 GPU, -ncmoe 48, q8_0, the PLE flags, arms interleaved in one batch, -n 512, MTP depth 4; t/s and tokens/step): depth (ctx) dense sparse pool (204 MiB) text (-n 64) 5 298 (16 384) 72.09 71.58 71.27 pool == sparse: 332 chars dd1981213373 102 899 (131 072) 59.10 54.70 54.65 (5.3k / 51 475 references; dense differs) 180 035 (196 608) 48.94 43.16 43.41 pool == sparse: 861 chars 263c7f2be4d9 The pool lands ON the sparse ceiling at every depth (+0.5 / +0.6 / +0.58 %), so its placement is free and what remains against a resident KV (-7 % / -11 %) is the sparse decode arm's own indexer cost (block 11), not the KV's storage. A 204 MiB pool replaces the resident attention KV's 1 632 MiB at 103k / 2 448 MiB at 180k, and the freed VRAM goes to the expert arena: 103k plain decode, -n 2000, 23 579.8 -> 25 018.6 MiB (+1 438.8 MiB, +18 slots/table), expert hit 96.26 -> 97.02 %, cold reads 42.0 -> 31.6 GiB. The pool's own cost is 0.10-0.11 ms/token (mark/claim/map+fill) with fills 0.03-0.05 ms/step at 92-99 % hits, which is why a better page policy (LRU / F-LRU / a heat prior) is measured dead at this shape. Full numbers and the three-depth table: ../wip/kv-residency/BA-POOL-DESIGN.md §7-§8. PURITY (the pool). Greedy text pool == the resident sparse arm at 5.3k (332 dd1981213373), 51 475 depth (854 43b30de151b9) and 180k (861 263c7f2be4d9), with the dense arm differing as documented (GREEDY-PURITY §45/§63); LLAMA_KV_POOL_VERIFY=1 0 mismatches on every arm; gate-prefill-logits --ab "LLAMA_KV_REGION_POOL=..." 0.000000 / 100.000 % on the pool arm (base PPL 2.9225, bit-identical to the campaign's own base); gate-park-idle-slots, gate-ckpt-reuse and gate-state-pipe PASS on a pooled cache (the mirror is authoritative, which is what makes them trivial); test-backend-ops -o FLASH_ATTN_QSA pass; no GPU faults; and `--fit` accepts the arms that only fit with the pool (-ncmoe 21/22 at -c 262144: refused without it, accepted with it; -fitp moves 3 264 MiB from the device row to Host). ========================================================================== PART 3 -- a STREAMED cache takes the sparse decode arm (B2) ========================================================================== A cache that is streaming at the depth it reads -- a window the used extent has passed, or a pool -- takes the sparse QSA decode arm; a resident cache keeps the dense one. llama_kv_cache::is_streaming() plus the qwen4exp arm policy, LLAMA_QSA_DENSE_DECODE_STREAM=0 to restore the old behaviour. Measured on a spilled KV (Flash-Next IQ3_XXS, -ncmoe 48, q8_0, 1 GPU, -n 400, 2 reps): +34.3 % at 102 899 depth (23.42 -> 31.43 t/s) and +47.3 % at 180 035 (16.51 -> 24.31); a resident cache byte-identical (853 77a40bf40be1). This is a decode-ARM choice, i.e. a different attention regime (like GREEDY-PURITY §45/§63), so a streamed arm's text differs from the old dense-arm text by construction and a resident arm is the oracle. ========================================================================== DEFAULT OFF, for both placements ========================================================================== Neither knob is a speed feature on a config whose KV fits: the window costs the depth below W (11-26 %) and the pool costs the sparse-vs-dense gap (-7 % at 103k, -11 % at 180k). They are FITTABILITY features -- they turn an OOM into a run and they hand the freed VRAM to the expert arena -- so both are opt-in and both stay byte-identical, including the OOM, with their knobs unset. Do not "fix" the defaults. Goal C (the MTP drafter ring, TODO ggml-org#121) joins the same block -- it is the same claim applied to the draft context, and its default follows the delivery's own rule because it measures positive. `LLAMA_SPEC_DRAFT_WINDOW` gives the MTP draft context a sliding window instead of a `-c`-sized KV: unset or `auto` is the adaptive policy (a quarter of the context, clamped to [32768, 65536] cells), `0` is off (byte-identical to a build without it) and `N` is a cell count. The drafter reads its last few thousand tokens, so a window at or above that is free and one far below it costs 7-9 % of decode; the clamps keep it above that band, and the target verifies every token it proposes, so a truncated draft can only be slower. The ring is the shipped reclaim in `llama_kv_cache::find_slot` (`n_swa`), not a new allocator, and the derived kq mask stays valid -- its predicate compares each cell's POSITION, so a recycled cell reports its new one. The VRAM win needed one more piece: an embedded MTP head has no GGUF of its own, so the slab's draft reserve was the flat 3584 MiB and the freed VRAM never reached the expert arena. For an embedded MTP head with an active window the reserve is now derived from the model's own metadata with the weights zeroed (they are the target's) and the KV sized by the window: aux 3.50 -> 0.76 GiB, i.e. the arena gains ~2.8 GiB. A separate MTP draft GGUF (qwen4exp/Flash-Next) and an un-windowed run keep the flat constant exactly as before, and a declined arena preflight now re-evaluates when the smaller real value arrives instead of latching on the load-time estimate. Measured (1 GPU; one R9700; `-n 2000`/`-n 3000`; static depth 3; interleaved): * 35B-A3B Q8_0 `-ncmoe 48 -c 262144` q8_0 KV, 51 433-token prompt: arena 20 910 -> 23 715 MiB (residency 64.1 -> 72.7 %), decode 111.2 -> 113.7 t/s at `-n 3000` (+2.2 %; +2.8-4.9 % at `-n 2000`), prefill +3.4 %, drafts byte-for-byte the same count (1995/3011) -- the window truncates nothing the drafter used. * dense 27B UD-Q4_K_XL `-c 102400`, MTP Protocol A `-n 3000`, reasoning-pinned: layer 71.9 -> 72.1, tensor 72.6 -> 72.5 (neutral), acceptance 2083/2747 identical in all four arms. * target greedy text byte-identical across off/auto/4096, and plain == draft-mtp == draft-mtp(W=512) at `-c 16384` with a 5256-token prompt and 3000 generated tokens (10 158 chars, sha 99b267e8dc3e), i.e. no wrong answer under constant cell reuse. * gates on a windowed draft: `gate-park-idle-slots.sh` (35B, -ncmoe 48, `-c 65536`: 3 park moves, park == lazyoff), `gate-ckpt-reuse.sh` (4B, `-c 131072`: draft cache 33280 of 131072), `gate-state-pipe.sh` (35B, `-c 65536`: all five arms) -- all PASS with `MTP draft KV window = 32768 cells` in their logs. r194 corner fixes (found by a configuration battery against Flash-Next after r193): * LLAMA_KV_REGION_POOL is capped at the cache's own cell count. =1000000 on a 262144-cell context used to take a 12451 MiB device pool of 250000 pages where only 65536 blocks exist (never claimed, arena -4 GiB); it is now 3264 MiB / 65536 pages, and a small context clamps the same way. * the draft KV window sizes only the reserve of the cache it actually windows. A separate -md MTP head (Flash-Next) keeps its full -c cache, but the reserve was derived with the window: 921 MiB where the honest number is 1566 (kv 217 vs 862) at -c 262144, the under-charge direction. Embedded heads (qwen3.5/3.6/3.8) are unchanged (776 MiB on the 35B). The VRAM cliff at -c 262144 is documented (not code): the 768 MiB default headroom is one hipBLASLt workspace short for the first prefill, GGML_CUDA_SLAB_HEADROOM_MIB=1536 is 3/3 requests clean. Amendment (TODO ggml-org#129's sibling): `-nkvo` declines the window, and the streamed arm keys on the placement. The window is a DEVICE region plus a pinned host tail, but its guard did not test `offload`: with `-nkvo` the per-layer buffer is chosen inside `if (offload)` and stays plain pageable host memory, while the plan block still logged "WINDOWED KV ENABLED", reserved pinned-RAM spill budget and left `kv_resident_cells` set. `is_streaming()` then keyed the streamed (sparse) decode arm on that plan -- qwen4exp consumes it -- for a KV with no region at all. Measured: `-nkvo LLAMA_KV_RESIDENT_CELLS=64` built a plain `CPU KV buffer` of the whole context while announcing a 64-cell VRAM window. The window now declines once, with the reason (the pool already declines on `!offload`), so `-nkvo` means "no streamed placement"; `is_streaming()` tests `kv_region`, the placement actually taken, which also covers a device cache whose region buft the backend refused. Text is unchanged in every arm (the decline is a no-op: `-nkvo` + window already read as `-nkvo` alone). Amendment (issue ggml-org#264): the draft window is PER SEQUENCE, and under `--kv-unified` its cell count is `(win + one batch) x n_seq_max`. A unified cache holds every sequence in ONE stream, so the r193 sizing (`win + n_ubatch` cells) was shared by all of them: once the first sequence had filled its window the tail was all the room left, the tail is where that sequence's own ring writes, and a second sequence's first batch had no contiguous run to be placed in -- `find_slot` refused, and every request on that slot answered `decode() failed: failed to process speculative batch` (HTTP 500) while the drafter ran. Reported on `--kv-unified -np 2` with a 65 536-cell window at `-c 262144` after slot 0 held ~100k tokens; reproduced here with a forced 8192-cell window. A per-stream cache (no `--kv-unified`) already sized each stream separately and is unchanged. `llama_spec_draft_kv_cells()` is now the one geometry function -- the cache (`create_memory`), the slab's draft reserve estimate and the "is a window active" test in `common` all call it, so the reserve can never under-charge an allocation. It grants `win` per sequence plus one placeable batch (`(win + n_ubatch) * n_seq_max`, capped at the context), and DECLINES the window when that does not fit the context per sequence rather than lowering it to `per_seq - n_ubatch`: a window that small saves one batch of cells per sequence and masks the drafter's newest cells to do it. `llama_spec_draft_window_cells()` stays the policy (it is the per-sequence window). n_seq_max == 1 -- every `llama-cli`/`llama-bench` run -- measures exactly what it did (cells 1536 for a 1024-cell window at `-c 8192`), so no single-sequence arm changes at all. Measured (dense 27B, 1 GPU, `-np 2 --kv-unified`): the issue's scenario now answers both slots, and `scripts/gate-spec-draft-window.sh` (new) drives 6 requests over 2 slots with a 1024-cell window -- both rings wrapping, prompts full re-prefilled by swapping them between slots -- with output byte-identical to `LLAMA_SPEC_DRAFT_WINDOW=0` on every step and draft acceptance identical (17/36, 23/23). Greedy text `plain == draft-mtp == draft-mtp(W=1024) == draft-mtp(W=0)` (876 chars, sha 8c8fd395402f) at `-c 16384`. And the reserve now charges a per-STREAM (no `--kv-unified`) draft cache for every stream it allocates: `n_seq_max x` the per-stream cell count. Before, a multi-slot windowed MTP server without `--kv-unified` (35B-A3B `-ncmoe 40 -np 2 -c 8192`, window 1024: 2 x 1536 = 3072 cells allocated, 1536 charged) under-charged the slab's aux reserve by one stream's window -- the direction the reserve header calls dangerous. Measured: 3072 cells reported on both the unified and the per-stream arm now.
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Nov 1, 2026
…W (Goal A) and an attendance POOL (Goal B), both opt-in Goals A and B of TODO ggml-org#118, promoted from the `wip/kv-residency` campaign. This block is the delivery's "the KV does not have to be O(-c) of VRAM" work: TWO opt-in placements of the same cache, and each one is byte-identical to a build without it when its knob is unset. * the WINDOW (`LLAMA_KV_RESIDENT_CELLS=<cells>|auto`): the newest W cells stay in VRAM, everything older spills to pinned system RAM in the SAME VA reservation -- a positional window, no kernel or op change; * the POOL (`LLAMA_KV_REGION_POOL=<cells>`): the authoritative copy of the WHOLE context in a pinned host mirror, and a compact device pool of the pages a decode step actually attends to, which the QSA sparse read resolves through a page table (`GGML_OP_KV_POOL`). They are mutually exclusive by construction (the pool declines while a window is active) and they answer the same question from opposite ends: the window keeps the *newest* cells hot, the pool keeps the *attended* cells hot. Both report `is_streaming()`, so a streamed cache takes the sparse QSA decode arm (B2, below). ========================================================================== PART 1 -- the WINDOW (Goal A, promoted in r178) ========================================================================== Goal A of TODO ggml-org#118, promoted from the `wip/kv-residency` campaign. WHAT IT DOES. The KV cache's VRAM cost becomes a WINDOW of the newest `W` cells instead of `-c` cells: one VA reservation (a CUDA/HIP VMM region) holds the whole cache, the window's cells are backed by VRAM and everything below them by pinned system RAM. `set_rows`, the in-place rope shift, `state_write/read`, the kq mask and the FA kernels keep addressing one contiguous range, so no kernel and no op changes. The window slides with the watermark in whole map units, so a remap happens once per few thousand tokens and the apparatus itself is free (a zero-spill arm measures the same as plain). WHY. (a) A context that OOMs today runs: 27B Q8_0 `-c 262144` (8704 MiB of KV) now runs on one 32 GiB card at 128 MiB VRAM + 8576 MiB pinned host for the KV. (b) With host-resident MoE experts, the VRAM the KV does not need *yet* goes to the expert-cache arena: measured at `-c 262144`, `-n 2000`, `-ncmoe` = the model's full layer count, 51 433-token prompt, W at or above the run's depth = **+2.2 to +2.9 GiB of arena** (+3.9 to +6.7 points of residency) for free -- 122B-A10B Q4_K_XL +3.8 % decode and +4.7 % prefill, 35B-A3B Q8_0 -0.9 % decode and +3 % prefill; a `W` 35 k cells BELOW the run depth costs 11-26 % (the spill is read every token). OPT-IN, AND ONLY WHEN ASKED FOR. `LLAMA_KV_RESIDENT_CELLS=<cells>` (a number) or `=auto` (`--fit` sizes it, and only spills a context the user pinned with `-c`); unset/0 = no window. With no window the KV takes the PLAIN device buffer, so a run without the knob is byte-identical to a build without this block -- including its OOM (verified). `LLAMA_KV_SPILL_RAM_PCT` (85 % of MemAvailable) caps the pinned spill and widens the window rather than being OOM-killed; `LLAMA_KV_REGION=0` disables the provider; `LLAMA_KV_REGION_QUARANTINE=0` and `LLAMA_KV_REGION_DEBUG/TRACE/CANARY/DUMP` are the diagnosis switches. PURITY (the window). A spilled KV is numerically transparent: prefill-logit **KLD -0.000000 / 100.000 %** on a spilling 27B arm and -0.000000 / 99.994 % on a spilling Flash-Next (two KV caches: the attention KV and the QSA indexer), text byte-identical on 27B (f16 and q8_0), 4B, 35B-A3B and Flash-Next, and the state paths, the context-checkpoint path and the MTP verify widths all green on arms that provably spill. Two driver hazards are held: a kind flip zeroes a neighbouring live host mapping unless the released physical is held across the create (`LLAMA_KV_REGION_QUARANTINE`, default on -- `=0` reproduces the corruption), and every tensor in a windowed region is placed on the driver's map granularity so a slide step coincides with a mapping. An idle-slot park is REFUSED on a region-backed cache (the server then saves the slot to the prompt cache and clears it, which is byte-identical to the parking gate's reference) because a park moves cells above the region's mapped watermark through the copy engine, which faults the GPU. FIT. `--fit` sizes and reports the window (`auto`), or honours and reports a numeric `W`: the resident/spill split, the VRAM saved, and the per-token read cost at the model's full context from the backend's calibrated link rate. The fit identifies the KV's bytes by the region buffer TYPE, and its measurement context is a `no_alloc` probe that declines a window -- so the probe takes the region buffer explicitly (`llama_kv_region_set_probe`); without that the fit cannot see the KV, reports an over-budget config and aborts instead of sizing the window (the r178 regression). GATES (1 GPU, gfx1201): default path byte-identical (`5ba44647188f`) and still OOMs; VMM selftest PASS and FAIL with the hold disabled; windowed arms 305 `e2cea6fa6670` = plain at W=1024/2048/4096 (spilling at 1024: 128 MiB host), `QUARANTINE=0` -> 325 `fb65430049e9` (the hazard); `--fit` sizes `auto` (96680 of 262144 cells, 3210 MiB resident) and reports a numeric W; `gate-ckpt-reuse.sh` / `gate-state-pipe.sh` / MTP verify widths on spilling arms; `test-backend-ops -o FLASH_ATTN_QSA` 26/26; `check-gpu-faults.sh` clean. Not in this block: the campaign's Goal B (a sparse attended set) and Goal C (the MTP drafter ring, `LLAMA_SPEC_DRAFT_WINDOW`) -- both remain campaign work -- and A1 (the superseded two-base FA read). Records: `wip/kv-residency/A2-MIXED-BACKING.md` (§3.7.9, §3.7.11), `HANDOVER.md`. MULTI-DEVICE `--fit` (r181): the KV-region glue is now safe on a Meta (tensor-split) device, and `auto`'s decision reaches the cache as a decision. r178 made default `--fit` abort on ANY `-sm tensor` run with more than one device: the fit's KV probes and the cache's own region lookups call `ggml_backend_dev_backend_reg(dev)` and hand it to `ggml_backend_reg_get_proc_address`, and a Meta device has no backend reg (`device->reg == NULL`), so `GGML_ASSERT(reg)` fired at model load. Three paths asserted: the fit probe (any run), the runtime buft lookup (a numeric W), and the spill budget/link lookups (a numeric W below `-c`). The window is one VMM region per device and a tensor split has no per-device region buffer type, so the backend simply has no answer there -- which is now what it says: a null reg reads as "not provided", the window is declined with one message naming the tensor split (fit and cache), and the KV stays fully resident. A resolved-to-child reg in the fit (the same Meta->simple-device walk the split accounting already does) keeps the identification exact if a multi-device window ever exists. Three wiring defects in the same code, all visible on ONE device: - `auto`'s "no window needed" decision (0) was indistinguishable from "nobody decided", so the cache warned "--fit did not run" immediately after the fit had decided exactly that. `llama_kv_region_set_resident_cells` now records that a decision was made (`llama_kv_region_resident_cells_decided`), and a decided 0 is silent. - every run without the knob logged "the windowed KV is unavailable for this cache (no spilled cells)". That message now only fires when a window was actually requested and declined for a real reason. - the pinned-RAM ceiling clamp could raise W past the VRAM budget and then be reported as "does not make this fit either". It is now only taken while the wider window still meets the VRAM target; otherwise the fit says the ceiling cannot be served at this `-c` and drops the window (which the fit then fits by reducing the context). That ordering is not cosmetic: an intermediate form of this fix accepted a 235 GiB pinned spill plan for a 4B at `-c 8388608`, and creating it OOM-killed the test box. GATES (the window, gfx1201): `--fit on` (default) at 2 and 3 devices, `-sm tensor`, with no knob / a numeric W / `auto`, fit on and off: no assert, tokens produced, exactly one message per requested window. `-sm layer` 2 devices and 1 GPU still take the window per device (numeric W), and `auto` still sizes the 27B Q8_0 `-c 262144` q8_0 arm identically (123265 of 262144 cells, 4092.8 MiB resident / 4611.2 MiB spilling). One device, no knob: no KV message at all. Purity unchanged: plain vs a SPILLING windowed arm prefill-logit KLD 0.000000 / 99.990 % (q8_0 KV), greedy text byte-identical on that arm; 35B-A3B (1 GPU and 2-GPU `-sm tensor`), dense 27B and the canonical 27B Q8_0 prefill-logit gate (0.000000 / 100.000 %) byte-identical to r180; MTP Protocol A unchanged (tensor acceptance 0.60816 = 1937/3185, plain == draft-mtp); no GPU faults. ========================================================================== PART 2 -- the ATTENDANCE POOL (Goal B, promoted in r190) ========================================================================== The attention KV lives twice: its AUTHORITATIVE copy in a pinned host MIRROR (cell-indexed, so the writers, state_write/state_read, the K-shift, defrag and seq_park all work on it unchanged -- the writer rule) and a compact DEVICE POOL of pages of one indexer block (compress_ratio cells) with a page table block -> slot and its inverse. A decode step resolves its top-k selection through the table and fills the pages it missed from the mirror; the QSA reader gathers K/V at the pool slots while the mask stays cell-indexed. LLAMA_KV_REGION_POOL=<cells>, unset/0 = off = byte-identical. Contents. - ggml/src/ggml-cuda/kv-pool.{cu,cuh}: GGML_OP_KV_POOL. MARK sets use[slot] = epoch for every page this launch reads AND every page the batch just wrote (the graph's k_idxs), and queues the written ones for re-fill; CLAIM takes a slot for each DISTINCT missing block (the table CAS is the dedupe) and never takes a slot MARK protected; MAP+FILL writes each selected cell's pool position into the reader's K/V id list and copies the claimed and dirty pages from the mirror, K and V sharing slots. The epoch is a device counter incremented once per launch: the graph bakes pointers, never counters, and nothing is allocated per launch. - ggml-cuda.cu: the pool's pinned host mirror buffer type -- a DEVICE buffer type whose allocation is pinned host memory (`ROCm_Host` reports is_host, which would send the KV's writers and the FA read to the CPU on a discrete device), and its proc-address entry. - llama-kv-cache: the eligibility, the per-layer pool tensors (pool_k/pool_v, tbl, inv, use, one shared counter block), the resolve wiring into the QSA id list, kv_pool_serves() (a batch too wide for the pool takes the cell-indexed path), the teardown accounting (LLAMA_KV_POOL_STATS takes a PATH: a line on stderr sits inside the generated text), and memory_breakdown() charging the mirror to the host bucket so `--fit` does not reserve it as VRAM. - llama-memory-hybrid-idx / llama-memory-hybrid / llama-memory: the second id list (the K/V gather follows the page table while the mask stays cell-indexed), the flag threading, and the pool's byte accounting for `--fit` (llama_get_kv_pool_bytes()). - models/qwen4exp.cpp: a pooled cache reports is_streaming() and the sparse arm uses the pool's id list; the MTP draft's own cache is never pooled (its attention is dense). - llama-context / the async state copies: the mirror's buffer type is accepted by the batched save and restore (its bytes are host memory, staged through the pinned state_stage). - common/fit.cpp + src/llama-ext.h: the pool's split in --fit's arithmetic and report (the mirror is pinned host RAM, the pool is VRAM), and no context-reduction interpolation while the pool is active -- the pool's VRAM is fixed, so reducing -c frees nothing and the interpolation would divide by a near-zero bytes-per-context delta. Invariants, each one caught by the greedy text. 1. MARK then CLAIM: a claim must never evict a page the same launch reads. Without MARK the round-robin victim could be a page another row still needs (the text diverged ~400 chars in, and a pool larger than the whole cache hid it completely). 2. Claim ATTEMPTS are not distinct blocks: a slot per id attempt wrapped the cursor within one 4-row batch, so two blocks shared a slot and a just-resolved block went unresident. The table CAS dedupes first, so only distinct blocks consume a slot and kv_pool_serves() bounds the distinct count. 3. No transient scratch in a captured graph: the fill list lived in a ggml_cuda_pool_alloc that is freed at the end of the op, and a captured graph bakes the pointer, so a replay wrote into whatever op had been handed that block ("values verify clean, text differs run to run"). It lives in the counters tensor. 4. The mirror is AUTHORITATIVE: the writers land in it and a declared page is re-filled from it before the attention reads it, so an eviction costs nothing and nothing has to be invalidated -- except by a path that rewrites cells in place without going through the writers (the K-shift, a state restore), which calls kv_pool_invalidate(). 5. Eligibility is narrow on purpose: one stream, non-MLA, K and V both present, !v_trans, a uniform compress_ratio and cell geometry, no window active, a device-offloaded cache, and only the trunk context of a qwen4exp model. Anything else declines with one message and the KV is unchanged. 6. The pool is floored at one decode band's worth of blocks (8 x ceil(width/page) pages) so a verify batch cannot exhaust the slot budget, and the mirror is bounded at creation by LLAMA_KV_SPILL_RAM_PCT (it is pinned, non-swappable RAM) -- over the ceiling the pool is declined loudly instead of being OOM-killed. Measured (Flash-Next GSQ-IQ3_XXS, 1 GPU, -ncmoe 48, q8_0, the PLE flags, arms interleaved in one batch, -n 512, MTP depth 4; t/s and tokens/step): depth (ctx) dense sparse pool (204 MiB) text (-n 64) 5 298 (16 384) 72.09 71.58 71.27 pool == sparse: 332 chars dd1981213373 102 899 (131 072) 59.10 54.70 54.65 (5.3k / 51 475 references; dense differs) 180 035 (196 608) 48.94 43.16 43.41 pool == sparse: 861 chars 263c7f2be4d9 The pool lands ON the sparse ceiling at every depth (+0.5 / +0.6 / +0.58 %), so its placement is free and what remains against a resident KV (-7 % / -11 %) is the sparse decode arm's own indexer cost (block 11), not the KV's storage. A 204 MiB pool replaces the resident attention KV's 1 632 MiB at 103k / 2 448 MiB at 180k, and the freed VRAM goes to the expert arena: 103k plain decode, -n 2000, 23 579.8 -> 25 018.6 MiB (+1 438.8 MiB, +18 slots/table), expert hit 96.26 -> 97.02 %, cold reads 42.0 -> 31.6 GiB. The pool's own cost is 0.10-0.11 ms/token (mark/claim/map+fill) with fills 0.03-0.05 ms/step at 92-99 % hits, which is why a better page policy (LRU / F-LRU / a heat prior) is measured dead at this shape. Full numbers and the three-depth table: ../wip/kv-residency/BA-POOL-DESIGN.md §7-§8. PURITY (the pool). Greedy text pool == the resident sparse arm at 5.3k (332 dd1981213373), 51 475 depth (854 43b30de151b9) and 180k (861 263c7f2be4d9), with the dense arm differing as documented (GREEDY-PURITY §45/§63); LLAMA_KV_POOL_VERIFY=1 0 mismatches on every arm; gate-prefill-logits --ab "LLAMA_KV_REGION_POOL=..." 0.000000 / 100.000 % on the pool arm (base PPL 2.9225, bit-identical to the campaign's own base); gate-park-idle-slots, gate-ckpt-reuse and gate-state-pipe PASS on a pooled cache (the mirror is authoritative, which is what makes them trivial); test-backend-ops -o FLASH_ATTN_QSA pass; no GPU faults; and `--fit` accepts the arms that only fit with the pool (-ncmoe 21/22 at -c 262144: refused without it, accepted with it; -fitp moves 3 264 MiB from the device row to Host). ========================================================================== PART 3 -- a STREAMED cache takes the sparse decode arm (B2) ========================================================================== A cache that is streaming at the depth it reads -- a window the used extent has passed, or a pool -- takes the sparse QSA decode arm; a resident cache keeps the dense one. llama_kv_cache::is_streaming() plus the qwen4exp arm policy, LLAMA_QSA_DENSE_DECODE_STREAM=0 to restore the old behaviour. Measured on a spilled KV (Flash-Next IQ3_XXS, -ncmoe 48, q8_0, 1 GPU, -n 400, 2 reps): +34.3 % at 102 899 depth (23.42 -> 31.43 t/s) and +47.3 % at 180 035 (16.51 -> 24.31); a resident cache byte-identical (853 77a40bf40be1). This is a decode-ARM choice, i.e. a different attention regime (like GREEDY-PURITY §45/§63), so a streamed arm's text differs from the old dense-arm text by construction and a resident arm is the oracle. ========================================================================== DEFAULT OFF, for both placements ========================================================================== Neither knob is a speed feature on a config whose KV fits: the window costs the depth below W (11-26 %) and the pool costs the sparse-vs-dense gap (-7 % at 103k, -11 % at 180k). They are FITTABILITY features -- they turn an OOM into a run and they hand the freed VRAM to the expert arena -- so both are opt-in and both stay byte-identical, including the OOM, with their knobs unset. Do not "fix" the defaults. Goal C (the MTP drafter ring, TODO ggml-org#121) joins the same block -- it is the same claim applied to the draft context, and its default follows the delivery's own rule because it measures positive. `LLAMA_SPEC_DRAFT_WINDOW` gives the MTP draft context a sliding window instead of a `-c`-sized KV: unset or `auto` is the adaptive policy (a quarter of the context, clamped to [32768, 65536] cells), `0` is off (byte-identical to a build without it) and `N` is a cell count. The drafter reads its last few thousand tokens, so a window at or above that is free and one far below it costs 7-9 % of decode; the clamps keep it above that band, and the target verifies every token it proposes, so a truncated draft can only be slower. The ring is the shipped reclaim in `llama_kv_cache::find_slot` (`n_swa`), not a new allocator, and the derived kq mask stays valid -- its predicate compares each cell's POSITION, so a recycled cell reports its new one. The VRAM win needed one more piece: an embedded MTP head has no GGUF of its own, so the slab's draft reserve was the flat 3584 MiB and the freed VRAM never reached the expert arena. For an embedded MTP head with an active window the reserve is now derived from the model's own metadata with the weights zeroed (they are the target's) and the KV sized by the window: aux 3.50 -> 0.76 GiB, i.e. the arena gains ~2.8 GiB. A separate MTP draft GGUF (qwen4exp/Flash-Next) and an un-windowed run keep the flat constant exactly as before, and a declined arena preflight now re-evaluates when the smaller real value arrives instead of latching on the load-time estimate. Measured (1 GPU; one R9700; `-n 2000`/`-n 3000`; static depth 3; interleaved): * 35B-A3B Q8_0 `-ncmoe 48 -c 262144` q8_0 KV, 51 433-token prompt: arena 20 910 -> 23 715 MiB (residency 64.1 -> 72.7 %), decode 111.2 -> 113.7 t/s at `-n 3000` (+2.2 %; +2.8-4.9 % at `-n 2000`), prefill +3.4 %, drafts byte-for-byte the same count (1995/3011) -- the window truncates nothing the drafter used. * dense 27B UD-Q4_K_XL `-c 102400`, MTP Protocol A `-n 3000`, reasoning-pinned: layer 71.9 -> 72.1, tensor 72.6 -> 72.5 (neutral), acceptance 2083/2747 identical in all four arms. * target greedy text byte-identical across off/auto/4096, and plain == draft-mtp == draft-mtp(W=512) at `-c 16384` with a 5256-token prompt and 3000 generated tokens (10 158 chars, sha 99b267e8dc3e), i.e. no wrong answer under constant cell reuse. * gates on a windowed draft: `gate-park-idle-slots.sh` (35B, -ncmoe 48, `-c 65536`: 3 park moves, park == lazyoff), `gate-ckpt-reuse.sh` (4B, `-c 131072`: draft cache 33280 of 131072), `gate-state-pipe.sh` (35B, `-c 65536`: all five arms) -- all PASS with `MTP draft KV window = 32768 cells` in their logs. r194 corner fixes (found by a configuration battery against Flash-Next after r193): * LLAMA_KV_REGION_POOL is capped at the cache's own cell count. =1000000 on a 262144-cell context used to take a 12451 MiB device pool of 250000 pages where only 65536 blocks exist (never claimed, arena -4 GiB); it is now 3264 MiB / 65536 pages, and a small context clamps the same way. * the draft KV window sizes only the reserve of the cache it actually windows. A separate -md MTP head (Flash-Next) keeps its full -c cache, but the reserve was derived with the window: 921 MiB where the honest number is 1566 (kv 217 vs 862) at -c 262144, the under-charge direction. Embedded heads (qwen3.5/3.6/3.8) are unchanged (776 MiB on the 35B). The VRAM cliff at -c 262144 is documented (not code): the 768 MiB default headroom is one hipBLASLt workspace short for the first prefill, GGML_CUDA_SLAB_HEADROOM_MIB=1536 is 3/3 requests clean. Amendment (TODO ggml-org#129's sibling): `-nkvo` declines the window, and the streamed arm keys on the placement. The window is a DEVICE region plus a pinned host tail, but its guard did not test `offload`: with `-nkvo` the per-layer buffer is chosen inside `if (offload)` and stays plain pageable host memory, while the plan block still logged "WINDOWED KV ENABLED", reserved pinned-RAM spill budget and left `kv_resident_cells` set. `is_streaming()` then keyed the streamed (sparse) decode arm on that plan -- qwen4exp consumes it -- for a KV with no region at all. Measured: `-nkvo LLAMA_KV_RESIDENT_CELLS=64` built a plain `CPU KV buffer` of the whole context while announcing a 64-cell VRAM window. The window now declines once, with the reason (the pool already declines on `!offload`), so `-nkvo` means "no streamed placement"; `is_streaming()` tests `kv_region`, the placement actually taken, which also covers a device cache whose region buft the backend refused. Text is unchanged in every arm (the decline is a no-op: `-nkvo` + window already read as `-nkvo` alone). Amendment (issue ggml-org#264): the draft window is PER SEQUENCE, and under `--kv-unified` its cell count is `(win + one batch) x n_seq_max`. A unified cache holds every sequence in ONE stream, so the r193 sizing (`win + n_ubatch` cells) was shared by all of them: once the first sequence had filled its window the tail was all the room left, the tail is where that sequence's own ring writes, and a second sequence's first batch had no contiguous run to be placed in -- `find_slot` refused, and every request on that slot answered `decode() failed: failed to process speculative batch` (HTTP 500) while the drafter ran. Reported on `--kv-unified -np 2` with a 65 536-cell window at `-c 262144` after slot 0 held ~100k tokens; reproduced here with a forced 8192-cell window. A per-stream cache (no `--kv-unified`) already sized each stream separately and is unchanged. `llama_spec_draft_kv_cells()` is now the one geometry function -- the cache (`create_memory`), the slab's draft reserve estimate and the "is a window active" test in `common` all call it, so the reserve can never under-charge an allocation. It grants `win` per sequence plus one placeable batch (`(win + n_ubatch) * n_seq_max`, capped at the context), and DECLINES the window when that does not fit the context per sequence rather than lowering it to `per_seq - n_ubatch`: a window that small saves one batch of cells per sequence and masks the drafter's newest cells to do it. `llama_spec_draft_window_cells()` stays the policy (it is the per-sequence window). n_seq_max == 1 -- every `llama-cli`/`llama-bench` run -- measures exactly what it did (cells 1536 for a 1024-cell window at `-c 8192`), so no single-sequence arm changes at all. Measured (dense 27B, 1 GPU, `-np 2 --kv-unified`): the issue's scenario now answers both slots, and `scripts/gate-spec-draft-window.sh` (new) drives 6 requests over 2 slots with a 1024-cell window -- both rings wrapping, prompts full re-prefilled by swapping them between slots -- with output byte-identical to `LLAMA_SPEC_DRAFT_WINDOW=0` on every step and draft acceptance identical (17/36, 23/23). Greedy text `plain == draft-mtp == draft-mtp(W=1024) == draft-mtp(W=0)` (876 chars, sha 8c8fd395402f) at `-c 16384`. And the reserve now charges a per-STREAM (no `--kv-unified`) draft cache for every stream it allocates: `n_seq_max x` the per-stream cell count. Before, a multi-slot windowed MTP server without `--kv-unified` (35B-A3B `-ncmoe 40 -np 2 -c 8192`, window 1024: 2 x 1536 = 3072 cells allocated, 1536 charged) under-charged the slab's aux reserve by one stream's window -- the direction the reserve header calls dangerous. Measured: 3072 cells reported on both the unified and the per-stream arm now.
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Nov 1, 2026
…W (Goal A) and an attendance POOL (Goal B), both opt-in Goals A and B of TODO ggml-org#118, promoted from the `wip/kv-residency` campaign. This block is the delivery's "the KV does not have to be O(-c) of VRAM" work: TWO opt-in placements of the same cache, and each one is byte-identical to a build without it when its knob is unset. * the WINDOW (`LLAMA_KV_RESIDENT_CELLS=<cells>|auto`): the newest W cells stay in VRAM, everything older spills to pinned system RAM in the SAME VA reservation -- a positional window, no kernel or op change; * the POOL (`LLAMA_KV_REGION_POOL=<cells>`): the authoritative copy of the WHOLE context in a pinned host mirror, and a compact device pool of the pages a decode step actually attends to, which the QSA sparse read resolves through a page table (`GGML_OP_KV_POOL`). They are mutually exclusive by construction (the pool declines while a window is active) and they answer the same question from opposite ends: the window keeps the *newest* cells hot, the pool keeps the *attended* cells hot. Both report `is_streaming()`, so a streamed cache takes the sparse QSA decode arm (B2, below). ========================================================================== PART 1 -- the WINDOW (Goal A, promoted in r178) ========================================================================== Goal A of TODO ggml-org#118, promoted from the `wip/kv-residency` campaign. WHAT IT DOES. The KV cache's VRAM cost becomes a WINDOW of the newest `W` cells instead of `-c` cells: one VA reservation (a CUDA/HIP VMM region) holds the whole cache, the window's cells are backed by VRAM and everything below them by pinned system RAM. `set_rows`, the in-place rope shift, `state_write/read`, the kq mask and the FA kernels keep addressing one contiguous range, so no kernel and no op changes. The window slides with the watermark in whole map units, so a remap happens once per few thousand tokens and the apparatus itself is free (a zero-spill arm measures the same as plain). WHY. (a) A context that OOMs today runs: 27B Q8_0 `-c 262144` (8704 MiB of KV) now runs on one 32 GiB card at 128 MiB VRAM + 8576 MiB pinned host for the KV. (b) With host-resident MoE experts, the VRAM the KV does not need *yet* goes to the expert-cache arena: measured at `-c 262144`, `-n 2000`, `-ncmoe` = the model's full layer count, 51 433-token prompt, W at or above the run's depth = **+2.2 to +2.9 GiB of arena** (+3.9 to +6.7 points of residency) for free -- 122B-A10B Q4_K_XL +3.8 % decode and +4.7 % prefill, 35B-A3B Q8_0 -0.9 % decode and +3 % prefill; a `W` 35 k cells BELOW the run depth costs 11-26 % (the spill is read every token). OPT-IN, AND ONLY WHEN ASKED FOR. `LLAMA_KV_RESIDENT_CELLS=<cells>` (a number) or `=auto` (`--fit` sizes it, and only spills a context the user pinned with `-c`); unset/0 = no window. With no window the KV takes the PLAIN device buffer, so a run without the knob is byte-identical to a build without this block -- including its OOM (verified). `LLAMA_KV_SPILL_RAM_PCT` (85 % of MemAvailable) caps the pinned spill and widens the window rather than being OOM-killed; `LLAMA_KV_REGION=0` disables the provider; `LLAMA_KV_REGION_QUARANTINE=0` and `LLAMA_KV_REGION_DEBUG/TRACE/CANARY/DUMP` are the diagnosis switches. PURITY (the window). A spilled KV is numerically transparent: prefill-logit **KLD -0.000000 / 100.000 %** on a spilling 27B arm and -0.000000 / 99.994 % on a spilling Flash-Next (two KV caches: the attention KV and the QSA indexer), text byte-identical on 27B (f16 and q8_0), 4B, 35B-A3B and Flash-Next, and the state paths, the context-checkpoint path and the MTP verify widths all green on arms that provably spill. Two driver hazards are held: a kind flip zeroes a neighbouring live host mapping unless the released physical is held across the create (`LLAMA_KV_REGION_QUARANTINE`, default on -- `=0` reproduces the corruption), and every tensor in a windowed region is placed on the driver's map granularity so a slide step coincides with a mapping. An idle-slot park is REFUSED on a region-backed cache (the server then saves the slot to the prompt cache and clears it, which is byte-identical to the parking gate's reference) because a park moves cells above the region's mapped watermark through the copy engine, which faults the GPU. FIT. `--fit` sizes and reports the window (`auto`), or honours and reports a numeric `W`: the resident/spill split, the VRAM saved, and the per-token read cost at the model's full context from the backend's calibrated link rate. The fit identifies the KV's bytes by the region buffer TYPE, and its measurement context is a `no_alloc` probe that declines a window -- so the probe takes the region buffer explicitly (`llama_kv_region_set_probe`); without that the fit cannot see the KV, reports an over-budget config and aborts instead of sizing the window (the r178 regression). GATES (1 GPU, gfx1201): default path byte-identical (`5ba44647188f`) and still OOMs; VMM selftest PASS and FAIL with the hold disabled; windowed arms 305 `e2cea6fa6670` = plain at W=1024/2048/4096 (spilling at 1024: 128 MiB host), `QUARANTINE=0` -> 325 `fb65430049e9` (the hazard); `--fit` sizes `auto` (96680 of 262144 cells, 3210 MiB resident) and reports a numeric W; `gate-ckpt-reuse.sh` / `gate-state-pipe.sh` / MTP verify widths on spilling arms; `test-backend-ops -o FLASH_ATTN_QSA` 26/26; `check-gpu-faults.sh` clean. Not in this block: the campaign's Goal B (a sparse attended set) and Goal C (the MTP drafter ring, `LLAMA_SPEC_DRAFT_WINDOW`) -- both remain campaign work -- and A1 (the superseded two-base FA read). Records: `wip/kv-residency/A2-MIXED-BACKING.md` (§3.7.9, §3.7.11), `HANDOVER.md`. MULTI-DEVICE `--fit` (r181): the KV-region glue is now safe on a Meta (tensor-split) device, and `auto`'s decision reaches the cache as a decision. r178 made default `--fit` abort on ANY `-sm tensor` run with more than one device: the fit's KV probes and the cache's own region lookups call `ggml_backend_dev_backend_reg(dev)` and hand it to `ggml_backend_reg_get_proc_address`, and a Meta device has no backend reg (`device->reg == NULL`), so `GGML_ASSERT(reg)` fired at model load. Three paths asserted: the fit probe (any run), the runtime buft lookup (a numeric W), and the spill budget/link lookups (a numeric W below `-c`). The window is one VMM region per device and a tensor split has no per-device region buffer type, so the backend simply has no answer there -- which is now what it says: a null reg reads as "not provided", the window is declined with one message naming the tensor split (fit and cache), and the KV stays fully resident. A resolved-to-child reg in the fit (the same Meta->simple-device walk the split accounting already does) keeps the identification exact if a multi-device window ever exists. Three wiring defects in the same code, all visible on ONE device: - `auto`'s "no window needed" decision (0) was indistinguishable from "nobody decided", so the cache warned "--fit did not run" immediately after the fit had decided exactly that. `llama_kv_region_set_resident_cells` now records that a decision was made (`llama_kv_region_resident_cells_decided`), and a decided 0 is silent. - every run without the knob logged "the windowed KV is unavailable for this cache (no spilled cells)". That message now only fires when a window was actually requested and declined for a real reason. - the pinned-RAM ceiling clamp could raise W past the VRAM budget and then be reported as "does not make this fit either". It is now only taken while the wider window still meets the VRAM target; otherwise the fit says the ceiling cannot be served at this `-c` and drops the window (which the fit then fits by reducing the context). That ordering is not cosmetic: an intermediate form of this fix accepted a 235 GiB pinned spill plan for a 4B at `-c 8388608`, and creating it OOM-killed the test box. GATES (the window, gfx1201): `--fit on` (default) at 2 and 3 devices, `-sm tensor`, with no knob / a numeric W / `auto`, fit on and off: no assert, tokens produced, exactly one message per requested window. `-sm layer` 2 devices and 1 GPU still take the window per device (numeric W), and `auto` still sizes the 27B Q8_0 `-c 262144` q8_0 arm identically (123265 of 262144 cells, 4092.8 MiB resident / 4611.2 MiB spilling). One device, no knob: no KV message at all. Purity unchanged: plain vs a SPILLING windowed arm prefill-logit KLD 0.000000 / 99.990 % (q8_0 KV), greedy text byte-identical on that arm; 35B-A3B (1 GPU and 2-GPU `-sm tensor`), dense 27B and the canonical 27B Q8_0 prefill-logit gate (0.000000 / 100.000 %) byte-identical to r180; MTP Protocol A unchanged (tensor acceptance 0.60816 = 1937/3185, plain == draft-mtp); no GPU faults. ========================================================================== PART 2 -- the ATTENDANCE POOL (Goal B, promoted in r190) ========================================================================== The attention KV lives twice: its AUTHORITATIVE copy in a pinned host MIRROR (cell-indexed, so the writers, state_write/state_read, the K-shift, defrag and seq_park all work on it unchanged -- the writer rule) and a compact DEVICE POOL of pages of one indexer block (compress_ratio cells) with a page table block -> slot and its inverse. A decode step resolves its top-k selection through the table and fills the pages it missed from the mirror; the QSA reader gathers K/V at the pool slots while the mask stays cell-indexed. LLAMA_KV_REGION_POOL=<cells>, unset/0 = off = byte-identical. Contents. - ggml/src/ggml-cuda/kv-pool.{cu,cuh}: GGML_OP_KV_POOL. MARK sets use[slot] = epoch for every page this launch reads AND every page the batch just wrote (the graph's k_idxs), and queues the written ones for re-fill; CLAIM takes a slot for each DISTINCT missing block (the table CAS is the dedupe) and never takes a slot MARK protected; MAP+FILL writes each selected cell's pool position into the reader's K/V id list and copies the claimed and dirty pages from the mirror, K and V sharing slots. The epoch is a device counter incremented once per launch: the graph bakes pointers, never counters, and nothing is allocated per launch. - ggml-cuda.cu: the pool's pinned host mirror buffer type -- a DEVICE buffer type whose allocation is pinned host memory (`ROCm_Host` reports is_host, which would send the KV's writers and the FA read to the CPU on a discrete device), and its proc-address entry. - llama-kv-cache: the eligibility, the per-layer pool tensors (pool_k/pool_v, tbl, inv, use, one shared counter block), the resolve wiring into the QSA id list, kv_pool_serves() (a batch too wide for the pool takes the cell-indexed path), the teardown accounting (LLAMA_KV_POOL_STATS takes a PATH: a line on stderr sits inside the generated text), and memory_breakdown() charging the mirror to the host bucket so `--fit` does not reserve it as VRAM. - llama-memory-hybrid-idx / llama-memory-hybrid / llama-memory: the second id list (the K/V gather follows the page table while the mask stays cell-indexed), the flag threading, and the pool's byte accounting for `--fit` (llama_get_kv_pool_bytes()). - models/qwen4exp.cpp: a pooled cache reports is_streaming() and the sparse arm uses the pool's id list; the MTP draft's own cache is never pooled (its attention is dense). - llama-context / the async state copies: the mirror's buffer type is accepted by the batched save and restore (its bytes are host memory, staged through the pinned state_stage). - common/fit.cpp + src/llama-ext.h: the pool's split in --fit's arithmetic and report (the mirror is pinned host RAM, the pool is VRAM), and no context-reduction interpolation while the pool is active -- the pool's VRAM is fixed, so reducing -c frees nothing and the interpolation would divide by a near-zero bytes-per-context delta. Invariants, each one caught by the greedy text. 1. MARK then CLAIM: a claim must never evict a page the same launch reads. Without MARK the round-robin victim could be a page another row still needs (the text diverged ~400 chars in, and a pool larger than the whole cache hid it completely). 2. Claim ATTEMPTS are not distinct blocks: a slot per id attempt wrapped the cursor within one 4-row batch, so two blocks shared a slot and a just-resolved block went unresident. The table CAS dedupes first, so only distinct blocks consume a slot and kv_pool_serves() bounds the distinct count. 3. No transient scratch in a captured graph: the fill list lived in a ggml_cuda_pool_alloc that is freed at the end of the op, and a captured graph bakes the pointer, so a replay wrote into whatever op had been handed that block ("values verify clean, text differs run to run"). It lives in the counters tensor. 4. The mirror is AUTHORITATIVE: the writers land in it and a declared page is re-filled from it before the attention reads it, so an eviction costs nothing and nothing has to be invalidated -- except by a path that rewrites cells in place without going through the writers (the K-shift, a state restore), which calls kv_pool_invalidate(). 5. Eligibility is narrow on purpose: one stream, non-MLA, K and V both present, !v_trans, a uniform compress_ratio and cell geometry, no window active, a device-offloaded cache, and only the trunk context of a qwen4exp model. Anything else declines with one message and the KV is unchanged. 6. The pool is floored at one decode band's worth of blocks (8 x ceil(width/page) pages) so a verify batch cannot exhaust the slot budget, and the mirror is bounded at creation by LLAMA_KV_SPILL_RAM_PCT (it is pinned, non-swappable RAM) -- over the ceiling the pool is declined loudly instead of being OOM-killed. Measured (Flash-Next GSQ-IQ3_XXS, 1 GPU, -ncmoe 48, q8_0, the PLE flags, arms interleaved in one batch, -n 512, MTP depth 4; t/s and tokens/step): depth (ctx) dense sparse pool (204 MiB) text (-n 64) 5 298 (16 384) 72.09 71.58 71.27 pool == sparse: 332 chars dd1981213373 102 899 (131 072) 59.10 54.70 54.65 (5.3k / 51 475 references; dense differs) 180 035 (196 608) 48.94 43.16 43.41 pool == sparse: 861 chars 263c7f2be4d9 The pool lands ON the sparse ceiling at every depth (+0.5 / +0.6 / +0.58 %), so its placement is free and what remains against a resident KV (-7 % / -11 %) is the sparse decode arm's own indexer cost (block 11), not the KV's storage. A 204 MiB pool replaces the resident attention KV's 1 632 MiB at 103k / 2 448 MiB at 180k, and the freed VRAM goes to the expert arena: 103k plain decode, -n 2000, 23 579.8 -> 25 018.6 MiB (+1 438.8 MiB, +18 slots/table), expert hit 96.26 -> 97.02 %, cold reads 42.0 -> 31.6 GiB. The pool's own cost is 0.10-0.11 ms/token (mark/claim/map+fill) with fills 0.03-0.05 ms/step at 92-99 % hits, which is why a better page policy (LRU / F-LRU / a heat prior) is measured dead at this shape. Full numbers and the three-depth table: ../wip/kv-residency/BA-POOL-DESIGN.md §7-§8. PURITY (the pool). Greedy text pool == the resident sparse arm at 5.3k (332 dd1981213373), 51 475 depth (854 43b30de151b9) and 180k (861 263c7f2be4d9), with the dense arm differing as documented (GREEDY-PURITY §45/§63); LLAMA_KV_POOL_VERIFY=1 0 mismatches on every arm; gate-prefill-logits --ab "LLAMA_KV_REGION_POOL=..." 0.000000 / 100.000 % on the pool arm (base PPL 2.9225, bit-identical to the campaign's own base); gate-park-idle-slots, gate-ckpt-reuse and gate-state-pipe PASS on a pooled cache (the mirror is authoritative, which is what makes them trivial); test-backend-ops -o FLASH_ATTN_QSA pass; no GPU faults; and `--fit` accepts the arms that only fit with the pool (-ncmoe 21/22 at -c 262144: refused without it, accepted with it; -fitp moves 3 264 MiB from the device row to Host). ========================================================================== PART 3 -- a STREAMED cache takes the sparse decode arm (B2) ========================================================================== A cache that is streaming at the depth it reads -- a window the used extent has passed, or a pool -- takes the sparse QSA decode arm; a resident cache keeps the dense one. llama_kv_cache::is_streaming() plus the qwen4exp arm policy, LLAMA_QSA_DENSE_DECODE_STREAM=0 to restore the old behaviour. Measured on a spilled KV (Flash-Next IQ3_XXS, -ncmoe 48, q8_0, 1 GPU, -n 400, 2 reps): +34.3 % at 102 899 depth (23.42 -> 31.43 t/s) and +47.3 % at 180 035 (16.51 -> 24.31); a resident cache byte-identical (853 77a40bf40be1). This is a decode-ARM choice, i.e. a different attention regime (like GREEDY-PURITY §45/§63), so a streamed arm's text differs from the old dense-arm text by construction and a resident arm is the oracle. ========================================================================== DEFAULT OFF, for both placements ========================================================================== Neither knob is a speed feature on a config whose KV fits: the window costs the depth below W (11-26 %) and the pool costs the sparse-vs-dense gap (-7 % at 103k, -11 % at 180k). They are FITTABILITY features -- they turn an OOM into a run and they hand the freed VRAM to the expert arena -- so both are opt-in and both stay byte-identical, including the OOM, with their knobs unset. Do not "fix" the defaults. Goal C (the MTP drafter ring, TODO ggml-org#121) joins the same block -- it is the same claim applied to the draft context, and its default follows the delivery's own rule because it measures positive. `LLAMA_SPEC_DRAFT_WINDOW` gives the MTP draft context a sliding window instead of a `-c`-sized KV: unset or `auto` is the adaptive policy (a quarter of the context, clamped to [32768, 65536] cells), `0` is off (byte-identical to a build without it) and `N` is a cell count. The drafter reads its last few thousand tokens, so a window at or above that is free and one far below it costs 7-9 % of decode; the clamps keep it above that band, and the target verifies every token it proposes, so a truncated draft can only be slower. The ring is the shipped reclaim in `llama_kv_cache::find_slot` (`n_swa`), not a new allocator, and the derived kq mask stays valid -- its predicate compares each cell's POSITION, so a recycled cell reports its new one. The VRAM win needed one more piece: an embedded MTP head has no GGUF of its own, so the slab's draft reserve was the flat 3584 MiB and the freed VRAM never reached the expert arena. For an embedded MTP head with an active window the reserve is now derived from the model's own metadata with the weights zeroed (they are the target's) and the KV sized by the window: aux 3.50 -> 0.76 GiB, i.e. the arena gains ~2.8 GiB. A separate MTP draft GGUF (qwen4exp/Flash-Next) and an un-windowed run keep the flat constant exactly as before, and a declined arena preflight now re-evaluates when the smaller real value arrives instead of latching on the load-time estimate. Measured (1 GPU; one R9700; `-n 2000`/`-n 3000`; static depth 3; interleaved): * 35B-A3B Q8_0 `-ncmoe 48 -c 262144` q8_0 KV, 51 433-token prompt: arena 20 910 -> 23 715 MiB (residency 64.1 -> 72.7 %), decode 111.2 -> 113.7 t/s at `-n 3000` (+2.2 %; +2.8-4.9 % at `-n 2000`), prefill +3.4 %, drafts byte-for-byte the same count (1995/3011) -- the window truncates nothing the drafter used. * dense 27B UD-Q4_K_XL `-c 102400`, MTP Protocol A `-n 3000`, reasoning-pinned: layer 71.9 -> 72.1, tensor 72.6 -> 72.5 (neutral), acceptance 2083/2747 identical in all four arms. * target greedy text byte-identical across off/auto/4096, and plain == draft-mtp == draft-mtp(W=512) at `-c 16384` with a 5256-token prompt and 3000 generated tokens (10 158 chars, sha 99b267e8dc3e), i.e. no wrong answer under constant cell reuse. * gates on a windowed draft: `gate-park-idle-slots.sh` (35B, -ncmoe 48, `-c 65536`: 3 park moves, park == lazyoff), `gate-ckpt-reuse.sh` (4B, `-c 131072`: draft cache 33280 of 131072), `gate-state-pipe.sh` (35B, `-c 65536`: all five arms) -- all PASS with `MTP draft KV window = 32768 cells` in their logs. r194 corner fixes (found by a configuration battery against Flash-Next after r193): * LLAMA_KV_REGION_POOL is capped at the cache's own cell count. =1000000 on a 262144-cell context used to take a 12451 MiB device pool of 250000 pages where only 65536 blocks exist (never claimed, arena -4 GiB); it is now 3264 MiB / 65536 pages, and a small context clamps the same way. * the draft KV window sizes only the reserve of the cache it actually windows. A separate -md MTP head (Flash-Next) keeps its full -c cache, but the reserve was derived with the window: 921 MiB where the honest number is 1566 (kv 217 vs 862) at -c 262144, the under-charge direction. Embedded heads (qwen3.5/3.6/3.8) are unchanged (776 MiB on the 35B). The VRAM cliff at -c 262144 is documented (not code): the 768 MiB default headroom is one hipBLASLt workspace short for the first prefill, GGML_CUDA_SLAB_HEADROOM_MIB=1536 is 3/3 requests clean. Amendment (TODO ggml-org#129's sibling): `-nkvo` declines the window, and the streamed arm keys on the placement. The window is a DEVICE region plus a pinned host tail, but its guard did not test `offload`: with `-nkvo` the per-layer buffer is chosen inside `if (offload)` and stays plain pageable host memory, while the plan block still logged "WINDOWED KV ENABLED", reserved pinned-RAM spill budget and left `kv_resident_cells` set. `is_streaming()` then keyed the streamed (sparse) decode arm on that plan -- qwen4exp consumes it -- for a KV with no region at all. Measured: `-nkvo LLAMA_KV_RESIDENT_CELLS=64` built a plain `CPU KV buffer` of the whole context while announcing a 64-cell VRAM window. The window now declines once, with the reason (the pool already declines on `!offload`), so `-nkvo` means "no streamed placement"; `is_streaming()` tests `kv_region`, the placement actually taken, which also covers a device cache whose region buft the backend refused. Text is unchanged in every arm (the decline is a no-op: `-nkvo` + window already read as `-nkvo` alone). Amendment (issue ggml-org#264): the draft window is PER SEQUENCE, and under `--kv-unified` its cell count is `(win + one batch) x n_seq_max`. A unified cache holds every sequence in ONE stream, so the r193 sizing (`win + n_ubatch` cells) was shared by all of them: once the first sequence had filled its window the tail was all the room left, the tail is where that sequence's own ring writes, and a second sequence's first batch had no contiguous run to be placed in -- `find_slot` refused, and every request on that slot answered `decode() failed: failed to process speculative batch` (HTTP 500) while the drafter ran. Reported on `--kv-unified -np 2` with a 65 536-cell window at `-c 262144` after slot 0 held ~100k tokens; reproduced here with a forced 8192-cell window. A per-stream cache (no `--kv-unified`) already sized each stream separately and is unchanged. `llama_spec_draft_kv_cells()` is now the one geometry function -- the cache (`create_memory`), the slab's draft reserve estimate and the "is a window active" test in `common` all call it, so the reserve can never under-charge an allocation. It grants `win` per sequence plus one placeable batch (`(win + n_ubatch) * n_seq_max`, capped at the context), and DECLINES the window when that does not fit the context per sequence rather than lowering it to `per_seq - n_ubatch`: a window that small saves one batch of cells per sequence and masks the drafter's newest cells to do it. `llama_spec_draft_window_cells()` stays the policy (it is the per-sequence window). n_seq_max == 1 -- every `llama-cli`/`llama-bench` run -- measures exactly what it did (cells 1536 for a 1024-cell window at `-c 8192`), so no single-sequence arm changes at all. Measured (dense 27B, 1 GPU, `-np 2 --kv-unified`): the issue's scenario now answers both slots, and `scripts/gate-spec-draft-window.sh` (new) drives 6 requests over 2 slots with a 1024-cell window -- both rings wrapping, prompts full re-prefilled by swapping them between slots -- with output byte-identical to `LLAMA_SPEC_DRAFT_WINDOW=0` on every step and draft acceptance identical (17/36, 23/23). Greedy text `plain == draft-mtp == draft-mtp(W=1024) == draft-mtp(W=0)` (876 chars, sha 8c8fd395402f) at `-c 16384`. And the reserve now charges a per-STREAM (no `--kv-unified`) draft cache for every stream it allocates: `n_seq_max x` the per-stream cell count. Before, a multi-slot windowed MTP server without `--kv-unified` (35B-A3B `-ncmoe 40 -np 2 -c 8192`, window 1024: 2 x 1536 = 3072 cells allocated, 1536 charged) under-charged the slab's aux reserve by one stream's window -- the direction the reserve header calls dangerous. Measured: 3072 cells reported on both the unified and the per-stream arm now.
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Nov 1, 2026
…W (Goal A) and an attendance POOL (Goal B), both opt-in Goals A and B of TODO ggml-org#118, promoted from the `wip/kv-residency` campaign. This block is the delivery's "the KV does not have to be O(-c) of VRAM" work: TWO opt-in placements of the same cache, and each one is byte-identical to a build without it when its knob is unset. * the WINDOW (`LLAMA_KV_RESIDENT_CELLS=<cells>|auto`): the newest W cells stay in VRAM, everything older spills to pinned system RAM in the SAME VA reservation -- a positional window, no kernel or op change; * the POOL (`LLAMA_KV_REGION_POOL=<cells>`): the authoritative copy of the WHOLE context in a pinned host mirror, and a compact device pool of the pages a decode step actually attends to, which the QSA sparse read resolves through a page table (`GGML_OP_KV_POOL`). They are mutually exclusive by construction (the pool declines while a window is active) and they answer the same question from opposite ends: the window keeps the *newest* cells hot, the pool keeps the *attended* cells hot. Both report `is_streaming()`, so a streamed cache takes the sparse QSA decode arm (B2, below). ========================================================================== PART 1 -- the WINDOW (Goal A, promoted in r178) ========================================================================== Goal A of TODO ggml-org#118, promoted from the `wip/kv-residency` campaign. WHAT IT DOES. The KV cache's VRAM cost becomes a WINDOW of the newest `W` cells instead of `-c` cells: one VA reservation (a CUDA/HIP VMM region) holds the whole cache, the window's cells are backed by VRAM and everything below them by pinned system RAM. `set_rows`, the in-place rope shift, `state_write/read`, the kq mask and the FA kernels keep addressing one contiguous range, so no kernel and no op changes. The window slides with the watermark in whole map units, so a remap happens once per few thousand tokens and the apparatus itself is free (a zero-spill arm measures the same as plain). WHY. (a) A context that OOMs today runs: 27B Q8_0 `-c 262144` (8704 MiB of KV) now runs on one 32 GiB card at 128 MiB VRAM + 8576 MiB pinned host for the KV. (b) With host-resident MoE experts, the VRAM the KV does not need *yet* goes to the expert-cache arena: measured at `-c 262144`, `-n 2000`, `-ncmoe` = the model's full layer count, 51 433-token prompt, W at or above the run's depth = **+2.2 to +2.9 GiB of arena** (+3.9 to +6.7 points of residency) for free -- 122B-A10B Q4_K_XL +3.8 % decode and +4.7 % prefill, 35B-A3B Q8_0 -0.9 % decode and +3 % prefill; a `W` 35 k cells BELOW the run depth costs 11-26 % (the spill is read every token). OPT-IN, AND ONLY WHEN ASKED FOR. `LLAMA_KV_RESIDENT_CELLS=<cells>` (a number) or `=auto` (`--fit` sizes it, and only spills a context the user pinned with `-c`); unset/0 = no window. With no window the KV takes the PLAIN device buffer, so a run without the knob is byte-identical to a build without this block -- including its OOM (verified). `LLAMA_KV_SPILL_RAM_PCT` (85 % of MemAvailable) caps the pinned spill and widens the window rather than being OOM-killed; `LLAMA_KV_REGION=0` disables the provider; `LLAMA_KV_REGION_QUARANTINE=0` and `LLAMA_KV_REGION_DEBUG/TRACE/CANARY/DUMP` are the diagnosis switches. PURITY (the window). A spilled KV is numerically transparent: prefill-logit **KLD -0.000000 / 100.000 %** on a spilling 27B arm and -0.000000 / 99.994 % on a spilling Flash-Next (two KV caches: the attention KV and the QSA indexer), text byte-identical on 27B (f16 and q8_0), 4B, 35B-A3B and Flash-Next, and the state paths, the context-checkpoint path and the MTP verify widths all green on arms that provably spill. Two driver hazards are held: a kind flip zeroes a neighbouring live host mapping unless the released physical is held across the create (`LLAMA_KV_REGION_QUARANTINE`, default on -- `=0` reproduces the corruption), and every tensor in a windowed region is placed on the driver's map granularity so a slide step coincides with a mapping. An idle-slot park is REFUSED on a region-backed cache (the server then saves the slot to the prompt cache and clears it, which is byte-identical to the parking gate's reference) because a park moves cells above the region's mapped watermark through the copy engine, which faults the GPU. FIT. `--fit` sizes and reports the window (`auto`), or honours and reports a numeric `W`: the resident/spill split, the VRAM saved, and the per-token read cost at the model's full context from the backend's calibrated link rate. The fit identifies the KV's bytes by the region buffer TYPE, and its measurement context is a `no_alloc` probe that declines a window -- so the probe takes the region buffer explicitly (`llama_kv_region_set_probe`); without that the fit cannot see the KV, reports an over-budget config and aborts instead of sizing the window (the r178 regression). GATES (1 GPU, gfx1201): default path byte-identical (`5ba44647188f`) and still OOMs; VMM selftest PASS and FAIL with the hold disabled; windowed arms 305 `e2cea6fa6670` = plain at W=1024/2048/4096 (spilling at 1024: 128 MiB host), `QUARANTINE=0` -> 325 `fb65430049e9` (the hazard); `--fit` sizes `auto` (96680 of 262144 cells, 3210 MiB resident) and reports a numeric W; `gate-ckpt-reuse.sh` / `gate-state-pipe.sh` / MTP verify widths on spilling arms; `test-backend-ops -o FLASH_ATTN_QSA` 26/26; `check-gpu-faults.sh` clean. Not in this block: the campaign's Goal B (a sparse attended set) and Goal C (the MTP drafter ring, `LLAMA_SPEC_DRAFT_WINDOW`) -- both remain campaign work -- and A1 (the superseded two-base FA read). Records: `wip/kv-residency/A2-MIXED-BACKING.md` (§3.7.9, §3.7.11), `HANDOVER.md`. MULTI-DEVICE `--fit` (r181): the KV-region glue is now safe on a Meta (tensor-split) device, and `auto`'s decision reaches the cache as a decision. r178 made default `--fit` abort on ANY `-sm tensor` run with more than one device: the fit's KV probes and the cache's own region lookups call `ggml_backend_dev_backend_reg(dev)` and hand it to `ggml_backend_reg_get_proc_address`, and a Meta device has no backend reg (`device->reg == NULL`), so `GGML_ASSERT(reg)` fired at model load. Three paths asserted: the fit probe (any run), the runtime buft lookup (a numeric W), and the spill budget/link lookups (a numeric W below `-c`). The window is one VMM region per device and a tensor split has no per-device region buffer type, so the backend simply has no answer there -- which is now what it says: a null reg reads as "not provided", the window is declined with one message naming the tensor split (fit and cache), and the KV stays fully resident. A resolved-to-child reg in the fit (the same Meta->simple-device walk the split accounting already does) keeps the identification exact if a multi-device window ever exists. Three wiring defects in the same code, all visible on ONE device: - `auto`'s "no window needed" decision (0) was indistinguishable from "nobody decided", so the cache warned "--fit did not run" immediately after the fit had decided exactly that. `llama_kv_region_set_resident_cells` now records that a decision was made (`llama_kv_region_resident_cells_decided`), and a decided 0 is silent. - every run without the knob logged "the windowed KV is unavailable for this cache (no spilled cells)". That message now only fires when a window was actually requested and declined for a real reason. - the pinned-RAM ceiling clamp could raise W past the VRAM budget and then be reported as "does not make this fit either". It is now only taken while the wider window still meets the VRAM target; otherwise the fit says the ceiling cannot be served at this `-c` and drops the window (which the fit then fits by reducing the context). That ordering is not cosmetic: an intermediate form of this fix accepted a 235 GiB pinned spill plan for a 4B at `-c 8388608`, and creating it OOM-killed the test box. GATES (the window, gfx1201): `--fit on` (default) at 2 and 3 devices, `-sm tensor`, with no knob / a numeric W / `auto`, fit on and off: no assert, tokens produced, exactly one message per requested window. `-sm layer` 2 devices and 1 GPU still take the window per device (numeric W), and `auto` still sizes the 27B Q8_0 `-c 262144` q8_0 arm identically (123265 of 262144 cells, 4092.8 MiB resident / 4611.2 MiB spilling). One device, no knob: no KV message at all. Purity unchanged: plain vs a SPILLING windowed arm prefill-logit KLD 0.000000 / 99.990 % (q8_0 KV), greedy text byte-identical on that arm; 35B-A3B (1 GPU and 2-GPU `-sm tensor`), dense 27B and the canonical 27B Q8_0 prefill-logit gate (0.000000 / 100.000 %) byte-identical to r180; MTP Protocol A unchanged (tensor acceptance 0.60816 = 1937/3185, plain == draft-mtp); no GPU faults. ========================================================================== PART 2 -- the ATTENDANCE POOL (Goal B, promoted in r190) ========================================================================== The attention KV lives twice: its AUTHORITATIVE copy in a pinned host MIRROR (cell-indexed, so the writers, state_write/state_read, the K-shift, defrag and seq_park all work on it unchanged -- the writer rule) and a compact DEVICE POOL of pages of one indexer block (compress_ratio cells) with a page table block -> slot and its inverse. A decode step resolves its top-k selection through the table and fills the pages it missed from the mirror; the QSA reader gathers K/V at the pool slots while the mask stays cell-indexed. LLAMA_KV_REGION_POOL=<cells>, unset/0 = off = byte-identical. Contents. - ggml/src/ggml-cuda/kv-pool.{cu,cuh}: GGML_OP_KV_POOL. MARK sets use[slot] = epoch for every page this launch reads AND every page the batch just wrote (the graph's k_idxs), and queues the written ones for re-fill; CLAIM takes a slot for each DISTINCT missing block (the table CAS is the dedupe) and never takes a slot MARK protected; MAP+FILL writes each selected cell's pool position into the reader's K/V id list and copies the claimed and dirty pages from the mirror, K and V sharing slots. The epoch is a device counter incremented once per launch: the graph bakes pointers, never counters, and nothing is allocated per launch. - ggml-cuda.cu: the pool's pinned host mirror buffer type -- a DEVICE buffer type whose allocation is pinned host memory (`ROCm_Host` reports is_host, which would send the KV's writers and the FA read to the CPU on a discrete device), and its proc-address entry. - llama-kv-cache: the eligibility, the per-layer pool tensors (pool_k/pool_v, tbl, inv, use, one shared counter block), the resolve wiring into the QSA id list, kv_pool_serves() (a batch too wide for the pool takes the cell-indexed path), the teardown accounting (LLAMA_KV_POOL_STATS takes a PATH: a line on stderr sits inside the generated text), and memory_breakdown() charging the mirror to the host bucket so `--fit` does not reserve it as VRAM. - llama-memory-hybrid-idx / llama-memory-hybrid / llama-memory: the second id list (the K/V gather follows the page table while the mask stays cell-indexed), the flag threading, and the pool's byte accounting for `--fit` (llama_get_kv_pool_bytes()). - models/qwen4exp.cpp: a pooled cache reports is_streaming() and the sparse arm uses the pool's id list; the MTP draft's own cache is never pooled (its attention is dense). - llama-context / the async state copies: the mirror's buffer type is accepted by the batched save and restore (its bytes are host memory, staged through the pinned state_stage). - common/fit.cpp + src/llama-ext.h: the pool's split in --fit's arithmetic and report (the mirror is pinned host RAM, the pool is VRAM), and no context-reduction interpolation while the pool is active -- the pool's VRAM is fixed, so reducing -c frees nothing and the interpolation would divide by a near-zero bytes-per-context delta. Invariants, each one caught by the greedy text. 1. MARK then CLAIM: a claim must never evict a page the same launch reads. Without MARK the round-robin victim could be a page another row still needs (the text diverged ~400 chars in, and a pool larger than the whole cache hid it completely). 2. Claim ATTEMPTS are not distinct blocks: a slot per id attempt wrapped the cursor within one 4-row batch, so two blocks shared a slot and a just-resolved block went unresident. The table CAS dedupes first, so only distinct blocks consume a slot and kv_pool_serves() bounds the distinct count. 3. No transient scratch in a captured graph: the fill list lived in a ggml_cuda_pool_alloc that is freed at the end of the op, and a captured graph bakes the pointer, so a replay wrote into whatever op had been handed that block ("values verify clean, text differs run to run"). It lives in the counters tensor. 4. The mirror is AUTHORITATIVE: the writers land in it and a declared page is re-filled from it before the attention reads it, so an eviction costs nothing and nothing has to be invalidated -- except by a path that rewrites cells in place without going through the writers (the K-shift, a state restore), which calls kv_pool_invalidate(). 5. Eligibility is narrow on purpose: one stream, non-MLA, K and V both present, !v_trans, a uniform compress_ratio and cell geometry, no window active, a device-offloaded cache, and only the trunk context of a qwen4exp model. Anything else declines with one message and the KV is unchanged. 6. The pool is floored at one decode band's worth of blocks (8 x ceil(width/page) pages) so a verify batch cannot exhaust the slot budget, and the mirror is bounded at creation by LLAMA_KV_SPILL_RAM_PCT (it is pinned, non-swappable RAM) -- over the ceiling the pool is declined loudly instead of being OOM-killed. Measured (Flash-Next GSQ-IQ3_XXS, 1 GPU, -ncmoe 48, q8_0, the PLE flags, arms interleaved in one batch, -n 512, MTP depth 4; t/s and tokens/step): depth (ctx) dense sparse pool (204 MiB) text (-n 64) 5 298 (16 384) 72.09 71.58 71.27 pool == sparse: 332 chars dd1981213373 102 899 (131 072) 59.10 54.70 54.65 (5.3k / 51 475 references; dense differs) 180 035 (196 608) 48.94 43.16 43.41 pool == sparse: 861 chars 263c7f2be4d9 The pool lands ON the sparse ceiling at every depth (+0.5 / +0.6 / +0.58 %), so its placement is free and what remains against a resident KV (-7 % / -11 %) is the sparse decode arm's own indexer cost (block 11), not the KV's storage. A 204 MiB pool replaces the resident attention KV's 1 632 MiB at 103k / 2 448 MiB at 180k, and the freed VRAM goes to the expert arena: 103k plain decode, -n 2000, 23 579.8 -> 25 018.6 MiB (+1 438.8 MiB, +18 slots/table), expert hit 96.26 -> 97.02 %, cold reads 42.0 -> 31.6 GiB. The pool's own cost is 0.10-0.11 ms/token (mark/claim/map+fill) with fills 0.03-0.05 ms/step at 92-99 % hits, which is why a better page policy (LRU / F-LRU / a heat prior) is measured dead at this shape. Full numbers and the three-depth table: ../wip/kv-residency/BA-POOL-DESIGN.md §7-§8. PURITY (the pool). Greedy text pool == the resident sparse arm at 5.3k (332 dd1981213373), 51 475 depth (854 43b30de151b9) and 180k (861 263c7f2be4d9), with the dense arm differing as documented (GREEDY-PURITY §45/§63); LLAMA_KV_POOL_VERIFY=1 0 mismatches on every arm; gate-prefill-logits --ab "LLAMA_KV_REGION_POOL=..." 0.000000 / 100.000 % on the pool arm (base PPL 2.9225, bit-identical to the campaign's own base); gate-park-idle-slots, gate-ckpt-reuse and gate-state-pipe PASS on a pooled cache (the mirror is authoritative, which is what makes them trivial); test-backend-ops -o FLASH_ATTN_QSA pass; no GPU faults; and `--fit` accepts the arms that only fit with the pool (-ncmoe 21/22 at -c 262144: refused without it, accepted with it; -fitp moves 3 264 MiB from the device row to Host). ========================================================================== PART 3 -- a STREAMED cache takes the sparse decode arm (B2) ========================================================================== A cache that is streaming at the depth it reads -- a window the used extent has passed, or a pool -- takes the sparse QSA decode arm; a resident cache keeps the dense one. llama_kv_cache::is_streaming() plus the qwen4exp arm policy, LLAMA_QSA_DENSE_DECODE_STREAM=0 to restore the old behaviour. Measured on a spilled KV (Flash-Next IQ3_XXS, -ncmoe 48, q8_0, 1 GPU, -n 400, 2 reps): +34.3 % at 102 899 depth (23.42 -> 31.43 t/s) and +47.3 % at 180 035 (16.51 -> 24.31); a resident cache byte-identical (853 77a40bf40be1). This is a decode-ARM choice, i.e. a different attention regime (like GREEDY-PURITY §45/§63), so a streamed arm's text differs from the old dense-arm text by construction and a resident arm is the oracle. ========================================================================== DEFAULT OFF, for both placements ========================================================================== Neither knob is a speed feature on a config whose KV fits: the window costs the depth below W (11-26 %) and the pool costs the sparse-vs-dense gap (-7 % at 103k, -11 % at 180k). They are FITTABILITY features -- they turn an OOM into a run and they hand the freed VRAM to the expert arena -- so both are opt-in and both stay byte-identical, including the OOM, with their knobs unset. Do not "fix" the defaults. Goal C (the MTP drafter ring, TODO ggml-org#121) joins the same block -- it is the same claim applied to the draft context, and its default follows the delivery's own rule because it measures positive. `LLAMA_SPEC_DRAFT_WINDOW` gives the MTP draft context a sliding window instead of a `-c`-sized KV: unset or `auto` is the adaptive policy (a quarter of the context, clamped to [32768, 65536] cells), `0` is off (byte-identical to a build without it) and `N` is a cell count. The drafter reads its last few thousand tokens, so a window at or above that is free and one far below it costs 7-9 % of decode; the clamps keep it above that band, and the target verifies every token it proposes, so a truncated draft can only be slower. The ring is the shipped reclaim in `llama_kv_cache::find_slot` (`n_swa`), not a new allocator, and the derived kq mask stays valid -- its predicate compares each cell's POSITION, so a recycled cell reports its new one. The VRAM win needed one more piece: an embedded MTP head has no GGUF of its own, so the slab's draft reserve was the flat 3584 MiB and the freed VRAM never reached the expert arena. For an embedded MTP head with an active window the reserve is now derived from the model's own metadata with the weights zeroed (they are the target's) and the KV sized by the window: aux 3.50 -> 0.76 GiB, i.e. the arena gains ~2.8 GiB. A separate MTP draft GGUF (qwen4exp/Flash-Next) and an un-windowed run keep the flat constant exactly as before, and a declined arena preflight now re-evaluates when the smaller real value arrives instead of latching on the load-time estimate. Measured (1 GPU; one R9700; `-n 2000`/`-n 3000`; static depth 3; interleaved): * 35B-A3B Q8_0 `-ncmoe 48 -c 262144` q8_0 KV, 51 433-token prompt: arena 20 910 -> 23 715 MiB (residency 64.1 -> 72.7 %), decode 111.2 -> 113.7 t/s at `-n 3000` (+2.2 %; +2.8-4.9 % at `-n 2000`), prefill +3.4 %, drafts byte-for-byte the same count (1995/3011) -- the window truncates nothing the drafter used. * dense 27B UD-Q4_K_XL `-c 102400`, MTP Protocol A `-n 3000`, reasoning-pinned: layer 71.9 -> 72.1, tensor 72.6 -> 72.5 (neutral), acceptance 2083/2747 identical in all four arms. * target greedy text byte-identical across off/auto/4096, and plain == draft-mtp == draft-mtp(W=512) at `-c 16384` with a 5256-token prompt and 3000 generated tokens (10 158 chars, sha 99b267e8dc3e), i.e. no wrong answer under constant cell reuse. * gates on a windowed draft: `gate-park-idle-slots.sh` (35B, -ncmoe 48, `-c 65536`: 3 park moves, park == lazyoff), `gate-ckpt-reuse.sh` (4B, `-c 131072`: draft cache 33280 of 131072), `gate-state-pipe.sh` (35B, `-c 65536`: all five arms) -- all PASS with `MTP draft KV window = 32768 cells` in their logs. r194 corner fixes (found by a configuration battery against Flash-Next after r193): * LLAMA_KV_REGION_POOL is capped at the cache's own cell count. =1000000 on a 262144-cell context used to take a 12451 MiB device pool of 250000 pages where only 65536 blocks exist (never claimed, arena -4 GiB); it is now 3264 MiB / 65536 pages, and a small context clamps the same way. * the draft KV window sizes only the reserve of the cache it actually windows. A separate -md MTP head (Flash-Next) keeps its full -c cache, but the reserve was derived with the window: 921 MiB where the honest number is 1566 (kv 217 vs 862) at -c 262144, the under-charge direction. Embedded heads (qwen3.5/3.6/3.8) are unchanged (776 MiB on the 35B). The VRAM cliff at -c 262144 is documented (not code): the 768 MiB default headroom is one hipBLASLt workspace short for the first prefill, GGML_CUDA_SLAB_HEADROOM_MIB=1536 is 3/3 requests clean. Amendment (TODO ggml-org#129's sibling): `-nkvo` declines the window, and the streamed arm keys on the placement. The window is a DEVICE region plus a pinned host tail, but its guard did not test `offload`: with `-nkvo` the per-layer buffer is chosen inside `if (offload)` and stays plain pageable host memory, while the plan block still logged "WINDOWED KV ENABLED", reserved pinned-RAM spill budget and left `kv_resident_cells` set. `is_streaming()` then keyed the streamed (sparse) decode arm on that plan -- qwen4exp consumes it -- for a KV with no region at all. Measured: `-nkvo LLAMA_KV_RESIDENT_CELLS=64` built a plain `CPU KV buffer` of the whole context while announcing a 64-cell VRAM window. The window now declines once, with the reason (the pool already declines on `!offload`), so `-nkvo` means "no streamed placement"; `is_streaming()` tests `kv_region`, the placement actually taken, which also covers a device cache whose region buft the backend refused. Text is unchanged in every arm (the decline is a no-op: `-nkvo` + window already read as `-nkvo` alone). Amendment (issue ggml-org#264): the draft window is PER SEQUENCE, and under `--kv-unified` its cell count is `(win + one batch) x n_seq_max`. A unified cache holds every sequence in ONE stream, so the r193 sizing (`win + n_ubatch` cells) was shared by all of them: once the first sequence had filled its window the tail was all the room left, the tail is where that sequence's own ring writes, and a second sequence's first batch had no contiguous run to be placed in -- `find_slot` refused, and every request on that slot answered `decode() failed: failed to process speculative batch` (HTTP 500) while the drafter ran. Reported on `--kv-unified -np 2` with a 65 536-cell window at `-c 262144` after slot 0 held ~100k tokens; reproduced here with a forced 8192-cell window. A per-stream cache (no `--kv-unified`) already sized each stream separately and is unchanged. `llama_spec_draft_kv_cells()` is now the one geometry function -- the cache (`create_memory`), the slab's draft reserve estimate and the "is a window active" test in `common` all call it, so the reserve can never under-charge an allocation. It grants `win` per sequence plus one placeable batch (`(win + n_ubatch) * n_seq_max`, capped at the context), and DECLINES the window when that does not fit the context per sequence rather than lowering it to `per_seq - n_ubatch`: a window that small saves one batch of cells per sequence and masks the drafter's newest cells to do it. `llama_spec_draft_window_cells()` stays the policy (it is the per-sequence window). n_seq_max == 1 -- every `llama-cli`/`llama-bench` run -- measures exactly what it did (cells 1536 for a 1024-cell window at `-c 8192`), so no single-sequence arm changes at all. Measured (dense 27B, 1 GPU, `-np 2 --kv-unified`): the issue's scenario now answers both slots, and `scripts/gate-spec-draft-window.sh` (new) drives 6 requests over 2 slots with a 1024-cell window -- both rings wrapping, prompts full re-prefilled by swapping them between slots -- with output byte-identical to `LLAMA_SPEC_DRAFT_WINDOW=0` on every step and draft acceptance identical (17/36, 23/23). Greedy text `plain == draft-mtp == draft-mtp(W=1024) == draft-mtp(W=0)` (876 chars, sha 8c8fd395402f) at `-c 16384`. And the reserve now charges a per-STREAM (no `--kv-unified`) draft cache for every stream it allocates: `n_seq_max x` the per-stream cell count. Before, a multi-slot windowed MTP server without `--kv-unified` (35B-A3B `-ncmoe 40 -np 2 -c 8192`, window 1024: 2 x 1536 = 3072 cells allocated, 1536 charged) under-charged the slab's aux reserve by one stream's window -- the direction the reserve header calls dangerous. Measured: 3072 cells reported on both the unified and the per-stream arm now.
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Nov 1, 2026
…W (Goal A) and an attendance POOL (Goal B), both opt-in Goals A and B of TODO ggml-org#118, promoted from the `wip/kv-residency` campaign. This block is the delivery's "the KV does not have to be O(-c) of VRAM" work: TWO opt-in placements of the same cache, and each one is byte-identical to a build without it when its knob is unset. * the WINDOW (`LLAMA_KV_RESIDENT_CELLS=<cells>|auto`): the newest W cells stay in VRAM, everything older spills to pinned system RAM in the SAME VA reservation -- a positional window, no kernel or op change; * the POOL (`LLAMA_KV_REGION_POOL=<cells>`): the authoritative copy of the WHOLE context in a pinned host mirror, and a compact device pool of the pages a decode step actually attends to, which the QSA sparse read resolves through a page table (`GGML_OP_KV_POOL`). They are mutually exclusive by construction (the pool declines while a window is active) and they answer the same question from opposite ends: the window keeps the *newest* cells hot, the pool keeps the *attended* cells hot. Both report `is_streaming()`, so a streamed cache takes the sparse QSA decode arm (B2, below). ========================================================================== PART 1 -- the WINDOW (Goal A, promoted in r178) ========================================================================== Goal A of TODO ggml-org#118, promoted from the `wip/kv-residency` campaign. WHAT IT DOES. The KV cache's VRAM cost becomes a WINDOW of the newest `W` cells instead of `-c` cells: one VA reservation (a CUDA/HIP VMM region) holds the whole cache, the window's cells are backed by VRAM and everything below them by pinned system RAM. `set_rows`, the in-place rope shift, `state_write/read`, the kq mask and the FA kernels keep addressing one contiguous range, so no kernel and no op changes. The window slides with the watermark in whole map units, so a remap happens once per few thousand tokens and the apparatus itself is free (a zero-spill arm measures the same as plain). WHY. (a) A context that OOMs today runs: 27B Q8_0 `-c 262144` (8704 MiB of KV) now runs on one 32 GiB card at 128 MiB VRAM + 8576 MiB pinned host for the KV. (b) With host-resident MoE experts, the VRAM the KV does not need *yet* goes to the expert-cache arena: measured at `-c 262144`, `-n 2000`, `-ncmoe` = the model's full layer count, 51 433-token prompt, W at or above the run's depth = **+2.2 to +2.9 GiB of arena** (+3.9 to +6.7 points of residency) for free -- 122B-A10B Q4_K_XL +3.8 % decode and +4.7 % prefill, 35B-A3B Q8_0 -0.9 % decode and +3 % prefill; a `W` 35 k cells BELOW the run depth costs 11-26 % (the spill is read every token). OPT-IN, AND ONLY WHEN ASKED FOR. `LLAMA_KV_RESIDENT_CELLS=<cells>` (a number) or `=auto` (`--fit` sizes it, and only spills a context the user pinned with `-c`); unset/0 = no window. With no window the KV takes the PLAIN device buffer, so a run without the knob is byte-identical to a build without this block -- including its OOM (verified). `LLAMA_KV_SPILL_RAM_PCT` (85 % of MemAvailable) caps the pinned spill and widens the window rather than being OOM-killed; `LLAMA_KV_REGION=0` disables the provider; `LLAMA_KV_REGION_QUARANTINE=0` and `LLAMA_KV_REGION_DEBUG/TRACE/CANARY/DUMP` are the diagnosis switches. PURITY (the window). A spilled KV is numerically transparent: prefill-logit **KLD -0.000000 / 100.000 %** on a spilling 27B arm and -0.000000 / 99.994 % on a spilling Flash-Next (two KV caches: the attention KV and the QSA indexer), text byte-identical on 27B (f16 and q8_0), 4B, 35B-A3B and Flash-Next, and the state paths, the context-checkpoint path and the MTP verify widths all green on arms that provably spill. Two driver hazards are held: a kind flip zeroes a neighbouring live host mapping unless the released physical is held across the create (`LLAMA_KV_REGION_QUARANTINE`, default on -- `=0` reproduces the corruption), and every tensor in a windowed region is placed on the driver's map granularity so a slide step coincides with a mapping. An idle-slot park is REFUSED on a region-backed cache (the server then saves the slot to the prompt cache and clears it, which is byte-identical to the parking gate's reference) because a park moves cells above the region's mapped watermark through the copy engine, which faults the GPU. FIT. `--fit` sizes and reports the window (`auto`), or honours and reports a numeric `W`: the resident/spill split, the VRAM saved, and the per-token read cost at the model's full context from the backend's calibrated link rate. The fit identifies the KV's bytes by the region buffer TYPE, and its measurement context is a `no_alloc` probe that declines a window -- so the probe takes the region buffer explicitly (`llama_kv_region_set_probe`); without that the fit cannot see the KV, reports an over-budget config and aborts instead of sizing the window (the r178 regression). GATES (1 GPU, gfx1201): default path byte-identical (`5ba44647188f`) and still OOMs; VMM selftest PASS and FAIL with the hold disabled; windowed arms 305 `e2cea6fa6670` = plain at W=1024/2048/4096 (spilling at 1024: 128 MiB host), `QUARANTINE=0` -> 325 `fb65430049e9` (the hazard); `--fit` sizes `auto` (96680 of 262144 cells, 3210 MiB resident) and reports a numeric W; `gate-ckpt-reuse.sh` / `gate-state-pipe.sh` / MTP verify widths on spilling arms; `test-backend-ops -o FLASH_ATTN_QSA` 26/26; `check-gpu-faults.sh` clean. Not in this block: the campaign's Goal B (a sparse attended set) and Goal C (the MTP drafter ring, `LLAMA_SPEC_DRAFT_WINDOW`) -- both remain campaign work -- and A1 (the superseded two-base FA read). Records: `wip/kv-residency/A2-MIXED-BACKING.md` (§3.7.9, §3.7.11), `HANDOVER.md`. MULTI-DEVICE `--fit` (r181): the KV-region glue is now safe on a Meta (tensor-split) device, and `auto`'s decision reaches the cache as a decision. r178 made default `--fit` abort on ANY `-sm tensor` run with more than one device: the fit's KV probes and the cache's own region lookups call `ggml_backend_dev_backend_reg(dev)` and hand it to `ggml_backend_reg_get_proc_address`, and a Meta device has no backend reg (`device->reg == NULL`), so `GGML_ASSERT(reg)` fired at model load. Three paths asserted: the fit probe (any run), the runtime buft lookup (a numeric W), and the spill budget/link lookups (a numeric W below `-c`). The window is one VMM region per device and a tensor split has no per-device region buffer type, so the backend simply has no answer there -- which is now what it says: a null reg reads as "not provided", the window is declined with one message naming the tensor split (fit and cache), and the KV stays fully resident. A resolved-to-child reg in the fit (the same Meta->simple-device walk the split accounting already does) keeps the identification exact if a multi-device window ever exists. Three wiring defects in the same code, all visible on ONE device: - `auto`'s "no window needed" decision (0) was indistinguishable from "nobody decided", so the cache warned "--fit did not run" immediately after the fit had decided exactly that. `llama_kv_region_set_resident_cells` now records that a decision was made (`llama_kv_region_resident_cells_decided`), and a decided 0 is silent. - every run without the knob logged "the windowed KV is unavailable for this cache (no spilled cells)". That message now only fires when a window was actually requested and declined for a real reason. - the pinned-RAM ceiling clamp could raise W past the VRAM budget and then be reported as "does not make this fit either". It is now only taken while the wider window still meets the VRAM target; otherwise the fit says the ceiling cannot be served at this `-c` and drops the window (which the fit then fits by reducing the context). That ordering is not cosmetic: an intermediate form of this fix accepted a 235 GiB pinned spill plan for a 4B at `-c 8388608`, and creating it OOM-killed the test box. GATES (the window, gfx1201): `--fit on` (default) at 2 and 3 devices, `-sm tensor`, with no knob / a numeric W / `auto`, fit on and off: no assert, tokens produced, exactly one message per requested window. `-sm layer` 2 devices and 1 GPU still take the window per device (numeric W), and `auto` still sizes the 27B Q8_0 `-c 262144` q8_0 arm identically (123265 of 262144 cells, 4092.8 MiB resident / 4611.2 MiB spilling). One device, no knob: no KV message at all. Purity unchanged: plain vs a SPILLING windowed arm prefill-logit KLD 0.000000 / 99.990 % (q8_0 KV), greedy text byte-identical on that arm; 35B-A3B (1 GPU and 2-GPU `-sm tensor`), dense 27B and the canonical 27B Q8_0 prefill-logit gate (0.000000 / 100.000 %) byte-identical to r180; MTP Protocol A unchanged (tensor acceptance 0.60816 = 1937/3185, plain == draft-mtp); no GPU faults. ========================================================================== PART 2 -- the ATTENDANCE POOL (Goal B, promoted in r190) ========================================================================== The attention KV lives twice: its AUTHORITATIVE copy in a pinned host MIRROR (cell-indexed, so the writers, state_write/state_read, the K-shift, defrag and seq_park all work on it unchanged -- the writer rule) and a compact DEVICE POOL of pages of one indexer block (compress_ratio cells) with a page table block -> slot and its inverse. A decode step resolves its top-k selection through the table and fills the pages it missed from the mirror; the QSA reader gathers K/V at the pool slots while the mask stays cell-indexed. LLAMA_KV_REGION_POOL=<cells>, unset/0 = off = byte-identical. Contents. - ggml/src/ggml-cuda/kv-pool.{cu,cuh}: GGML_OP_KV_POOL. MARK sets use[slot] = epoch for every page this launch reads AND every page the batch just wrote (the graph's k_idxs), and queues the written ones for re-fill; CLAIM takes a slot for each DISTINCT missing block (the table CAS is the dedupe) and never takes a slot MARK protected; MAP+FILL writes each selected cell's pool position into the reader's K/V id list and copies the claimed and dirty pages from the mirror, K and V sharing slots. The epoch is a device counter incremented once per launch: the graph bakes pointers, never counters, and nothing is allocated per launch. - ggml-cuda.cu: the pool's pinned host mirror buffer type -- a DEVICE buffer type whose allocation is pinned host memory (`ROCm_Host` reports is_host, which would send the KV's writers and the FA read to the CPU on a discrete device), and its proc-address entry. - llama-kv-cache: the eligibility, the per-layer pool tensors (pool_k/pool_v, tbl, inv, use, one shared counter block), the resolve wiring into the QSA id list, kv_pool_serves() (a batch too wide for the pool takes the cell-indexed path), the teardown accounting (LLAMA_KV_POOL_STATS takes a PATH: a line on stderr sits inside the generated text), and memory_breakdown() charging the mirror to the host bucket so `--fit` does not reserve it as VRAM. - llama-memory-hybrid-idx / llama-memory-hybrid / llama-memory: the second id list (the K/V gather follows the page table while the mask stays cell-indexed), the flag threading, and the pool's byte accounting for `--fit` (llama_get_kv_pool_bytes()). - models/qwen4exp.cpp: a pooled cache reports is_streaming() and the sparse arm uses the pool's id list; the MTP draft's own cache is never pooled (its attention is dense). - llama-context / the async state copies: the mirror's buffer type is accepted by the batched save and restore (its bytes are host memory, staged through the pinned state_stage). - common/fit.cpp + src/llama-ext.h: the pool's split in --fit's arithmetic and report (the mirror is pinned host RAM, the pool is VRAM), and no context-reduction interpolation while the pool is active -- the pool's VRAM is fixed, so reducing -c frees nothing and the interpolation would divide by a near-zero bytes-per-context delta. Invariants, each one caught by the greedy text. 1. MARK then CLAIM: a claim must never evict a page the same launch reads. Without MARK the round-robin victim could be a page another row still needs (the text diverged ~400 chars in, and a pool larger than the whole cache hid it completely). 2. Claim ATTEMPTS are not distinct blocks: a slot per id attempt wrapped the cursor within one 4-row batch, so two blocks shared a slot and a just-resolved block went unresident. The table CAS dedupes first, so only distinct blocks consume a slot and kv_pool_serves() bounds the distinct count. 3. No transient scratch in a captured graph: the fill list lived in a ggml_cuda_pool_alloc that is freed at the end of the op, and a captured graph bakes the pointer, so a replay wrote into whatever op had been handed that block ("values verify clean, text differs run to run"). It lives in the counters tensor. 4. The mirror is AUTHORITATIVE: the writers land in it and a declared page is re-filled from it before the attention reads it, so an eviction costs nothing and nothing has to be invalidated -- except by a path that rewrites cells in place without going through the writers (the K-shift, a state restore), which calls kv_pool_invalidate(). 5. Eligibility is narrow on purpose: one stream, non-MLA, K and V both present, !v_trans, a uniform compress_ratio and cell geometry, no window active, a device-offloaded cache, and only the trunk context of a qwen4exp model. Anything else declines with one message and the KV is unchanged. 6. The pool is floored at one decode band's worth of blocks (8 x ceil(width/page) pages) so a verify batch cannot exhaust the slot budget, and the mirror is bounded at creation by LLAMA_KV_SPILL_RAM_PCT (it is pinned, non-swappable RAM) -- over the ceiling the pool is declined loudly instead of being OOM-killed. Measured (Flash-Next GSQ-IQ3_XXS, 1 GPU, -ncmoe 48, q8_0, the PLE flags, arms interleaved in one batch, -n 512, MTP depth 4; t/s and tokens/step): depth (ctx) dense sparse pool (204 MiB) text (-n 64) 5 298 (16 384) 72.09 71.58 71.27 pool == sparse: 332 chars dd1981213373 102 899 (131 072) 59.10 54.70 54.65 (5.3k / 51 475 references; dense differs) 180 035 (196 608) 48.94 43.16 43.41 pool == sparse: 861 chars 263c7f2be4d9 The pool lands ON the sparse ceiling at every depth (+0.5 / +0.6 / +0.58 %), so its placement is free and what remains against a resident KV (-7 % / -11 %) is the sparse decode arm's own indexer cost (block 11), not the KV's storage. A 204 MiB pool replaces the resident attention KV's 1 632 MiB at 103k / 2 448 MiB at 180k, and the freed VRAM goes to the expert arena: 103k plain decode, -n 2000, 23 579.8 -> 25 018.6 MiB (+1 438.8 MiB, +18 slots/table), expert hit 96.26 -> 97.02 %, cold reads 42.0 -> 31.6 GiB. The pool's own cost is 0.10-0.11 ms/token (mark/claim/map+fill) with fills 0.03-0.05 ms/step at 92-99 % hits, which is why a better page policy (LRU / F-LRU / a heat prior) is measured dead at this shape. Full numbers and the three-depth table: ../wip/kv-residency/BA-POOL-DESIGN.md §7-§8. PURITY (the pool). Greedy text pool == the resident sparse arm at 5.3k (332 dd1981213373), 51 475 depth (854 43b30de151b9) and 180k (861 263c7f2be4d9), with the dense arm differing as documented (GREEDY-PURITY §45/§63); LLAMA_KV_POOL_VERIFY=1 0 mismatches on every arm; gate-prefill-logits --ab "LLAMA_KV_REGION_POOL=..." 0.000000 / 100.000 % on the pool arm (base PPL 2.9225, bit-identical to the campaign's own base); gate-park-idle-slots, gate-ckpt-reuse and gate-state-pipe PASS on a pooled cache (the mirror is authoritative, which is what makes them trivial); test-backend-ops -o FLASH_ATTN_QSA pass; no GPU faults; and `--fit` accepts the arms that only fit with the pool (-ncmoe 21/22 at -c 262144: refused without it, accepted with it; -fitp moves 3 264 MiB from the device row to Host). ========================================================================== PART 3 -- a STREAMED cache takes the sparse decode arm (B2) ========================================================================== A cache that is streaming at the depth it reads -- a window the used extent has passed, or a pool -- takes the sparse QSA decode arm; a resident cache keeps the dense one. llama_kv_cache::is_streaming() plus the qwen4exp arm policy, LLAMA_QSA_DENSE_DECODE_STREAM=0 to restore the old behaviour. Measured on a spilled KV (Flash-Next IQ3_XXS, -ncmoe 48, q8_0, 1 GPU, -n 400, 2 reps): +34.3 % at 102 899 depth (23.42 -> 31.43 t/s) and +47.3 % at 180 035 (16.51 -> 24.31); a resident cache byte-identical (853 77a40bf40be1). This is a decode-ARM choice, i.e. a different attention regime (like GREEDY-PURITY §45/§63), so a streamed arm's text differs from the old dense-arm text by construction and a resident arm is the oracle. ========================================================================== DEFAULT OFF, for both placements ========================================================================== Neither knob is a speed feature on a config whose KV fits: the window costs the depth below W (11-26 %) and the pool costs the sparse-vs-dense gap (-7 % at 103k, -11 % at 180k). They are FITTABILITY features -- they turn an OOM into a run and they hand the freed VRAM to the expert arena -- so both are opt-in and both stay byte-identical, including the OOM, with their knobs unset. Do not "fix" the defaults. Goal C (the MTP drafter ring, TODO ggml-org#121) joins the same block -- it is the same claim applied to the draft context, and its default follows the delivery's own rule because it measures positive. `LLAMA_SPEC_DRAFT_WINDOW` gives the MTP draft context a sliding window instead of a `-c`-sized KV: unset or `auto` is the adaptive policy (a quarter of the context, clamped to [32768, 65536] cells), `0` is off (byte-identical to a build without it) and `N` is a cell count. The drafter reads its last few thousand tokens, so a window at or above that is free and one far below it costs 7-9 % of decode; the clamps keep it above that band, and the target verifies every token it proposes, so a truncated draft can only be slower. The ring is the shipped reclaim in `llama_kv_cache::find_slot` (`n_swa`), not a new allocator, and the derived kq mask stays valid -- its predicate compares each cell's POSITION, so a recycled cell reports its new one. The VRAM win needed one more piece: an embedded MTP head has no GGUF of its own, so the slab's draft reserve was the flat 3584 MiB and the freed VRAM never reached the expert arena. For an embedded MTP head with an active window the reserve is now derived from the model's own metadata with the weights zeroed (they are the target's) and the KV sized by the window: aux 3.50 -> 0.76 GiB, i.e. the arena gains ~2.8 GiB. A separate MTP draft GGUF (qwen4exp/Flash-Next) and an un-windowed run keep the flat constant exactly as before, and a declined arena preflight now re-evaluates when the smaller real value arrives instead of latching on the load-time estimate. Measured (1 GPU; one R9700; `-n 2000`/`-n 3000`; static depth 3; interleaved): * 35B-A3B Q8_0 `-ncmoe 48 -c 262144` q8_0 KV, 51 433-token prompt: arena 20 910 -> 23 715 MiB (residency 64.1 -> 72.7 %), decode 111.2 -> 113.7 t/s at `-n 3000` (+2.2 %; +2.8-4.9 % at `-n 2000`), prefill +3.4 %, drafts byte-for-byte the same count (1995/3011) -- the window truncates nothing the drafter used. * dense 27B UD-Q4_K_XL `-c 102400`, MTP Protocol A `-n 3000`, reasoning-pinned: layer 71.9 -> 72.1, tensor 72.6 -> 72.5 (neutral), acceptance 2083/2747 identical in all four arms. * target greedy text byte-identical across off/auto/4096, and plain == draft-mtp == draft-mtp(W=512) at `-c 16384` with a 5256-token prompt and 3000 generated tokens (10 158 chars, sha 99b267e8dc3e), i.e. no wrong answer under constant cell reuse. * gates on a windowed draft: `gate-park-idle-slots.sh` (35B, -ncmoe 48, `-c 65536`: 3 park moves, park == lazyoff), `gate-ckpt-reuse.sh` (4B, `-c 131072`: draft cache 33280 of 131072), `gate-state-pipe.sh` (35B, `-c 65536`: all five arms) -- all PASS with `MTP draft KV window = 32768 cells` in their logs. r194 corner fixes (found by a configuration battery against Flash-Next after r193): * LLAMA_KV_REGION_POOL is capped at the cache's own cell count. =1000000 on a 262144-cell context used to take a 12451 MiB device pool of 250000 pages where only 65536 blocks exist (never claimed, arena -4 GiB); it is now 3264 MiB / 65536 pages, and a small context clamps the same way. * the draft KV window sizes only the reserve of the cache it actually windows. A separate -md MTP head (Flash-Next) keeps its full -c cache, but the reserve was derived with the window: 921 MiB where the honest number is 1566 (kv 217 vs 862) at -c 262144, the under-charge direction. Embedded heads (qwen3.5/3.6/3.8) are unchanged (776 MiB on the 35B). The VRAM cliff at -c 262144 is documented (not code): the 768 MiB default headroom is one hipBLASLt workspace short for the first prefill, GGML_CUDA_SLAB_HEADROOM_MIB=1536 is 3/3 requests clean. Amendment (TODO ggml-org#129's sibling): `-nkvo` declines the window, and the streamed arm keys on the placement. The window is a DEVICE region plus a pinned host tail, but its guard did not test `offload`: with `-nkvo` the per-layer buffer is chosen inside `if (offload)` and stays plain pageable host memory, while the plan block still logged "WINDOWED KV ENABLED", reserved pinned-RAM spill budget and left `kv_resident_cells` set. `is_streaming()` then keyed the streamed (sparse) decode arm on that plan -- qwen4exp consumes it -- for a KV with no region at all. Measured: `-nkvo LLAMA_KV_RESIDENT_CELLS=64` built a plain `CPU KV buffer` of the whole context while announcing a 64-cell VRAM window. The window now declines once, with the reason (the pool already declines on `!offload`), so `-nkvo` means "no streamed placement"; `is_streaming()` tests `kv_region`, the placement actually taken, which also covers a device cache whose region buft the backend refused. Text is unchanged in every arm (the decline is a no-op: `-nkvo` + window already read as `-nkvo` alone). Amendment (issue ggml-org#264): the draft window is PER SEQUENCE, and under `--kv-unified` its cell count is `(win + one batch) x n_seq_max`. A unified cache holds every sequence in ONE stream, so the r193 sizing (`win + n_ubatch` cells) was shared by all of them: once the first sequence had filled its window the tail was all the room left, the tail is where that sequence's own ring writes, and a second sequence's first batch had no contiguous run to be placed in -- `find_slot` refused, and every request on that slot answered `decode() failed: failed to process speculative batch` (HTTP 500) while the drafter ran. Reported on `--kv-unified -np 2` with a 65 536-cell window at `-c 262144` after slot 0 held ~100k tokens; reproduced here with a forced 8192-cell window. A per-stream cache (no `--kv-unified`) already sized each stream separately and is unchanged. `llama_spec_draft_kv_cells()` is now the one geometry function -- the cache (`create_memory`), the slab's draft reserve estimate and the "is a window active" test in `common` all call it, so the reserve can never under-charge an allocation. It grants `win` per sequence plus one placeable batch (`(win + n_ubatch) * n_seq_max`, capped at the context), and DECLINES the window when that does not fit the context per sequence rather than lowering it to `per_seq - n_ubatch`: a window that small saves one batch of cells per sequence and masks the drafter's newest cells to do it. `llama_spec_draft_window_cells()` stays the policy (it is the per-sequence window). n_seq_max == 1 -- every `llama-cli`/`llama-bench` run -- measures exactly what it did (cells 1536 for a 1024-cell window at `-c 8192`), so no single-sequence arm changes at all. Measured (dense 27B, 1 GPU, `-np 2 --kv-unified`): the issue's scenario now answers both slots, and `scripts/gate-spec-draft-window.sh` (new) drives 6 requests over 2 slots with a 1024-cell window -- both rings wrapping, prompts full re-prefilled by swapping them between slots -- with output byte-identical to `LLAMA_SPEC_DRAFT_WINDOW=0` on every step and draft acceptance identical (17/36, 23/23). Greedy text `plain == draft-mtp == draft-mtp(W=1024) == draft-mtp(W=0)` (876 chars, sha 8c8fd395402f) at `-c 16384`. And the reserve now charges a per-STREAM (no `--kv-unified`) draft cache for every stream it allocates: `n_seq_max x` the per-stream cell count. Before, a multi-slot windowed MTP server without `--kv-unified` (35B-A3B `-ncmoe 40 -np 2 -c 8192`, window 1024: 2 x 1536 = 3072 cells allocated, 1536 charged) under-charged the slab's aux reserve by one stream's window -- the direction the reserve header calls dangerous. Measured: 3072 cells reported on both the unified and the per-stream arm now.
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Nov 1, 2026
…W (Goal A) and an attendance POOL (Goal B), both opt-in Goals A and B of TODO ggml-org#118, promoted from the `wip/kv-residency` campaign. This block is the delivery's "the KV does not have to be O(-c) of VRAM" work: TWO opt-in placements of the same cache, and each one is byte-identical to a build without it when its knob is unset. * the WINDOW (`LLAMA_KV_RESIDENT_CELLS=<cells>|auto`): the newest W cells stay in VRAM, everything older spills to pinned system RAM in the SAME VA reservation -- a positional window, no kernel or op change; * the POOL (`LLAMA_KV_REGION_POOL=<cells>`): the authoritative copy of the WHOLE context in a pinned host mirror, and a compact device pool of the pages a decode step actually attends to, which the QSA sparse read resolves through a page table (`GGML_OP_KV_POOL`). They are mutually exclusive by construction (the pool declines while a window is active) and they answer the same question from opposite ends: the window keeps the *newest* cells hot, the pool keeps the *attended* cells hot. Both report `is_streaming()`, so a streamed cache takes the sparse QSA decode arm (B2, below). ========================================================================== PART 1 -- the WINDOW (Goal A, promoted in r178) ========================================================================== Goal A of TODO ggml-org#118, promoted from the `wip/kv-residency` campaign. WHAT IT DOES. The KV cache's VRAM cost becomes a WINDOW of the newest `W` cells instead of `-c` cells: one VA reservation (a CUDA/HIP VMM region) holds the whole cache, the window's cells are backed by VRAM and everything below them by pinned system RAM. `set_rows`, the in-place rope shift, `state_write/read`, the kq mask and the FA kernels keep addressing one contiguous range, so no kernel and no op changes. The window slides with the watermark in whole map units, so a remap happens once per few thousand tokens and the apparatus itself is free (a zero-spill arm measures the same as plain). WHY. (a) A context that OOMs today runs: 27B Q8_0 `-c 262144` (8704 MiB of KV) now runs on one 32 GiB card at 128 MiB VRAM + 8576 MiB pinned host for the KV. (b) With host-resident MoE experts, the VRAM the KV does not need *yet* goes to the expert-cache arena: measured at `-c 262144`, `-n 2000`, `-ncmoe` = the model's full layer count, 51 433-token prompt, W at or above the run's depth = **+2.2 to +2.9 GiB of arena** (+3.9 to +6.7 points of residency) for free -- 122B-A10B Q4_K_XL +3.8 % decode and +4.7 % prefill, 35B-A3B Q8_0 -0.9 % decode and +3 % prefill; a `W` 35 k cells BELOW the run depth costs 11-26 % (the spill is read every token). OPT-IN, AND ONLY WHEN ASKED FOR. `LLAMA_KV_RESIDENT_CELLS=<cells>` (a number) or `=auto` (`--fit` sizes it, and only spills a context the user pinned with `-c`); unset/0 = no window. With no window the KV takes the PLAIN device buffer, so a run without the knob is byte-identical to a build without this block -- including its OOM (verified). `LLAMA_KV_SPILL_RAM_PCT` (85 % of MemAvailable) caps the pinned spill and widens the window rather than being OOM-killed; `LLAMA_KV_REGION=0` disables the provider; `LLAMA_KV_REGION_QUARANTINE=0` and `LLAMA_KV_REGION_DEBUG/TRACE/CANARY/DUMP` are the diagnosis switches. PURITY (the window). A spilled KV is numerically transparent: prefill-logit **KLD -0.000000 / 100.000 %** on a spilling 27B arm and -0.000000 / 99.994 % on a spilling Flash-Next (two KV caches: the attention KV and the QSA indexer), text byte-identical on 27B (f16 and q8_0), 4B, 35B-A3B and Flash-Next, and the state paths, the context-checkpoint path and the MTP verify widths all green on arms that provably spill. Two driver hazards are held: a kind flip zeroes a neighbouring live host mapping unless the released physical is held across the create (`LLAMA_KV_REGION_QUARANTINE`, default on -- `=0` reproduces the corruption), and every tensor in a windowed region is placed on the driver's map granularity so a slide step coincides with a mapping. An idle-slot park is REFUSED on a region-backed cache (the server then saves the slot to the prompt cache and clears it, which is byte-identical to the parking gate's reference) because a park moves cells above the region's mapped watermark through the copy engine, which faults the GPU. FIT. `--fit` sizes and reports the window (`auto`), or honours and reports a numeric `W`: the resident/spill split, the VRAM saved, and the per-token read cost at the model's full context from the backend's calibrated link rate. The fit identifies the KV's bytes by the region buffer TYPE, and its measurement context is a `no_alloc` probe that declines a window -- so the probe takes the region buffer explicitly (`llama_kv_region_set_probe`); without that the fit cannot see the KV, reports an over-budget config and aborts instead of sizing the window (the r178 regression). GATES (1 GPU, gfx1201): default path byte-identical (`5ba44647188f`) and still OOMs; VMM selftest PASS and FAIL with the hold disabled; windowed arms 305 `e2cea6fa6670` = plain at W=1024/2048/4096 (spilling at 1024: 128 MiB host), `QUARANTINE=0` -> 325 `fb65430049e9` (the hazard); `--fit` sizes `auto` (96680 of 262144 cells, 3210 MiB resident) and reports a numeric W; `gate-ckpt-reuse.sh` / `gate-state-pipe.sh` / MTP verify widths on spilling arms; `test-backend-ops -o FLASH_ATTN_QSA` 26/26; `check-gpu-faults.sh` clean. Not in this block: the campaign's Goal B (a sparse attended set) and Goal C (the MTP drafter ring, `LLAMA_SPEC_DRAFT_WINDOW`) -- both remain campaign work -- and A1 (the superseded two-base FA read). Records: `wip/kv-residency/A2-MIXED-BACKING.md` (§3.7.9, §3.7.11), `HANDOVER.md`. MULTI-DEVICE `--fit` (r181; the window itself reaches a tensor split in r204, at the end of this message): the KV-region glue is now safe on a Meta (tensor-split) device, and `auto`'s decision reaches the cache as a decision. r178 made default `--fit` abort on ANY `-sm tensor` run with more than one device: the fit's KV probes and the cache's own region lookups call `ggml_backend_dev_backend_reg(dev)` and hand it to `ggml_backend_reg_get_proc_address`, and a Meta device has no backend reg (`device->reg == NULL`), so `GGML_ASSERT(reg)` fired at model load. Three paths asserted: the fit probe (any run), the runtime buft lookup (a numeric W), and the spill budget/link lookups (a numeric W below `-c`). r181 makes a null reg read as "not provided" and declines the window with one message naming the tensor split (fit and cache), keeping the KV fully resident -- which is the r181 state; r204, below, is what makes the backend answer there. Three wiring defects in the same code, all visible on ONE device: - `auto`'s "no window needed" decision (0) was indistinguishable from "nobody decided", so the cache warned "--fit did not run" immediately after the fit had decided exactly that. `llama_kv_region_set_resident_cells` now records that a decision was made (`llama_kv_region_resident_cells_decided`), and a decided 0 is silent. - every run without the knob logged "the windowed KV is unavailable for this cache (no spilled cells)". That message now only fires when a window was actually requested and declined for a real reason. - the pinned-RAM ceiling clamp could raise W past the VRAM budget and then be reported as "does not make this fit either". It is now only taken while the wider window still meets the VRAM target; otherwise the fit says the ceiling cannot be served at this `-c` and drops the window (which the fit then fits by reducing the context). That ordering is not cosmetic: an intermediate form of this fix accepted a 235 GiB pinned spill plan for a 4B at `-c 8388608`, and creating it OOM-killed the test box. GATES (the window, gfx1201): `--fit on` (default) at 2 and 3 devices, `-sm tensor`, with no knob / a numeric W / `auto`, fit on and off: no assert, tokens produced, exactly one message per requested window. `-sm layer` 2 devices and 1 GPU still take the window per device (numeric W), and `auto` still sizes the 27B Q8_0 `-c 262144` q8_0 arm identically (123265 of 262144 cells, 4092.8 MiB resident / 4611.2 MiB spilling). One device, no knob: no KV message at all. Purity unchanged: plain vs a SPILLING windowed arm prefill-logit KLD 0.000000 / 99.990 % (q8_0 KV), greedy text byte-identical on that arm; 35B-A3B (1 GPU and 2-GPU `-sm tensor`), dense 27B and the canonical 27B Q8_0 prefill-logit gate (0.000000 / 100.000 %) byte-identical to r180; MTP Protocol A unchanged (tensor acceptance 0.60816 = 1937/3185, plain == draft-mtp); no GPU faults. ========================================================================== PART 2 -- the ATTENDANCE POOL (Goal B, promoted in r190) ========================================================================== The attention KV lives twice: its AUTHORITATIVE copy in a pinned host MIRROR (cell-indexed, so the writers, state_write/state_read, the K-shift, defrag and seq_park all work on it unchanged -- the writer rule) and a compact DEVICE POOL of pages of one indexer block (compress_ratio cells) with a page table block -> slot and its inverse. A decode step resolves its top-k selection through the table and fills the pages it missed from the mirror; the QSA reader gathers K/V at the pool slots while the mask stays cell-indexed. LLAMA_KV_REGION_POOL=<cells>, unset/0 = off = byte-identical. Contents. - ggml/src/ggml-cuda/kv-pool.{cu,cuh}: GGML_OP_KV_POOL. MARK sets use[slot] = epoch for every page this launch reads AND every page the batch just wrote (the graph's k_idxs), and queues the written ones for re-fill; CLAIM takes a slot for each DISTINCT missing block (the table CAS is the dedupe) and never takes a slot MARK protected; MAP+FILL writes each selected cell's pool position into the reader's K/V id list and copies the claimed and dirty pages from the mirror, K and V sharing slots. The epoch is a device counter incremented once per launch: the graph bakes pointers, never counters, and nothing is allocated per launch. - ggml-cuda.cu: the pool's pinned host mirror buffer type -- a DEVICE buffer type whose allocation is pinned host memory (`ROCm_Host` reports is_host, which would send the KV's writers and the FA read to the CPU on a discrete device), and its proc-address entry. - llama-kv-cache: the eligibility, the per-layer pool tensors (pool_k/pool_v, tbl, inv, use, one shared counter block), the resolve wiring into the QSA id list, kv_pool_serves() (a batch too wide for the pool takes the cell-indexed path), the teardown accounting (LLAMA_KV_POOL_STATS takes a PATH: a line on stderr sits inside the generated text), and memory_breakdown() charging the mirror to the host bucket so `--fit` does not reserve it as VRAM. - llama-memory-hybrid-idx / llama-memory-hybrid / llama-memory: the second id list (the K/V gather follows the page table while the mask stays cell-indexed), the flag threading, and the pool's byte accounting for `--fit` (llama_get_kv_pool_bytes()). - models/qwen4exp.cpp: a pooled cache reports is_streaming() and the sparse arm uses the pool's id list; the MTP draft's own cache is never pooled (its attention is dense). - llama-context / the async state copies: the mirror's buffer type is accepted by the batched save and restore (its bytes are host memory, staged through the pinned state_stage). - common/fit.cpp + src/llama-ext.h: the pool's split in --fit's arithmetic and report (the mirror is pinned host RAM, the pool is VRAM), and no context-reduction interpolation while the pool is active -- the pool's VRAM is fixed, so reducing -c frees nothing and the interpolation would divide by a near-zero bytes-per-context delta. Invariants, each one caught by the greedy text. 1. MARK then CLAIM: a claim must never evict a page the same launch reads. Without MARK the round-robin victim could be a page another row still needs (the text diverged ~400 chars in, and a pool larger than the whole cache hid it completely). 2. Claim ATTEMPTS are not distinct blocks: a slot per id attempt wrapped the cursor within one 4-row batch, so two blocks shared a slot and a just-resolved block went unresident. The table CAS dedupes first, so only distinct blocks consume a slot and kv_pool_serves() bounds the distinct count. 3. No transient scratch in a captured graph: the fill list lived in a ggml_cuda_pool_alloc that is freed at the end of the op, and a captured graph bakes the pointer, so a replay wrote into whatever op had been handed that block ("values verify clean, text differs run to run"). It lives in the counters tensor. 4. The mirror is AUTHORITATIVE: the writers land in it and a declared page is re-filled from it before the attention reads it, so an eviction costs nothing and nothing has to be invalidated -- except by a path that rewrites cells in place without going through the writers (the K-shift, a state restore), which calls kv_pool_invalidate(). 5. Eligibility is narrow on purpose: one stream, non-MLA, K and V both present, !v_trans, a uniform compress_ratio and cell geometry, no window active, a device-offloaded cache, and only the trunk context of a qwen4exp model. Anything else declines with one message and the KV is unchanged. 6. The pool is floored at one decode band's worth of blocks (8 x ceil(width/page) pages) so a verify batch cannot exhaust the slot budget, and the mirror is bounded at creation by LLAMA_KV_SPILL_RAM_PCT (it is pinned, non-swappable RAM) -- over the ceiling the pool is declined loudly instead of being OOM-killed. Measured (Flash-Next GSQ-IQ3_XXS, 1 GPU, -ncmoe 48, q8_0, the PLE flags, arms interleaved in one batch, -n 512, MTP depth 4; t/s and tokens/step): depth (ctx) dense sparse pool (204 MiB) text (-n 64) 5 298 (16 384) 72.09 71.58 71.27 pool == sparse: 332 chars dd1981213373 102 899 (131 072) 59.10 54.70 54.65 (5.3k / 51 475 references; dense differs) 180 035 (196 608) 48.94 43.16 43.41 pool == sparse: 861 chars 263c7f2be4d9 The pool lands ON the sparse ceiling at every depth (+0.5 / +0.6 / +0.58 %), so its placement is free and what remains against a resident KV (-7 % / -11 %) is the sparse decode arm's own indexer cost (block 11), not the KV's storage. A 204 MiB pool replaces the resident attention KV's 1 632 MiB at 103k / 2 448 MiB at 180k, and the freed VRAM goes to the expert arena: 103k plain decode, -n 2000, 23 579.8 -> 25 018.6 MiB (+1 438.8 MiB, +18 slots/table), expert hit 96.26 -> 97.02 %, cold reads 42.0 -> 31.6 GiB. The pool's own cost is 0.10-0.11 ms/token (mark/claim/map+fill) with fills 0.03-0.05 ms/step at 92-99 % hits, which is why a better page policy (LRU / F-LRU / a heat prior) is measured dead at this shape. Full numbers and the three-depth table: ../wip/kv-residency/BA-POOL-DESIGN.md §7-§8. PURITY (the pool). Greedy text pool == the resident sparse arm at 5.3k (332 dd1981213373), 51 475 depth (854 43b30de151b9) and 180k (861 263c7f2be4d9), with the dense arm differing as documented (GREEDY-PURITY §45/§63); LLAMA_KV_POOL_VERIFY=1 0 mismatches on every arm; gate-prefill-logits --ab "LLAMA_KV_REGION_POOL=..." 0.000000 / 100.000 % on the pool arm (base PPL 2.9225, bit-identical to the campaign's own base); gate-park-idle-slots, gate-ckpt-reuse and gate-state-pipe PASS on a pooled cache (the mirror is authoritative, which is what makes them trivial); test-backend-ops -o FLASH_ATTN_QSA pass; no GPU faults; and `--fit` accepts the arms that only fit with the pool (-ncmoe 21/22 at -c 262144: refused without it, accepted with it; -fitp moves 3 264 MiB from the device row to Host). ========================================================================== PART 3 -- a STREAMED cache takes the sparse decode arm (B2) ========================================================================== A cache that is streaming at the depth it reads -- a window the used extent has passed, or a pool -- takes the sparse QSA decode arm; a resident cache keeps the dense one. llama_kv_cache::is_streaming() plus the qwen4exp arm policy, LLAMA_QSA_DENSE_DECODE_STREAM=0 to restore the old behaviour. Measured on a spilled KV (Flash-Next IQ3_XXS, -ncmoe 48, q8_0, 1 GPU, -n 400, 2 reps): +34.3 % at 102 899 depth (23.42 -> 31.43 t/s) and +47.3 % at 180 035 (16.51 -> 24.31); a resident cache byte-identical (853 77a40bf40be1). This is a decode-ARM choice, i.e. a different attention regime (like GREEDY-PURITY §45/§63), so a streamed arm's text differs from the old dense-arm text by construction and a resident arm is the oracle. ========================================================================== DEFAULT OFF, for both placements ========================================================================== Neither knob is a speed feature on a config whose KV fits: the window costs the depth below W (11-26 %) and the pool costs the sparse-vs-dense gap (-7 % at 103k, -11 % at 180k). They are FITTABILITY features -- they turn an OOM into a run and they hand the freed VRAM to the expert arena -- so both are opt-in and both stay byte-identical, including the OOM, with their knobs unset. Do not "fix" the defaults. Goal C (the MTP drafter ring, TODO ggml-org#121) joins the same block -- it is the same claim applied to the draft context, and its default follows the delivery's own rule because it measures positive. `LLAMA_SPEC_DRAFT_WINDOW` gives the MTP draft context a sliding window instead of a `-c`-sized KV: unset or `auto` is the adaptive policy (a quarter of the context, clamped to [32768, 65536] cells), `0` is off (byte-identical to a build without it) and `N` is a cell count. The drafter reads its last few thousand tokens, so a window at or above that is free and one far below it costs 7-9 % of decode; the clamps keep it above that band, and the target verifies every token it proposes, so a truncated draft can only be slower. The ring is the shipped reclaim in `llama_kv_cache::find_slot` (`n_swa`), not a new allocator, and the derived kq mask stays valid -- its predicate compares each cell's POSITION, so a recycled cell reports its new one. The VRAM win needed one more piece: an embedded MTP head has no GGUF of its own, so the slab's draft reserve was the flat 3584 MiB and the freed VRAM never reached the expert arena. For an embedded MTP head with an active window the reserve is now derived from the model's own metadata with the weights zeroed (they are the target's) and the KV sized by the window: aux 3.50 -> 0.76 GiB, i.e. the arena gains ~2.8 GiB. A separate MTP draft GGUF (qwen4exp/Flash-Next) and an un-windowed run keep the flat constant exactly as before, and a declined arena preflight now re-evaluates when the smaller real value arrives instead of latching on the load-time estimate. Measured (1 GPU; one R9700; `-n 2000`/`-n 3000`; static depth 3; interleaved): * 35B-A3B Q8_0 `-ncmoe 48 -c 262144` q8_0 KV, 51 433-token prompt: arena 20 910 -> 23 715 MiB (residency 64.1 -> 72.7 %), decode 111.2 -> 113.7 t/s at `-n 3000` (+2.2 %; +2.8-4.9 % at `-n 2000`), prefill +3.4 %, drafts byte-for-byte the same count (1995/3011) -- the window truncates nothing the drafter used. * dense 27B UD-Q4_K_XL `-c 102400`, MTP Protocol A `-n 3000`, reasoning-pinned: layer 71.9 -> 72.1, tensor 72.6 -> 72.5 (neutral), acceptance 2083/2747 identical in all four arms. * target greedy text byte-identical across off/auto/4096, and plain == draft-mtp == draft-mtp(W=512) at `-c 16384` with a 5256-token prompt and 3000 generated tokens (10 158 chars, sha 99b267e8dc3e), i.e. no wrong answer under constant cell reuse. * gates on a windowed draft: `gate-park-idle-slots.sh` (35B, -ncmoe 48, `-c 65536`: 3 park moves, park == lazyoff), `gate-ckpt-reuse.sh` (4B, `-c 131072`: draft cache 33280 of 131072), `gate-state-pipe.sh` (35B, `-c 65536`: all five arms) -- all PASS with `MTP draft KV window = 32768 cells` in their logs. r194 corner fixes (found by a configuration battery against Flash-Next after r193): * LLAMA_KV_REGION_POOL is capped at the cache's own cell count. =1000000 on a 262144-cell context used to take a 12451 MiB device pool of 250000 pages where only 65536 blocks exist (never claimed, arena -4 GiB); it is now 3264 MiB / 65536 pages, and a small context clamps the same way. * the draft KV window sizes only the reserve of the cache it actually windows. A separate -md MTP head (Flash-Next) keeps its full -c cache, but the reserve was derived with the window: 921 MiB where the honest number is 1566 (kv 217 vs 862) at -c 262144, the under-charge direction. Embedded heads (qwen3.5/3.6/3.8) are unchanged (776 MiB on the 35B). The VRAM cliff at -c 262144 is documented (not code): the 768 MiB default headroom is one hipBLASLt workspace short for the first prefill, GGML_CUDA_SLAB_HEADROOM_MIB=1536 is 3/3 requests clean. Amendment (TODO ggml-org#129's sibling): `-nkvo` declines the window, and the streamed arm keys on the placement. The window is a DEVICE region plus a pinned host tail, but its guard did not test `offload`: with `-nkvo` the per-layer buffer is chosen inside `if (offload)` and stays plain pageable host memory, while the plan block still logged "WINDOWED KV ENABLED", reserved pinned-RAM spill budget and left `kv_resident_cells` set. `is_streaming()` then keyed the streamed (sparse) decode arm on that plan -- qwen4exp consumes it -- for a KV with no region at all. Measured: `-nkvo LLAMA_KV_RESIDENT_CELLS=64` built a plain `CPU KV buffer` of the whole context while announcing a 64-cell VRAM window. The window now declines once, with the reason (the pool already declines on `!offload`), so `-nkvo` means "no streamed placement"; `is_streaming()` tests `kv_region`, the placement actually taken, which also covers a device cache whose region buft the backend refused. Text is unchanged in every arm (the decline is a no-op: `-nkvo` + window already read as `-nkvo` alone). Amendment (issue ggml-org#264): the draft window is PER SEQUENCE, and under `--kv-unified` its cell count is `(win + one batch) x n_seq_max`. A unified cache holds every sequence in ONE stream, so the r193 sizing (`win + n_ubatch` cells) was shared by all of them: once the first sequence had filled its window the tail was all the room left, the tail is where that sequence's own ring writes, and a second sequence's first batch had no contiguous run to be placed in -- `find_slot` refused, and every request on that slot answered `decode() failed: failed to process speculative batch` (HTTP 500) while the drafter ran. Reported on `--kv-unified -np 2` with a 65 536-cell window at `-c 262144` after slot 0 held ~100k tokens; reproduced here with a forced 8192-cell window. A per-stream cache (no `--kv-unified`) already sized each stream separately and is unchanged. `llama_spec_draft_kv_cells()` is now the one geometry function -- the cache (`create_memory`), the slab's draft reserve estimate and the "is a window active" test in `common` all call it, so the reserve can never under-charge an allocation. It grants `win` per sequence plus one placeable batch (`(win + n_ubatch) * n_seq_max`, capped at the context), and DECLINES the window when that does not fit the context per sequence rather than lowering it to `per_seq - n_ubatch`: a window that small saves one batch of cells per sequence and masks the drafter's newest cells to do it. `llama_spec_draft_window_cells()` stays the policy (it is the per-sequence window). n_seq_max == 1 -- every `llama-cli`/`llama-bench` run -- measures exactly what it did (cells 1536 for a 1024-cell window at `-c 8192`), so no single-sequence arm changes at all. Measured (dense 27B, 1 GPU, `-np 2 --kv-unified`): the issue's scenario now answers both slots, and `scripts/gate-spec-draft-window.sh` (new) drives 6 requests over 2 slots with a 1024-cell window -- both rings wrapping, prompts full re-prefilled by swapping them between slots -- with output byte-identical to `LLAMA_SPEC_DRAFT_WINDOW=0` on every step and draft acceptance identical (17/36, 23/23). Greedy text `plain == draft-mtp == draft-mtp(W=1024) == draft-mtp(W=0)` (876 chars, sha 8c8fd395402f) at `-c 16384`. And the reserve now charges a per-STREAM (no `--kv-unified`) draft cache for every stream it allocates: `n_seq_max x` the per-stream cell count. Before, a multi-slot windowed MTP server without `--kv-unified` (35B-A3B `-ncmoe 40 -np 2 -c 8192`, window 1024: 2 x 1536 = 3072 cells allocated, 1536 charged) under-charged the slab's aux reserve by one stream's window -- the direction the reserve header calls dangerous. Measured: 3072 cells reported on both the unified and the per-stream arm now. ========================================================================== PART 4 -- `-sm tensor`: the window across a split (r204, `TODO` ggml-org#124) ========================================================================== A Meta (tensor-split) device carries no backend reg, so the r181 answer was "not provided" and the window was declined on every split. `TODO` ggml-org#124 designed the fix on a one-GPU box (`archive/work/kv-residency/ A6-TENSOR-SPLIT-WINDOW.md`, changes C1-C5); it is implemented and measured here, on a 3x R9700 host, and the decline is gone. * `ggml_backend_meta_kv_region_buft / _is_kv_buft / _grow` (new, `ggml-backend.h`): the Meta buffer type over the per-child region buffer types (ALL children or nothing), the is-a-region predicate `--fit` needs (the CUDA predicate is an identity on the child's `alloc_buffer` and cannot answer for a Meta buffer type), and a grow that fans out to every child. A child that cannot be reached is a REFUSAL (-1), never the 0 the CUDA hook returns for "not a region buffer": for a Meta buffer that 0 was a silent success on unmapped VA, i.e. a batch that page-faults the GPU. * `llama_kv_cache` resolves capability, the buffer type, the spill ceiling and the link through the Meta side; a MIRRORED cache (dsv4 / HRM, `llama_model::kv_cache_split_mirrored()`) declines the window with its own message, because every device holds the whole cache there (`n_devices x W x cell_bytes`) and the pinned-spill plan is per logical cache. * `common/fit.cpp` decides the window inside the tensor-split branch: charged at its PHYSICAL `W x cell_bytes` (what all devices commit together) against `min_i(target_i / ratio_i)`, which makes the aggregate check imply every device's (the loader shards the KV along the KV-head axis by the same ratio it shards the weights), and the Meta entry's margin is now the SUM of the children's `--fit-target`s (it was child 0's, so `(n_devices - 1) x target` silently vanished from the budget). The corrected KV term applies ONLY where a window is asked for: a run without `LLAMA_KV_RESIDENT_CELLS` keeps this branch's old arithmetic exactly, so the split's pre-existing `n_devices x` KV over-count is untouched outside the window arm. Four defects the arms found, fixed in the same block: 1. the init-time window commit was rounded up to a whole map unit past the tensor's own extent, and on a split each child is its own VA reservation -- the last tensor's inflated window was refused (`the KV window (4.00 MiB) could not be committed in VRAM on device 1`). Clamped to the region's END, in whole units (clamping to the tensor's own extent was tried first and is wrong: it leaves a short mapping off the unit grid and the next slide refuses to flip). 2. `ensure_span` refused a request that covered several WHOLE mappings; one batch can advance the boundary by more than one unit, and a 1 MiB unit is floored to the driver's 2 MiB granularity, so the request covered two mappings and aborted the batch. Whole mappings now flip one at a time; a request that covers a mapping only in PART is still refused (that loses bytes on this driver). 3. the batched state save issued a 2-D D2H per device and `hipMemcpy2DAsync` fails (`invalid argument`) when the range begins in a spilled region's pinned host mapping (the tensor-split checkpoint save aborted: `cache_k_l64 (view)`, 1024 B x 4782 rows). The region-backed directions of `get/set_tensor_2d_async` now go through the region buffer's own copy, ordered behind the compute stream like the pool mirror (a blocking default-stream copy does not wait for it, and the state saved mid-batch is torn). 4. that fallback's "contiguous rows = one copy" shortcut ignored the caller's destination pitch, which for a split splice is the FULL row, wider than one device's slice: the state-pipe gate failed on every cycle of all four async arms until a tight block required BOTH pitches to equal the width. Verified (gfx1201, `ROCBLAS_USE_HIPBLASLT=0` for every fresh-process pair): text byte-identical on `win3 == ref3` (3 devices, 4B, `057ea27b1009`) and `win2 == ref2 == win2mtp == ref2mtp` (2 devices, 27B, a 5246-token prompt, `7a7430617465`; draft acceptance 0.46154 in both MTP arms), also at a 1 MiB map unit; the spill is real on EVERY device (32 mapping flips each at 4 MiB, 128 at 1 MiB); a `-c 1048576` 2-device split (64 GiB of f16 KV) runs only because of the window; the single-device and `-nkvo` arms are unchanged; `--fit` on the split reports a WINDOWED cache and keeps the pinned `-c 524288` (plus the pinned-RAM ceiling's widen and drop arms, and `LLAMA_KV_REGION=0` silent); coherence identical to the r203 build on four no-window arms (3-GPU 4B, 2-GPU and 1-GPU 27B, 2-GPU host-expert 35B-A3B); prefill-logit 0.000000 / 100.000 %; Protocol A four-axis R/P/C/K 1.91x / 2.43x / 2.58x / 2.74x (acceptance 0.5869 / 0.8391 / 0.9112 / 0.9920, the r90 shape); `gate-spec-draft-window.sh` 6/6; `gate-state-pipe.sh` 2-GPU `-sm tensor` PASS with and without the window (the windowed arm failed before (3) and (4)); `GGML_CUDA_VMM_REGION_SELFTEST=1` PASS with a new multi-mapping arm; per-block build 1/1; `validate-set.sh` strict 16/16. Gate: `scripts/gate-kv-window-split.sh`. Record: `benchmarks/2026-11-01-kv-window-tensor-split-124.md`.
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Nov 2, 2026
…W (Goal A) and an attendance POOL (Goal B), both opt-in Goals A and B of TODO ggml-org#118, promoted from the `wip/kv-residency` campaign. This block is the delivery's "the KV does not have to be O(-c) of VRAM" work: TWO opt-in placements of the same cache, and each one is byte-identical to a build without it when its knob is unset. * the WINDOW (`LLAMA_KV_RESIDENT_CELLS=<cells>|auto`): the newest W cells stay in VRAM, everything older spills to pinned system RAM in the SAME VA reservation -- a positional window, no kernel or op change; * the POOL (`LLAMA_KV_REGION_POOL=<cells>`): the authoritative copy of the WHOLE context in a pinned host mirror, and a compact device pool of the pages a decode step actually attends to, which the QSA sparse read resolves through a page table (`GGML_OP_KV_POOL`). They are mutually exclusive by construction (the pool declines while a window is active) and they answer the same question from opposite ends: the window keeps the *newest* cells hot, the pool keeps the *attended* cells hot. Both report `is_streaming()`, so a streamed cache takes the sparse QSA decode arm (B2, below). ========================================================================== PART 1 -- the WINDOW (Goal A, promoted in r178) ========================================================================== Goal A of TODO ggml-org#118, promoted from the `wip/kv-residency` campaign. WHAT IT DOES. The KV cache's VRAM cost becomes a WINDOW of the newest `W` cells instead of `-c` cells: one VA reservation (a CUDA/HIP VMM region) holds the whole cache, the window's cells are backed by VRAM and everything below them by pinned system RAM. `set_rows`, the in-place rope shift, `state_write/read`, the kq mask and the FA kernels keep addressing one contiguous range, so no kernel and no op changes. The window slides with the watermark in whole map units, so a remap happens once per few thousand tokens and the apparatus itself is free (a zero-spill arm measures the same as plain). WHY. (a) A context that OOMs today runs: 27B Q8_0 `-c 262144` (8704 MiB of KV) now runs on one 32 GiB card at 128 MiB VRAM + 8576 MiB pinned host for the KV. (b) With host-resident MoE experts, the VRAM the KV does not need *yet* goes to the expert-cache arena: measured at `-c 262144`, `-n 2000`, `-ncmoe` = the model's full layer count, 51 433-token prompt, W at or above the run's depth = **+2.2 to +2.9 GiB of arena** (+3.9 to +6.7 points of residency) for free -- 122B-A10B Q4_K_XL +3.8 % decode and +4.7 % prefill, 35B-A3B Q8_0 -0.9 % decode and +3 % prefill; a `W` 35 k cells BELOW the run depth costs 11-26 % (the spill is read every token). OPT-IN, AND ONLY WHEN ASKED FOR. `LLAMA_KV_RESIDENT_CELLS=<cells>` (a number) or `=auto` (`--fit` sizes it, and only spills a context the user pinned with `-c`); unset/0 = no window. With no window the KV takes the PLAIN device buffer, so a run without the knob is byte-identical to a build without this block -- including its OOM (verified). `LLAMA_KV_SPILL_RAM_PCT` (85 % of MemAvailable) caps the pinned spill and widens the window rather than being OOM-killed; `LLAMA_KV_REGION=0` disables the provider; `LLAMA_KV_REGION_QUARANTINE=0` and `LLAMA_KV_REGION_DEBUG/TRACE/CANARY/DUMP` are the diagnosis switches. PURITY (the window). A spilled KV is numerically transparent: prefill-logit **KLD -0.000000 / 100.000 %** on a spilling 27B arm and -0.000000 / 99.994 % on a spilling Flash-Next (two KV caches: the attention KV and the QSA indexer), text byte-identical on 27B (f16 and q8_0), 4B, 35B-A3B and Flash-Next, and the state paths, the context-checkpoint path and the MTP verify widths all green on arms that provably spill. Two driver hazards are held: a kind flip zeroes a neighbouring live host mapping unless the released physical is held across the create (`LLAMA_KV_REGION_QUARANTINE`, default on -- `=0` reproduces the corruption), and every tensor in a windowed region is placed on the driver's map granularity so a slide step coincides with a mapping. An idle-slot park is REFUSED on a region-backed cache (the server then saves the slot to the prompt cache and clears it, which is byte-identical to the parking gate's reference) because a park moves cells above the region's mapped watermark through the copy engine, which faults the GPU. FIT. `--fit` sizes and reports the window (`auto`), or honours and reports a numeric `W`: the resident/spill split, the VRAM saved, and the per-token read cost at the model's full context from the backend's calibrated link rate. The fit identifies the KV's bytes by the region buffer TYPE, and its measurement context is a `no_alloc` probe that declines a window -- so the probe takes the region buffer explicitly (`llama_kv_region_set_probe`); without that the fit cannot see the KV, reports an over-budget config and aborts instead of sizing the window (the r178 regression). GATES (1 GPU, gfx1201): default path byte-identical (`5ba44647188f`) and still OOMs; VMM selftest PASS and FAIL with the hold disabled; windowed arms 305 `e2cea6fa6670` = plain at W=1024/2048/4096 (spilling at 1024: 128 MiB host), `QUARANTINE=0` -> 325 `fb65430049e9` (the hazard); `--fit` sizes `auto` (96680 of 262144 cells, 3210 MiB resident) and reports a numeric W; `gate-ckpt-reuse.sh` / `gate-state-pipe.sh` / MTP verify widths on spilling arms; `test-backend-ops -o FLASH_ATTN_QSA` 26/26; `check-gpu-faults.sh` clean. Not in this block: the campaign's Goal B (a sparse attended set) and Goal C (the MTP drafter ring, `LLAMA_SPEC_DRAFT_WINDOW`) -- both remain campaign work -- and A1 (the superseded two-base FA read). Records: `wip/kv-residency/A2-MIXED-BACKING.md` (§3.7.9, §3.7.11), `HANDOVER.md`. MULTI-DEVICE `--fit` (r181; the window itself reaches a tensor split in r204, at the end of this message): the KV-region glue is now safe on a Meta (tensor-split) device, and `auto`'s decision reaches the cache as a decision. r178 made default `--fit` abort on ANY `-sm tensor` run with more than one device: the fit's KV probes and the cache's own region lookups call `ggml_backend_dev_backend_reg(dev)` and hand it to `ggml_backend_reg_get_proc_address`, and a Meta device has no backend reg (`device->reg == NULL`), so `GGML_ASSERT(reg)` fired at model load. Three paths asserted: the fit probe (any run), the runtime buft lookup (a numeric W), and the spill budget/link lookups (a numeric W below `-c`). r181 makes a null reg read as "not provided" and declines the window with one message naming the tensor split (fit and cache), keeping the KV fully resident -- which is the r181 state; r204, below, is what makes the backend answer there. Three wiring defects in the same code, all visible on ONE device: - `auto`'s "no window needed" decision (0) was indistinguishable from "nobody decided", so the cache warned "--fit did not run" immediately after the fit had decided exactly that. `llama_kv_region_set_resident_cells` now records that a decision was made (`llama_kv_region_resident_cells_decided`), and a decided 0 is silent. - every run without the knob logged "the windowed KV is unavailable for this cache (no spilled cells)". That message now only fires when a window was actually requested and declined for a real reason. - the pinned-RAM ceiling clamp could raise W past the VRAM budget and then be reported as "does not make this fit either". It is now only taken while the wider window still meets the VRAM target; otherwise the fit says the ceiling cannot be served at this `-c` and drops the window (which the fit then fits by reducing the context). That ordering is not cosmetic: an intermediate form of this fix accepted a 235 GiB pinned spill plan for a 4B at `-c 8388608`, and creating it OOM-killed the test box. GATES (the window, gfx1201): `--fit on` (default) at 2 and 3 devices, `-sm tensor`, with no knob / a numeric W / `auto`, fit on and off: no assert, tokens produced, exactly one message per requested window. `-sm layer` 2 devices and 1 GPU still take the window per device (numeric W), and `auto` still sizes the 27B Q8_0 `-c 262144` q8_0 arm identically (123265 of 262144 cells, 4092.8 MiB resident / 4611.2 MiB spilling). One device, no knob: no KV message at all. Purity unchanged: plain vs a SPILLING windowed arm prefill-logit KLD 0.000000 / 99.990 % (q8_0 KV), greedy text byte-identical on that arm; 35B-A3B (1 GPU and 2-GPU `-sm tensor`), dense 27B and the canonical 27B Q8_0 prefill-logit gate (0.000000 / 100.000 %) byte-identical to r180; MTP Protocol A unchanged (tensor acceptance 0.60816 = 1937/3185, plain == draft-mtp); no GPU faults. ========================================================================== PART 2 -- the ATTENDANCE POOL (Goal B, promoted in r190) ========================================================================== The attention KV lives twice: its AUTHORITATIVE copy in a pinned host MIRROR (cell-indexed, so the writers, state_write/state_read, the K-shift, defrag and seq_park all work on it unchanged -- the writer rule) and a compact DEVICE POOL of pages of one indexer block (compress_ratio cells) with a page table block -> slot and its inverse. A decode step resolves its top-k selection through the table and fills the pages it missed from the mirror; the QSA reader gathers K/V at the pool slots while the mask stays cell-indexed. LLAMA_KV_REGION_POOL=<cells>, unset/0 = off = byte-identical. Contents. - ggml/src/ggml-cuda/kv-pool.{cu,cuh}: GGML_OP_KV_POOL. MARK sets use[slot] = epoch for every page this launch reads AND every page the batch just wrote (the graph's k_idxs), and queues the written ones for re-fill; CLAIM takes a slot for each DISTINCT missing block (the table CAS is the dedupe) and never takes a slot MARK protected; MAP+FILL writes each selected cell's pool position into the reader's K/V id list and copies the claimed and dirty pages from the mirror, K and V sharing slots. The epoch is a device counter incremented once per launch: the graph bakes pointers, never counters, and nothing is allocated per launch. - ggml-cuda.cu: the pool's pinned host mirror buffer type -- a DEVICE buffer type whose allocation is pinned host memory (`ROCm_Host` reports is_host, which would send the KV's writers and the FA read to the CPU on a discrete device), and its proc-address entry. - llama-kv-cache: the eligibility, the per-layer pool tensors (pool_k/pool_v, tbl, inv, use, one shared counter block), the resolve wiring into the QSA id list, kv_pool_serves() (a batch too wide for the pool takes the cell-indexed path), the teardown accounting (LLAMA_KV_POOL_STATS takes a PATH: a line on stderr sits inside the generated text), and memory_breakdown() charging the mirror to the host bucket so `--fit` does not reserve it as VRAM. - llama-memory-hybrid-idx / llama-memory-hybrid / llama-memory: the second id list (the K/V gather follows the page table while the mask stays cell-indexed), the flag threading, and the pool's byte accounting for `--fit` (llama_get_kv_pool_bytes()). - models/qwen4exp.cpp: a pooled cache reports is_streaming() and the sparse arm uses the pool's id list; the MTP draft's own cache is never pooled (its attention is dense). - llama-context / the async state copies: the mirror's buffer type is accepted by the batched save and restore (its bytes are host memory, staged through the pinned state_stage). - common/fit.cpp + src/llama-ext.h: the pool's split in --fit's arithmetic and report (the mirror is pinned host RAM, the pool is VRAM), and no context-reduction interpolation while the pool is active -- the pool's VRAM is fixed, so reducing -c frees nothing and the interpolation would divide by a near-zero bytes-per-context delta. Invariants, each one caught by the greedy text. 1. MARK then CLAIM: a claim must never evict a page the same launch reads. Without MARK the round-robin victim could be a page another row still needs (the text diverged ~400 chars in, and a pool larger than the whole cache hid it completely). 2. Claim ATTEMPTS are not distinct blocks: a slot per id attempt wrapped the cursor within one 4-row batch, so two blocks shared a slot and a just-resolved block went unresident. The table CAS dedupes first, so only distinct blocks consume a slot and kv_pool_serves() bounds the distinct count. 3. No transient scratch in a captured graph: the fill list lived in a ggml_cuda_pool_alloc that is freed at the end of the op, and a captured graph bakes the pointer, so a replay wrote into whatever op had been handed that block ("values verify clean, text differs run to run"). It lives in the counters tensor. 4. The mirror is AUTHORITATIVE: the writers land in it and a declared page is re-filled from it before the attention reads it, so an eviction costs nothing and nothing has to be invalidated -- except by a path that rewrites cells in place without going through the writers (the K-shift, a state restore), which calls kv_pool_invalidate(). 5. Eligibility is narrow on purpose: one stream, non-MLA, K and V both present, !v_trans, a uniform compress_ratio and cell geometry, no window active, a device-offloaded cache, and only the trunk context of a qwen4exp model. Anything else declines with one message and the KV is unchanged. 6. The pool is floored at one decode band's worth of blocks (8 x ceil(width/page) pages) so a verify batch cannot exhaust the slot budget, and the mirror is bounded at creation by LLAMA_KV_SPILL_RAM_PCT (it is pinned, non-swappable RAM) -- over the ceiling the pool is declined loudly instead of being OOM-killed. Measured (Flash-Next GSQ-IQ3_XXS, 1 GPU, -ncmoe 48, q8_0, the PLE flags, arms interleaved in one batch, -n 512, MTP depth 4; t/s and tokens/step): depth (ctx) dense sparse pool (204 MiB) text (-n 64) 5 298 (16 384) 72.09 71.58 71.27 pool == sparse: 332 chars dd1981213373 102 899 (131 072) 59.10 54.70 54.65 (5.3k / 51 475 references; dense differs) 180 035 (196 608) 48.94 43.16 43.41 pool == sparse: 861 chars 263c7f2be4d9 The pool lands ON the sparse ceiling at every depth (+0.5 / +0.6 / +0.58 %), so its placement is free and what remains against a resident KV (-7 % / -11 %) is the sparse decode arm's own indexer cost (block 11), not the KV's storage. A 204 MiB pool replaces the resident attention KV's 1 632 MiB at 103k / 2 448 MiB at 180k, and the freed VRAM goes to the expert arena: 103k plain decode, -n 2000, 23 579.8 -> 25 018.6 MiB (+1 438.8 MiB, +18 slots/table), expert hit 96.26 -> 97.02 %, cold reads 42.0 -> 31.6 GiB. The pool's own cost is 0.10-0.11 ms/token (mark/claim/map+fill) with fills 0.03-0.05 ms/step at 92-99 % hits, which is why a better page policy (LRU / F-LRU / a heat prior) is measured dead at this shape. Full numbers and the three-depth table: ../wip/kv-residency/BA-POOL-DESIGN.md §7-§8. PURITY (the pool). Greedy text pool == the resident sparse arm at 5.3k (332 dd1981213373), 51 475 depth (854 43b30de151b9) and 180k (861 263c7f2be4d9), with the dense arm differing as documented (GREEDY-PURITY §45/§63); LLAMA_KV_POOL_VERIFY=1 0 mismatches on every arm; gate-prefill-logits --ab "LLAMA_KV_REGION_POOL=..." 0.000000 / 100.000 % on the pool arm (base PPL 2.9225, bit-identical to the campaign's own base); gate-park-idle-slots, gate-ckpt-reuse and gate-state-pipe PASS on a pooled cache (the mirror is authoritative, which is what makes them trivial); test-backend-ops -o FLASH_ATTN_QSA pass; no GPU faults; and `--fit` accepts the arms that only fit with the pool (-ncmoe 21/22 at -c 262144: refused without it, accepted with it; -fitp moves 3 264 MiB from the device row to Host). ========================================================================== PART 3 -- a STREAMED cache takes the sparse decode arm (B2) ========================================================================== A cache that is streaming at the depth it reads -- a window the used extent has passed, or a pool -- takes the sparse QSA decode arm; a resident cache keeps the dense one. llama_kv_cache::is_streaming() plus the qwen4exp arm policy, LLAMA_QSA_DENSE_DECODE_STREAM=0 to restore the old behaviour. Measured on a spilled KV (Flash-Next IQ3_XXS, -ncmoe 48, q8_0, 1 GPU, -n 400, 2 reps): +34.3 % at 102 899 depth (23.42 -> 31.43 t/s) and +47.3 % at 180 035 (16.51 -> 24.31); a resident cache byte-identical (853 77a40bf40be1). This is a decode-ARM choice, i.e. a different attention regime (like GREEDY-PURITY §45/§63), so a streamed arm's text differs from the old dense-arm text by construction and a resident arm is the oracle. ========================================================================== DEFAULT OFF, for both placements ========================================================================== Neither knob is a speed feature on a config whose KV fits: the window costs the depth below W (11-26 %) and the pool costs the sparse-vs-dense gap (-7 % at 103k, -11 % at 180k). They are FITTABILITY features -- they turn an OOM into a run and they hand the freed VRAM to the expert arena -- so both are opt-in and both stay byte-identical, including the OOM, with their knobs unset. Do not "fix" the defaults. Goal C (the MTP drafter ring, TODO ggml-org#121) joins the same block -- it is the same claim applied to the draft context, and its default follows the delivery's own rule because it measures positive. `LLAMA_SPEC_DRAFT_WINDOW` gives the MTP draft context a sliding window instead of a `-c`-sized KV: unset or `auto` is the adaptive policy (a quarter of the context, clamped to [32768, 65536] cells), `0` is off (byte-identical to a build without it) and `N` is a cell count. The drafter reads its last few thousand tokens, so a window at or above that is free and one far below it costs 7-9 % of decode; the clamps keep it above that band, and the target verifies every token it proposes, so a truncated draft can only be slower. The ring is the shipped reclaim in `llama_kv_cache::find_slot` (`n_swa`), not a new allocator, and the derived kq mask stays valid -- its predicate compares each cell's POSITION, so a recycled cell reports its new one. The VRAM win needed one more piece: an embedded MTP head has no GGUF of its own, so the slab's draft reserve was the flat 3584 MiB and the freed VRAM never reached the expert arena. For an embedded MTP head with an active window the reserve is now derived from the model's own metadata with the weights zeroed (they are the target's) and the KV sized by the window: aux 3.50 -> 0.76 GiB, i.e. the arena gains ~2.8 GiB. A separate MTP draft GGUF (qwen4exp/Flash-Next) and an un-windowed run keep the flat constant exactly as before, and a declined arena preflight now re-evaluates when the smaller real value arrives instead of latching on the load-time estimate. Measured (1 GPU; one R9700; `-n 2000`/`-n 3000`; static depth 3; interleaved): * 35B-A3B Q8_0 `-ncmoe 48 -c 262144` q8_0 KV, 51 433-token prompt: arena 20 910 -> 23 715 MiB (residency 64.1 -> 72.7 %), decode 111.2 -> 113.7 t/s at `-n 3000` (+2.2 %; +2.8-4.9 % at `-n 2000`), prefill +3.4 %, drafts byte-for-byte the same count (1995/3011) -- the window truncates nothing the drafter used. * dense 27B UD-Q4_K_XL `-c 102400`, MTP Protocol A `-n 3000`, reasoning-pinned: layer 71.9 -> 72.1, tensor 72.6 -> 72.5 (neutral), acceptance 2083/2747 identical in all four arms. * target greedy text byte-identical across off/auto/4096, and plain == draft-mtp == draft-mtp(W=512) at `-c 16384` with a 5256-token prompt and 3000 generated tokens (10 158 chars, sha 99b267e8dc3e), i.e. no wrong answer under constant cell reuse. * gates on a windowed draft: `gate-park-idle-slots.sh` (35B, -ncmoe 48, `-c 65536`: 3 park moves, park == lazyoff), `gate-ckpt-reuse.sh` (4B, `-c 131072`: draft cache 33280 of 131072), `gate-state-pipe.sh` (35B, `-c 65536`: all five arms) -- all PASS with `MTP draft KV window = 32768 cells` in their logs. r194 corner fixes (found by a configuration battery against Flash-Next after r193): * LLAMA_KV_REGION_POOL is capped at the cache's own cell count. =1000000 on a 262144-cell context used to take a 12451 MiB device pool of 250000 pages where only 65536 blocks exist (never claimed, arena -4 GiB); it is now 3264 MiB / 65536 pages, and a small context clamps the same way. * the draft KV window sizes only the reserve of the cache it actually windows. A separate -md MTP head (Flash-Next) keeps its full -c cache, but the reserve was derived with the window: 921 MiB where the honest number is 1566 (kv 217 vs 862) at -c 262144, the under-charge direction. Embedded heads (qwen3.5/3.6/3.8) are unchanged (776 MiB on the 35B). The VRAM cliff at -c 262144 is documented (not code): the 768 MiB default headroom is one hipBLASLt workspace short for the first prefill, GGML_CUDA_SLAB_HEADROOM_MIB=1536 is 3/3 requests clean. Amendment (TODO ggml-org#129's sibling): `-nkvo` declines the window, and the streamed arm keys on the placement. The window is a DEVICE region plus a pinned host tail, but its guard did not test `offload`: with `-nkvo` the per-layer buffer is chosen inside `if (offload)` and stays plain pageable host memory, while the plan block still logged "WINDOWED KV ENABLED", reserved pinned-RAM spill budget and left `kv_resident_cells` set. `is_streaming()` then keyed the streamed (sparse) decode arm on that plan -- qwen4exp consumes it -- for a KV with no region at all. Measured: `-nkvo LLAMA_KV_RESIDENT_CELLS=64` built a plain `CPU KV buffer` of the whole context while announcing a 64-cell VRAM window. The window now declines once, with the reason (the pool already declines on `!offload`), so `-nkvo` means "no streamed placement"; `is_streaming()` tests `kv_region`, the placement actually taken, which also covers a device cache whose region buft the backend refused. Text is unchanged in every arm (the decline is a no-op: `-nkvo` + window already read as `-nkvo` alone). Amendment (issue ggml-org#264): the draft window is PER SEQUENCE, and under `--kv-unified` its cell count is `(win + one batch) x n_seq_max`. A unified cache holds every sequence in ONE stream, so the r193 sizing (`win + n_ubatch` cells) was shared by all of them: once the first sequence had filled its window the tail was all the room left, the tail is where that sequence's own ring writes, and a second sequence's first batch had no contiguous run to be placed in -- `find_slot` refused, and every request on that slot answered `decode() failed: failed to process speculative batch` (HTTP 500) while the drafter ran. Reported on `--kv-unified -np 2` with a 65 536-cell window at `-c 262144` after slot 0 held ~100k tokens; reproduced here with a forced 8192-cell window. A per-stream cache (no `--kv-unified`) already sized each stream separately and is unchanged. `llama_spec_draft_kv_cells()` is now the one geometry function -- the cache (`create_memory`), the slab's draft reserve estimate and the "is a window active" test in `common` all call it, so the reserve can never under-charge an allocation. It grants `win` per sequence plus one placeable batch (`(win + n_ubatch) * n_seq_max`, capped at the context), and DECLINES the window when that does not fit the context per sequence rather than lowering it to `per_seq - n_ubatch`: a window that small saves one batch of cells per sequence and masks the drafter's newest cells to do it. `llama_spec_draft_window_cells()` stays the policy (it is the per-sequence window). n_seq_max == 1 -- every `llama-cli`/`llama-bench` run -- measures exactly what it did (cells 1536 for a 1024-cell window at `-c 8192`), so no single-sequence arm changes at all. Measured (dense 27B, 1 GPU, `-np 2 --kv-unified`): the issue's scenario now answers both slots, and `scripts/gate-spec-draft-window.sh` (new) drives 6 requests over 2 slots with a 1024-cell window -- both rings wrapping, prompts full re-prefilled by swapping them between slots -- with output byte-identical to `LLAMA_SPEC_DRAFT_WINDOW=0` on every step and draft acceptance identical (17/36, 23/23). Greedy text `plain == draft-mtp == draft-mtp(W=1024) == draft-mtp(W=0)` (876 chars, sha 8c8fd395402f) at `-c 16384`. And the reserve now charges a per-STREAM (no `--kv-unified`) draft cache for every stream it allocates: `n_seq_max x` the per-stream cell count. Before, a multi-slot windowed MTP server without `--kv-unified` (35B-A3B `-ncmoe 40 -np 2 -c 8192`, window 1024: 2 x 1536 = 3072 cells allocated, 1536 charged) under-charged the slab's aux reserve by one stream's window -- the direction the reserve header calls dangerous. Measured: 3072 cells reported on both the unified and the per-stream arm now. ========================================================================== PART 4 -- `-sm tensor`: the window across a split (r204, `TODO` ggml-org#124) ========================================================================== A Meta (tensor-split) device carries no backend reg, so the r181 answer was "not provided" and the window was declined on every split. `TODO` ggml-org#124 designed the fix on a one-GPU box (`archive/work/kv-residency/ A6-TENSOR-SPLIT-WINDOW.md`, changes C1-C5); it is implemented and measured here, on a 3x R9700 host, and the decline is gone. * `ggml_backend_meta_kv_region_buft / _is_kv_buft / _grow` (new, `ggml-backend.h`): the Meta buffer type over the per-child region buffer types (ALL children or nothing), the is-a-region predicate `--fit` needs (the CUDA predicate is an identity on the child's `alloc_buffer` and cannot answer for a Meta buffer type), and a grow that fans out to every child. A child that cannot be reached is a REFUSAL (-1), never the 0 the CUDA hook returns for "not a region buffer": for a Meta buffer that 0 was a silent success on unmapped VA, i.e. a batch that page-faults the GPU. * `llama_kv_cache` resolves capability, the buffer type, the spill ceiling and the link through the Meta side; a MIRRORED cache (dsv4 / HRM, `llama_model::kv_cache_split_mirrored()`) declines the window with its own message, because every device holds the whole cache there (`n_devices x W x cell_bytes`) and the pinned-spill plan is per logical cache. * `common/fit.cpp` decides the window inside the tensor-split branch: charged at its PHYSICAL `W x cell_bytes` (what all devices commit together) against `min_i(target_i / ratio_i)`, which makes the aggregate check imply every device's (the loader shards the KV along the KV-head axis by the same ratio it shards the weights), and the Meta entry's margin is now the SUM of the children's `--fit-target`s (it was child 0's, so `(n_devices - 1) x target` silently vanished from the budget). The corrected KV term applies ONLY where a window is asked for: a run without `LLAMA_KV_RESIDENT_CELLS` keeps this branch's old arithmetic exactly, so the split's pre-existing `n_devices x` KV over-count is untouched outside the window arm. Four defects the arms found, fixed in the same block: 1. the init-time window commit was rounded up to a whole map unit past the tensor's own extent, and on a split each child is its own VA reservation -- the last tensor's inflated window was refused (`the KV window (4.00 MiB) could not be committed in VRAM on device 1`). Clamped to the region's END, in whole units (clamping to the tensor's own extent was tried first and is wrong: it leaves a short mapping off the unit grid and the next slide refuses to flip). 2. `ensure_span` refused a request that covered several WHOLE mappings; one batch can advance the boundary by more than one unit, and a 1 MiB unit is floored to the driver's 2 MiB granularity, so the request covered two mappings and aborted the batch. Whole mappings now flip one at a time; a request that covers a mapping only in PART is still refused (that loses bytes on this driver). 3. the batched state save issued a 2-D D2H per device and `hipMemcpy2DAsync` fails (`invalid argument`) when the range begins in a spilled region's pinned host mapping (the tensor-split checkpoint save aborted: `cache_k_l64 (view)`, 1024 B x 4782 rows). The region-backed directions of `get/set_tensor_2d_async` now go through the region buffer's own copy, ordered behind the compute stream like the pool mirror (a blocking default-stream copy does not wait for it, and the state saved mid-batch is torn). 4. that fallback's "contiguous rows = one copy" shortcut ignored the caller's destination pitch, which for a split splice is the FULL row, wider than one device's slice: the state-pipe gate failed on every cycle of all four async arms until a tight block required BOTH pitches to equal the width. Verified (gfx1201, `ROCBLAS_USE_HIPBLASLT=0` for every fresh-process pair): text byte-identical on `win3 == ref3` (3 devices, 4B, `057ea27b1009`) and `win2 == ref2 == win2mtp == ref2mtp` (2 devices, 27B, a 5246-token prompt, `7a7430617465`; draft acceptance 0.46154 in both MTP arms), also at a 1 MiB map unit; the spill is real on EVERY device (32 mapping flips each at 4 MiB, 128 at 1 MiB); a `-c 1048576` 2-device split (64 GiB of f16 KV) runs only because of the window; the single-device and `-nkvo` arms are unchanged; `--fit` on the split reports a WINDOWED cache and keeps the pinned `-c 524288` (plus the pinned-RAM ceiling's widen and drop arms, and `LLAMA_KV_REGION=0` silent); coherence identical to the r203 build on four no-window arms (3-GPU 4B, 2-GPU and 1-GPU 27B, 2-GPU host-expert 35B-A3B); prefill-logit 0.000000 / 100.000 %; Protocol A four-axis R/P/C/K 1.91x / 2.43x / 2.58x / 2.74x (acceptance 0.5869 / 0.8391 / 0.9112 / 0.9920, the r90 shape); `gate-spec-draft-window.sh` 6/6; `gate-state-pipe.sh` 2-GPU `-sm tensor` PASS with and without the window (the windowed arm failed before (3) and (4)); `GGML_CUDA_VMM_REGION_SELFTEST=1` PASS with a new multi-mapping arm; per-block build 1/1; `validate-set.sh` strict 16/16. Gate: `scripts/gate-kv-window-split.sh`. Record: `benchmarks/2026-11-01-kv-window-tensor-split-124.md`.
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Nov 2, 2026
…W (Goal A) and an attendance POOL (Goal B), both opt-in Goals A and B of TODO ggml-org#118, promoted from the `wip/kv-residency` campaign. This block is the delivery's "the KV does not have to be O(-c) of VRAM" work: TWO opt-in placements of the same cache, and each one is byte-identical to a build without it when its knob is unset. * the WINDOW (`LLAMA_KV_RESIDENT_CELLS=<cells>|auto`): the newest W cells stay in VRAM, everything older spills to pinned system RAM in the SAME VA reservation -- a positional window, no kernel or op change; * the POOL (`LLAMA_KV_REGION_POOL=<cells>`): the authoritative copy of the WHOLE context in a pinned host mirror, and a compact device pool of the pages a decode step actually attends to, which the QSA sparse read resolves through a page table (`GGML_OP_KV_POOL`). They are mutually exclusive by construction (the pool declines while a window is active) and they answer the same question from opposite ends: the window keeps the *newest* cells hot, the pool keeps the *attended* cells hot. Both report `is_streaming()`, so a streamed cache takes the sparse QSA decode arm (B2, below). ========================================================================== PART 1 -- the WINDOW (Goal A, promoted in r178) ========================================================================== Goal A of TODO ggml-org#118, promoted from the `wip/kv-residency` campaign. WHAT IT DOES. The KV cache's VRAM cost becomes a WINDOW of the newest `W` cells instead of `-c` cells: one VA reservation (a CUDA/HIP VMM region) holds the whole cache, the window's cells are backed by VRAM and everything below them by pinned system RAM. `set_rows`, the in-place rope shift, `state_write/read`, the kq mask and the FA kernels keep addressing one contiguous range, so no kernel and no op changes. The window slides with the watermark in whole map units, so a remap happens once per few thousand tokens and the apparatus itself is free (a zero-spill arm measures the same as plain). WHY. (a) A context that OOMs today runs: 27B Q8_0 `-c 262144` (8704 MiB of KV) now runs on one 32 GiB card at 128 MiB VRAM + 8576 MiB pinned host for the KV. (b) With host-resident MoE experts, the VRAM the KV does not need *yet* goes to the expert-cache arena: measured at `-c 262144`, `-n 2000`, `-ncmoe` = the model's full layer count, 51 433-token prompt, W at or above the run's depth = **+2.2 to +2.9 GiB of arena** (+3.9 to +6.7 points of residency) for free -- 122B-A10B Q4_K_XL +3.8 % decode and +4.7 % prefill, 35B-A3B Q8_0 -0.9 % decode and +3 % prefill; a `W` 35 k cells BELOW the run depth costs 11-26 % (the spill is read every token). OPT-IN, AND ONLY WHEN ASKED FOR. `LLAMA_KV_RESIDENT_CELLS=<cells>` (a number) or `=auto` (`--fit` sizes it, and only spills a context the user pinned with `-c`); unset/0 = no window. With no window the KV takes the PLAIN device buffer, so a run without the knob is byte-identical to a build without this block -- including its OOM (verified). `LLAMA_KV_SPILL_RAM_PCT` (85 % of MemAvailable) caps the pinned spill and widens the window rather than being OOM-killed; `LLAMA_KV_REGION=0` disables the provider; `LLAMA_KV_REGION_QUARANTINE=0` and `LLAMA_KV_REGION_DEBUG/TRACE/CANARY/DUMP` are the diagnosis switches. PURITY (the window). A spilled KV is numerically transparent: prefill-logit **KLD -0.000000 / 100.000 %** on a spilling 27B arm and -0.000000 / 99.994 % on a spilling Flash-Next (two KV caches: the attention KV and the QSA indexer), text byte-identical on 27B (f16 and q8_0), 4B, 35B-A3B and Flash-Next, and the state paths, the context-checkpoint path and the MTP verify widths all green on arms that provably spill. Two driver hazards are held: a kind flip zeroes a neighbouring live host mapping unless the released physical is held across the create (`LLAMA_KV_REGION_QUARANTINE`, default on -- `=0` reproduces the corruption), and every tensor in a windowed region is placed on the driver's map granularity so a slide step coincides with a mapping. An idle-slot park is REFUSED on a region-backed cache (the server then saves the slot to the prompt cache and clears it, which is byte-identical to the parking gate's reference) because a park moves cells above the region's mapped watermark through the copy engine, which faults the GPU. FIT. `--fit` sizes and reports the window (`auto`), or honours and reports a numeric `W`: the resident/spill split, the VRAM saved, and the per-token read cost at the model's full context from the backend's calibrated link rate. The fit identifies the KV's bytes by the region buffer TYPE, and its measurement context is a `no_alloc` probe that declines a window -- so the probe takes the region buffer explicitly (`llama_kv_region_set_probe`); without that the fit cannot see the KV, reports an over-budget config and aborts instead of sizing the window (the r178 regression). GATES (1 GPU, gfx1201): default path byte-identical (`5ba44647188f`) and still OOMs; VMM selftest PASS and FAIL with the hold disabled; windowed arms 305 `e2cea6fa6670` = plain at W=1024/2048/4096 (spilling at 1024: 128 MiB host), `QUARANTINE=0` -> 325 `fb65430049e9` (the hazard); `--fit` sizes `auto` (96680 of 262144 cells, 3210 MiB resident) and reports a numeric W; `gate-ckpt-reuse.sh` / `gate-state-pipe.sh` / MTP verify widths on spilling arms; `test-backend-ops -o FLASH_ATTN_QSA` 26/26; `check-gpu-faults.sh` clean. Not in this block: the campaign's Goal B (a sparse attended set) and Goal C (the MTP drafter ring, `LLAMA_SPEC_DRAFT_WINDOW`) -- both remain campaign work -- and A1 (the superseded two-base FA read). Records: `wip/kv-residency/A2-MIXED-BACKING.md` (§3.7.9, §3.7.11), `HANDOVER.md`. MULTI-DEVICE `--fit` (r181; the window itself reaches a tensor split in r204, at the end of this message): the KV-region glue is now safe on a Meta (tensor-split) device, and `auto`'s decision reaches the cache as a decision. r178 made default `--fit` abort on ANY `-sm tensor` run with more than one device: the fit's KV probes and the cache's own region lookups call `ggml_backend_dev_backend_reg(dev)` and hand it to `ggml_backend_reg_get_proc_address`, and a Meta device has no backend reg (`device->reg == NULL`), so `GGML_ASSERT(reg)` fired at model load. Three paths asserted: the fit probe (any run), the runtime buft lookup (a numeric W), and the spill budget/link lookups (a numeric W below `-c`). r181 makes a null reg read as "not provided" and declines the window with one message naming the tensor split (fit and cache), keeping the KV fully resident -- which is the r181 state; r204, below, is what makes the backend answer there. Three wiring defects in the same code, all visible on ONE device: - `auto`'s "no window needed" decision (0) was indistinguishable from "nobody decided", so the cache warned "--fit did not run" immediately after the fit had decided exactly that. `llama_kv_region_set_resident_cells` now records that a decision was made (`llama_kv_region_resident_cells_decided`), and a decided 0 is silent. - every run without the knob logged "the windowed KV is unavailable for this cache (no spilled cells)". That message now only fires when a window was actually requested and declined for a real reason. - the pinned-RAM ceiling clamp could raise W past the VRAM budget and then be reported as "does not make this fit either". It is now only taken while the wider window still meets the VRAM target; otherwise the fit says the ceiling cannot be served at this `-c` and drops the window (which the fit then fits by reducing the context). That ordering is not cosmetic: an intermediate form of this fix accepted a 235 GiB pinned spill plan for a 4B at `-c 8388608`, and creating it OOM-killed the test box. GATES (the window, gfx1201): `--fit on` (default) at 2 and 3 devices, `-sm tensor`, with no knob / a numeric W / `auto`, fit on and off: no assert, tokens produced, exactly one message per requested window. `-sm layer` 2 devices and 1 GPU still take the window per device (numeric W), and `auto` still sizes the 27B Q8_0 `-c 262144` q8_0 arm identically (123265 of 262144 cells, 4092.8 MiB resident / 4611.2 MiB spilling). One device, no knob: no KV message at all. Purity unchanged: plain vs a SPILLING windowed arm prefill-logit KLD 0.000000 / 99.990 % (q8_0 KV), greedy text byte-identical on that arm; 35B-A3B (1 GPU and 2-GPU `-sm tensor`), dense 27B and the canonical 27B Q8_0 prefill-logit gate (0.000000 / 100.000 %) byte-identical to r180; MTP Protocol A unchanged (tensor acceptance 0.60816 = 1937/3185, plain == draft-mtp); no GPU faults. ========================================================================== PART 2 -- the ATTENDANCE POOL (Goal B, promoted in r190) ========================================================================== The attention KV lives twice: its AUTHORITATIVE copy in a pinned host MIRROR (cell-indexed, so the writers, state_write/state_read, the K-shift, defrag and seq_park all work on it unchanged -- the writer rule) and a compact DEVICE POOL of pages of one indexer block (compress_ratio cells) with a page table block -> slot and its inverse. A decode step resolves its top-k selection through the table and fills the pages it missed from the mirror; the QSA reader gathers K/V at the pool slots while the mask stays cell-indexed. LLAMA_KV_REGION_POOL=<cells>, unset/0 = off = byte-identical. Contents. - ggml/src/ggml-cuda/kv-pool.{cu,cuh}: GGML_OP_KV_POOL. MARK sets use[slot] = epoch for every page this launch reads AND every page the batch just wrote (the graph's k_idxs), and queues the written ones for re-fill; CLAIM takes a slot for each DISTINCT missing block (the table CAS is the dedupe) and never takes a slot MARK protected; MAP+FILL writes each selected cell's pool position into the reader's K/V id list and copies the claimed and dirty pages from the mirror, K and V sharing slots. The epoch is a device counter incremented once per launch: the graph bakes pointers, never counters, and nothing is allocated per launch. - ggml-cuda.cu: the pool's pinned host mirror buffer type -- a DEVICE buffer type whose allocation is pinned host memory (`ROCm_Host` reports is_host, which would send the KV's writers and the FA read to the CPU on a discrete device), and its proc-address entry. - llama-kv-cache: the eligibility, the per-layer pool tensors (pool_k/pool_v, tbl, inv, use, one shared counter block), the resolve wiring into the QSA id list, kv_pool_serves() (a batch too wide for the pool takes the cell-indexed path), the teardown accounting (LLAMA_KV_POOL_STATS takes a PATH: a line on stderr sits inside the generated text), and memory_breakdown() charging the mirror to the host bucket so `--fit` does not reserve it as VRAM. - llama-memory-hybrid-idx / llama-memory-hybrid / llama-memory: the second id list (the K/V gather follows the page table while the mask stays cell-indexed), the flag threading, and the pool's byte accounting for `--fit` (llama_get_kv_pool_bytes()). - models/qwen4exp.cpp: a pooled cache reports is_streaming() and the sparse arm uses the pool's id list; the MTP draft's own cache is never pooled (its attention is dense). - llama-context / the async state copies: the mirror's buffer type is accepted by the batched save and restore (its bytes are host memory, staged through the pinned state_stage). - common/fit.cpp + src/llama-ext.h: the pool's split in --fit's arithmetic and report (the mirror is pinned host RAM, the pool is VRAM), and no context-reduction interpolation while the pool is active -- the pool's VRAM is fixed, so reducing -c frees nothing and the interpolation would divide by a near-zero bytes-per-context delta. Invariants, each one caught by the greedy text. 1. MARK then CLAIM: a claim must never evict a page the same launch reads. Without MARK the round-robin victim could be a page another row still needs (the text diverged ~400 chars in, and a pool larger than the whole cache hid it completely). 2. Claim ATTEMPTS are not distinct blocks: a slot per id attempt wrapped the cursor within one 4-row batch, so two blocks shared a slot and a just-resolved block went unresident. The table CAS dedupes first, so only distinct blocks consume a slot and kv_pool_serves() bounds the distinct count. 3. No transient scratch in a captured graph: the fill list lived in a ggml_cuda_pool_alloc that is freed at the end of the op, and a captured graph bakes the pointer, so a replay wrote into whatever op had been handed that block ("values verify clean, text differs run to run"). It lives in the counters tensor. 4. The mirror is AUTHORITATIVE: the writers land in it and a declared page is re-filled from it before the attention reads it, so an eviction costs nothing and nothing has to be invalidated -- except by a path that rewrites cells in place without going through the writers (the K-shift, a state restore), which calls kv_pool_invalidate(). 5. Eligibility is narrow on purpose: one stream, non-MLA, K and V both present, !v_trans, a uniform compress_ratio and cell geometry, no window active, a device-offloaded cache, and only the trunk context of a qwen4exp model. Anything else declines with one message and the KV is unchanged. 6. The pool is floored at one decode band's worth of blocks (8 x ceil(width/page) pages) so a verify batch cannot exhaust the slot budget, and the mirror is bounded at creation by LLAMA_KV_SPILL_RAM_PCT (it is pinned, non-swappable RAM) -- over the ceiling the pool is declined loudly instead of being OOM-killed. Measured (Flash-Next GSQ-IQ3_XXS, 1 GPU, -ncmoe 48, q8_0, the PLE flags, arms interleaved in one batch, -n 512, MTP depth 4; t/s and tokens/step): depth (ctx) dense sparse pool (204 MiB) text (-n 64) 5 298 (16 384) 72.09 71.58 71.27 pool == sparse: 332 chars dd1981213373 102 899 (131 072) 59.10 54.70 54.65 (5.3k / 51 475 references; dense differs) 180 035 (196 608) 48.94 43.16 43.41 pool == sparse: 861 chars 263c7f2be4d9 The pool lands ON the sparse ceiling at every depth (+0.5 / +0.6 / +0.58 %), so its placement is free and what remains against a resident KV (-7 % / -11 %) is the sparse decode arm's own indexer cost (block 11), not the KV's storage. A 204 MiB pool replaces the resident attention KV's 1 632 MiB at 103k / 2 448 MiB at 180k, and the freed VRAM goes to the expert arena: 103k plain decode, -n 2000, 23 579.8 -> 25 018.6 MiB (+1 438.8 MiB, +18 slots/table), expert hit 96.26 -> 97.02 %, cold reads 42.0 -> 31.6 GiB. The pool's own cost is 0.10-0.11 ms/token (mark/claim/map+fill) with fills 0.03-0.05 ms/step at 92-99 % hits, which is why a better page policy (LRU / F-LRU / a heat prior) is measured dead at this shape. Full numbers and the three-depth table: ../wip/kv-residency/BA-POOL-DESIGN.md §7-§8. PURITY (the pool). Greedy text pool == the resident sparse arm at 5.3k (332 dd1981213373), 51 475 depth (854 43b30de151b9) and 180k (861 263c7f2be4d9), with the dense arm differing as documented (GREEDY-PURITY §45/§63); LLAMA_KV_POOL_VERIFY=1 0 mismatches on every arm; gate-prefill-logits --ab "LLAMA_KV_REGION_POOL=..." 0.000000 / 100.000 % on the pool arm (base PPL 2.9225, bit-identical to the campaign's own base); gate-park-idle-slots, gate-ckpt-reuse and gate-state-pipe PASS on a pooled cache (the mirror is authoritative, which is what makes them trivial); test-backend-ops -o FLASH_ATTN_QSA pass; no GPU faults; and `--fit` accepts the arms that only fit with the pool (-ncmoe 21/22 at -c 262144: refused without it, accepted with it; -fitp moves 3 264 MiB from the device row to Host). ========================================================================== PART 3 -- a STREAMED cache takes the sparse decode arm (B2) ========================================================================== A cache that is streaming at the depth it reads -- a window the used extent has passed, or a pool -- takes the sparse QSA decode arm; a resident cache keeps the dense one. llama_kv_cache::is_streaming() plus the qwen4exp arm policy, LLAMA_QSA_DENSE_DECODE_STREAM=0 to restore the old behaviour. Measured on a spilled KV (Flash-Next IQ3_XXS, -ncmoe 48, q8_0, 1 GPU, -n 400, 2 reps): +34.3 % at 102 899 depth (23.42 -> 31.43 t/s) and +47.3 % at 180 035 (16.51 -> 24.31); a resident cache byte-identical (853 77a40bf40be1). This is a decode-ARM choice, i.e. a different attention regime (like GREEDY-PURITY §45/§63), so a streamed arm's text differs from the old dense-arm text by construction and a resident arm is the oracle. ========================================================================== DEFAULT OFF, for both placements ========================================================================== Neither knob is a speed feature on a config whose KV fits: the window costs the depth below W (11-26 %) and the pool costs the sparse-vs-dense gap (-7 % at 103k, -11 % at 180k). They are FITTABILITY features -- they turn an OOM into a run and they hand the freed VRAM to the expert arena -- so both are opt-in and both stay byte-identical, including the OOM, with their knobs unset. Do not "fix" the defaults. Goal C (the MTP drafter ring, TODO ggml-org#121) joins the same block -- it is the same claim applied to the draft context, and its default follows the delivery's own rule because it measures positive. `LLAMA_SPEC_DRAFT_WINDOW` gives the MTP draft context a sliding window instead of a `-c`-sized KV: unset or `auto` is the adaptive policy (a quarter of the context, clamped to [32768, 65536] cells), `0` is off (byte-identical to a build without it) and `N` is a cell count. The drafter reads its last few thousand tokens, so a window at or above that is free and one far below it costs 7-9 % of decode; the clamps keep it above that band, and the target verifies every token it proposes, so a truncated draft can only be slower. The ring is the shipped reclaim in `llama_kv_cache::find_slot` (`n_swa`), not a new allocator, and the derived kq mask stays valid -- its predicate compares each cell's POSITION, so a recycled cell reports its new one. The VRAM win needed one more piece: an embedded MTP head has no GGUF of its own, so the slab's draft reserve was the flat 3584 MiB and the freed VRAM never reached the expert arena. For an embedded MTP head with an active window the reserve is now derived from the model's own metadata with the weights zeroed (they are the target's) and the KV sized by the window: aux 3.50 -> 0.76 GiB, i.e. the arena gains ~2.8 GiB. A separate MTP draft GGUF (qwen4exp/Flash-Next) and an un-windowed run keep the flat constant exactly as before, and a declined arena preflight now re-evaluates when the smaller real value arrives instead of latching on the load-time estimate. Measured (1 GPU; one R9700; `-n 2000`/`-n 3000`; static depth 3; interleaved): * 35B-A3B Q8_0 `-ncmoe 48 -c 262144` q8_0 KV, 51 433-token prompt: arena 20 910 -> 23 715 MiB (residency 64.1 -> 72.7 %), decode 111.2 -> 113.7 t/s at `-n 3000` (+2.2 %; +2.8-4.9 % at `-n 2000`), prefill +3.4 %, drafts byte-for-byte the same count (1995/3011) -- the window truncates nothing the drafter used. * dense 27B UD-Q4_K_XL `-c 102400`, MTP Protocol A `-n 3000`, reasoning-pinned: layer 71.9 -> 72.1, tensor 72.6 -> 72.5 (neutral), acceptance 2083/2747 identical in all four arms. * target greedy text byte-identical across off/auto/4096, and plain == draft-mtp == draft-mtp(W=512) at `-c 16384` with a 5256-token prompt and 3000 generated tokens (10 158 chars, sha 99b267e8dc3e), i.e. no wrong answer under constant cell reuse. * gates on a windowed draft: `gate-park-idle-slots.sh` (35B, -ncmoe 48, `-c 65536`: 3 park moves, park == lazyoff), `gate-ckpt-reuse.sh` (4B, `-c 131072`: draft cache 33280 of 131072), `gate-state-pipe.sh` (35B, `-c 65536`: all five arms) -- all PASS with `MTP draft KV window = 32768 cells` in their logs. r194 corner fixes (found by a configuration battery against Flash-Next after r193): * LLAMA_KV_REGION_POOL is capped at the cache's own cell count. =1000000 on a 262144-cell context used to take a 12451 MiB device pool of 250000 pages where only 65536 blocks exist (never claimed, arena -4 GiB); it is now 3264 MiB / 65536 pages, and a small context clamps the same way. * the draft KV window sizes only the reserve of the cache it actually windows. A separate -md MTP head (Flash-Next) keeps its full -c cache, but the reserve was derived with the window: 921 MiB where the honest number is 1566 (kv 217 vs 862) at -c 262144, the under-charge direction. Embedded heads (qwen3.5/3.6/3.8) are unchanged (776 MiB on the 35B). The VRAM cliff at -c 262144 is documented (not code): the 768 MiB default headroom is one hipBLASLt workspace short for the first prefill, GGML_CUDA_SLAB_HEADROOM_MIB=1536 is 3/3 requests clean. Amendment (TODO ggml-org#129's sibling): `-nkvo` declines the window, and the streamed arm keys on the placement. The window is a DEVICE region plus a pinned host tail, but its guard did not test `offload`: with `-nkvo` the per-layer buffer is chosen inside `if (offload)` and stays plain pageable host memory, while the plan block still logged "WINDOWED KV ENABLED", reserved pinned-RAM spill budget and left `kv_resident_cells` set. `is_streaming()` then keyed the streamed (sparse) decode arm on that plan -- qwen4exp consumes it -- for a KV with no region at all. Measured: `-nkvo LLAMA_KV_RESIDENT_CELLS=64` built a plain `CPU KV buffer` of the whole context while announcing a 64-cell VRAM window. The window now declines once, with the reason (the pool already declines on `!offload`), so `-nkvo` means "no streamed placement"; `is_streaming()` tests `kv_region`, the placement actually taken, which also covers a device cache whose region buft the backend refused. Text is unchanged in every arm (the decline is a no-op: `-nkvo` + window already read as `-nkvo` alone). Amendment (issue ggml-org#264): the draft window is PER SEQUENCE, and under `--kv-unified` its cell count is `(win + one batch) x n_seq_max`. A unified cache holds every sequence in ONE stream, so the r193 sizing (`win + n_ubatch` cells) was shared by all of them: once the first sequence had filled its window the tail was all the room left, the tail is where that sequence's own ring writes, and a second sequence's first batch had no contiguous run to be placed in -- `find_slot` refused, and every request on that slot answered `decode() failed: failed to process speculative batch` (HTTP 500) while the drafter ran. Reported on `--kv-unified -np 2` with a 65 536-cell window at `-c 262144` after slot 0 held ~100k tokens; reproduced here with a forced 8192-cell window. A per-stream cache (no `--kv-unified`) already sized each stream separately and is unchanged. `llama_spec_draft_kv_cells()` is now the one geometry function -- the cache (`create_memory`), the slab's draft reserve estimate and the "is a window active" test in `common` all call it, so the reserve can never under-charge an allocation. It grants `win` per sequence plus one placeable batch (`(win + n_ubatch) * n_seq_max`, capped at the context), and DECLINES the window when that does not fit the context per sequence rather than lowering it to `per_seq - n_ubatch`: a window that small saves one batch of cells per sequence and masks the drafter's newest cells to do it. `llama_spec_draft_window_cells()` stays the policy (it is the per-sequence window). n_seq_max == 1 -- every `llama-cli`/`llama-bench` run -- measures exactly what it did (cells 1536 for a 1024-cell window at `-c 8192`), so no single-sequence arm changes at all. Measured (dense 27B, 1 GPU, `-np 2 --kv-unified`): the issue's scenario now answers both slots, and `scripts/gate-spec-draft-window.sh` (new) drives 6 requests over 2 slots with a 1024-cell window -- both rings wrapping, prompts full re-prefilled by swapping them between slots -- with output byte-identical to `LLAMA_SPEC_DRAFT_WINDOW=0` on every step and draft acceptance identical (17/36, 23/23). Greedy text `plain == draft-mtp == draft-mtp(W=1024) == draft-mtp(W=0)` (876 chars, sha 8c8fd395402f) at `-c 16384`. And the reserve now charges a per-STREAM (no `--kv-unified`) draft cache for every stream it allocates: `n_seq_max x` the per-stream cell count. Before, a multi-slot windowed MTP server without `--kv-unified` (35B-A3B `-ncmoe 40 -np 2 -c 8192`, window 1024: 2 x 1536 = 3072 cells allocated, 1536 charged) under-charged the slab's aux reserve by one stream's window -- the direction the reserve header calls dangerous. Measured: 3072 cells reported on both the unified and the per-stream arm now. ========================================================================== PART 4 -- `-sm tensor`: the window across a split (r204, `TODO` ggml-org#124) ========================================================================== A Meta (tensor-split) device carries no backend reg, so the r181 answer was "not provided" and the window was declined on every split. `TODO` ggml-org#124 designed the fix on a one-GPU box (`archive/work/kv-residency/ A6-TENSOR-SPLIT-WINDOW.md`, changes C1-C5); it is implemented and measured here, on a 3x R9700 host, and the decline is gone. * `ggml_backend_meta_kv_region_buft / _is_kv_buft / _grow` (new, `ggml-backend.h`): the Meta buffer type over the per-child region buffer types (ALL children or nothing), the is-a-region predicate `--fit` needs (the CUDA predicate is an identity on the child's `alloc_buffer` and cannot answer for a Meta buffer type), and a grow that fans out to every child. A child that cannot be reached is a REFUSAL (-1), never the 0 the CUDA hook returns for "not a region buffer": for a Meta buffer that 0 was a silent success on unmapped VA, i.e. a batch that page-faults the GPU. * `llama_kv_cache` resolves capability, the buffer type, the spill ceiling and the link through the Meta side; a MIRRORED cache (dsv4 / HRM, `llama_model::kv_cache_split_mirrored()`) declines the window with its own message, because every device holds the whole cache there (`n_devices x W x cell_bytes`) and the pinned-spill plan is per logical cache. * `common/fit.cpp` decides the window inside the tensor-split branch: charged at its PHYSICAL `W x cell_bytes` (what all devices commit together) against `min_i(target_i / ratio_i)`, which makes the aggregate check imply every device's (the loader shards the KV along the KV-head axis by the same ratio it shards the weights), and the Meta entry's margin is now the SUM of the children's `--fit-target`s (it was child 0's, so `(n_devices - 1) x target` silently vanished from the budget). The corrected KV term applies ONLY where a window is asked for: a run without `LLAMA_KV_RESIDENT_CELLS` keeps this branch's old arithmetic exactly, so the split's pre-existing `n_devices x` KV over-count is untouched outside the window arm. Four defects the arms found, fixed in the same block: 1. the init-time window commit was rounded up to a whole map unit past the tensor's own extent, and on a split each child is its own VA reservation -- the last tensor's inflated window was refused (`the KV window (4.00 MiB) could not be committed in VRAM on device 1`). Clamped to the region's END, in whole units (clamping to the tensor's own extent was tried first and is wrong: it leaves a short mapping off the unit grid and the next slide refuses to flip). 2. `ensure_span` refused a request that covered several WHOLE mappings; one batch can advance the boundary by more than one unit, and a 1 MiB unit is floored to the driver's 2 MiB granularity, so the request covered two mappings and aborted the batch. Whole mappings now flip one at a time; a request that covers a mapping only in PART is still refused (that loses bytes on this driver). 3. the batched state save issued a 2-D D2H per device and `hipMemcpy2DAsync` fails (`invalid argument`) when the range begins in a spilled region's pinned host mapping (the tensor-split checkpoint save aborted: `cache_k_l64 (view)`, 1024 B x 4782 rows). The region-backed directions of `get/set_tensor_2d_async` now go through the region buffer's own copy, ordered behind the compute stream like the pool mirror (a blocking default-stream copy does not wait for it, and the state saved mid-batch is torn). 4. that fallback's "contiguous rows = one copy" shortcut ignored the caller's destination pitch, which for a split splice is the FULL row, wider than one device's slice: the state-pipe gate failed on every cycle of all four async arms until a tight block required BOTH pitches to equal the width. Verified (gfx1201, `ROCBLAS_USE_HIPBLASLT=0` for every fresh-process pair): text byte-identical on `win3 == ref3` (3 devices, 4B, `057ea27b1009`) and `win2 == ref2 == win2mtp == ref2mtp` (2 devices, 27B, a 5246-token prompt, `7a7430617465`; draft acceptance 0.46154 in both MTP arms), also at a 1 MiB map unit; the spill is real on EVERY device (32 mapping flips each at 4 MiB, 128 at 1 MiB); a `-c 1048576` 2-device split (64 GiB of f16 KV) runs only because of the window; the single-device and `-nkvo` arms are unchanged; `--fit` on the split reports a WINDOWED cache and keeps the pinned `-c 524288` (plus the pinned-RAM ceiling's widen and drop arms, and `LLAMA_KV_REGION=0` silent); coherence identical to the r203 build on four no-window arms (3-GPU 4B, 2-GPU and 1-GPU 27B, 2-GPU host-expert 35B-A3B); prefill-logit 0.000000 / 100.000 %; Protocol A four-axis R/P/C/K 1.91x / 2.43x / 2.58x / 2.74x (acceptance 0.5869 / 0.8391 / 0.9112 / 0.9920, the r90 shape); `gate-spec-draft-window.sh` 6/6; `gate-state-pipe.sh` 2-GPU `-sm tensor` PASS with and without the window (the windowed arm failed before (3) and (4)); `GGML_CUDA_VMM_REGION_SELFTEST=1` PASS with a new multi-mapping arm; per-block build 1/1; `validate-set.sh` strict 16/16. Gate: `scripts/gate-kv-window-split.sh`. Record: `benchmarks/2026-11-01-kv-window-tensor-split-124.md`.
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Nov 3, 2026
…W (Goal A) and an attendance POOL (Goal B), both opt-in Goals A and B of TODO ggml-org#118, promoted from the `wip/kv-residency` campaign. This block is the delivery's "the KV does not have to be O(-c) of VRAM" work: TWO opt-in placements of the same cache, and each one is byte-identical to a build without it when its knob is unset. * the WINDOW (`LLAMA_KV_RESIDENT_CELLS=<cells>|auto`): the newest W cells stay in VRAM, everything older spills to pinned system RAM in the SAME VA reservation -- a positional window, no kernel or op change; * the POOL (`LLAMA_KV_REGION_POOL=<cells>`): the authoritative copy of the WHOLE context in a pinned host mirror, and a compact device pool of the pages a decode step actually attends to, which the QSA sparse read resolves through a page table (`GGML_OP_KV_POOL`). They are mutually exclusive by construction (the pool declines while a window is active) and they answer the same question from opposite ends: the window keeps the *newest* cells hot, the pool keeps the *attended* cells hot. Both report `is_streaming()`, so a streamed cache takes the sparse QSA decode arm (B2, below). ========================================================================== PART 1 -- the WINDOW (Goal A, promoted in r178) ========================================================================== Goal A of TODO ggml-org#118, promoted from the `wip/kv-residency` campaign. WHAT IT DOES. The KV cache's VRAM cost becomes a WINDOW of the newest `W` cells instead of `-c` cells: one VA reservation (a CUDA/HIP VMM region) holds the whole cache, the window's cells are backed by VRAM and everything below them by pinned system RAM. `set_rows`, the in-place rope shift, `state_write/read`, the kq mask and the FA kernels keep addressing one contiguous range, so no kernel and no op changes. The window slides with the watermark in whole map units, so a remap happens once per few thousand tokens and the apparatus itself is free (a zero-spill arm measures the same as plain). WHY. (a) A context that OOMs today runs: 27B Q8_0 `-c 262144` (8704 MiB of KV) now runs on one 32 GiB card at 128 MiB VRAM + 8576 MiB pinned host for the KV. (b) With host-resident MoE experts, the VRAM the KV does not need *yet* goes to the expert-cache arena: measured at `-c 262144`, `-n 2000`, `-ncmoe` = the model's full layer count, 51 433-token prompt, W at or above the run's depth = **+2.2 to +2.9 GiB of arena** (+3.9 to +6.7 points of residency) for free -- 122B-A10B Q4_K_XL +3.8 % decode and +4.7 % prefill, 35B-A3B Q8_0 -0.9 % decode and +3 % prefill; a `W` 35 k cells BELOW the run depth costs 11-26 % (the spill is read every token). OPT-IN, AND ONLY WHEN ASKED FOR. `LLAMA_KV_RESIDENT_CELLS=<cells>` (a number) or `=auto` (`--fit` sizes it, and only spills a context the user pinned with `-c`); unset/0 = no window. With no window the KV takes the PLAIN device buffer, so a run without the knob is byte-identical to a build without this block -- including its OOM (verified). `LLAMA_KV_SPILL_RAM_PCT` (85 % of MemAvailable) caps the pinned spill and widens the window rather than being OOM-killed; `LLAMA_KV_REGION=0` disables the provider; `LLAMA_KV_REGION_QUARANTINE=0` and `LLAMA_KV_REGION_DEBUG/TRACE/CANARY/DUMP` are the diagnosis switches. PURITY (the window). A spilled KV is numerically transparent: prefill-logit **KLD -0.000000 / 100.000 %** on a spilling 27B arm and -0.000000 / 99.994 % on a spilling Flash-Next (two KV caches: the attention KV and the QSA indexer), text byte-identical on 27B (f16 and q8_0), 4B, 35B-A3B and Flash-Next, and the state paths, the context-checkpoint path and the MTP verify widths all green on arms that provably spill. Two driver hazards are held: a kind flip zeroes a neighbouring live host mapping unless the released physical is held across the create (`LLAMA_KV_REGION_QUARANTINE`, default on -- `=0` reproduces the corruption), and every tensor in a windowed region is placed on the driver's map granularity so a slide step coincides with a mapping. An idle-slot park is REFUSED on a region-backed cache (the server then saves the slot to the prompt cache and clears it, which is byte-identical to the parking gate's reference) because a park moves cells above the region's mapped watermark through the copy engine, which faults the GPU. FIT. `--fit` sizes and reports the window (`auto`), or honours and reports a numeric `W`: the resident/spill split, the VRAM saved, and the per-token read cost at the model's full context from the backend's calibrated link rate. The fit identifies the KV's bytes by the region buffer TYPE, and its measurement context is a `no_alloc` probe that declines a window -- so the probe takes the region buffer explicitly (`llama_kv_region_set_probe`); without that the fit cannot see the KV, reports an over-budget config and aborts instead of sizing the window (the r178 regression). GATES (1 GPU, gfx1201): default path byte-identical (`5ba44647188f`) and still OOMs; VMM selftest PASS and FAIL with the hold disabled; windowed arms 305 `e2cea6fa6670` = plain at W=1024/2048/4096 (spilling at 1024: 128 MiB host), `QUARANTINE=0` -> 325 `fb65430049e9` (the hazard); `--fit` sizes `auto` (96680 of 262144 cells, 3210 MiB resident) and reports a numeric W; `gate-ckpt-reuse.sh` / `gate-state-pipe.sh` / MTP verify widths on spilling arms; `test-backend-ops -o FLASH_ATTN_QSA` 26/26; `check-gpu-faults.sh` clean. Not in this block: the campaign's Goal B (a sparse attended set) and Goal C (the MTP drafter ring, `LLAMA_SPEC_DRAFT_WINDOW`) -- both remain campaign work -- and A1 (the superseded two-base FA read). Records: `wip/kv-residency/A2-MIXED-BACKING.md` (§3.7.9, §3.7.11), `HANDOVER.md`. MULTI-DEVICE `--fit` (r181; the window itself reaches a tensor split in r204, at the end of this message): the KV-region glue is now safe on a Meta (tensor-split) device, and `auto`'s decision reaches the cache as a decision. r178 made default `--fit` abort on ANY `-sm tensor` run with more than one device: the fit's KV probes and the cache's own region lookups call `ggml_backend_dev_backend_reg(dev)` and hand it to `ggml_backend_reg_get_proc_address`, and a Meta device has no backend reg (`device->reg == NULL`), so `GGML_ASSERT(reg)` fired at model load. Three paths asserted: the fit probe (any run), the runtime buft lookup (a numeric W), and the spill budget/link lookups (a numeric W below `-c`). r181 makes a null reg read as "not provided" and declines the window with one message naming the tensor split (fit and cache), keeping the KV fully resident -- which is the r181 state; r204, below, is what makes the backend answer there. Three wiring defects in the same code, all visible on ONE device: - `auto`'s "no window needed" decision (0) was indistinguishable from "nobody decided", so the cache warned "--fit did not run" immediately after the fit had decided exactly that. `llama_kv_region_set_resident_cells` now records that a decision was made (`llama_kv_region_resident_cells_decided`), and a decided 0 is silent. - every run without the knob logged "the windowed KV is unavailable for this cache (no spilled cells)". That message now only fires when a window was actually requested and declined for a real reason. - the pinned-RAM ceiling clamp could raise W past the VRAM budget and then be reported as "does not make this fit either". It is now only taken while the wider window still meets the VRAM target; otherwise the fit says the ceiling cannot be served at this `-c` and drops the window (which the fit then fits by reducing the context). That ordering is not cosmetic: an intermediate form of this fix accepted a 235 GiB pinned spill plan for a 4B at `-c 8388608`, and creating it OOM-killed the test box. GATES (the window, gfx1201): `--fit on` (default) at 2 and 3 devices, `-sm tensor`, with no knob / a numeric W / `auto`, fit on and off: no assert, tokens produced, exactly one message per requested window. `-sm layer` 2 devices and 1 GPU still take the window per device (numeric W), and `auto` still sizes the 27B Q8_0 `-c 262144` q8_0 arm identically (123265 of 262144 cells, 4092.8 MiB resident / 4611.2 MiB spilling). One device, no knob: no KV message at all. Purity unchanged: plain vs a SPILLING windowed arm prefill-logit KLD 0.000000 / 99.990 % (q8_0 KV), greedy text byte-identical on that arm; 35B-A3B (1 GPU and 2-GPU `-sm tensor`), dense 27B and the canonical 27B Q8_0 prefill-logit gate (0.000000 / 100.000 %) byte-identical to r180; MTP Protocol A unchanged (tensor acceptance 0.60816 = 1937/3185, plain == draft-mtp); no GPU faults. ========================================================================== PART 2 -- the ATTENDANCE POOL (Goal B, promoted in r190) ========================================================================== The attention KV lives twice: its AUTHORITATIVE copy in a pinned host MIRROR (cell-indexed, so the writers, state_write/state_read, the K-shift, defrag and seq_park all work on it unchanged -- the writer rule) and a compact DEVICE POOL of pages of one indexer block (compress_ratio cells) with a page table block -> slot and its inverse. A decode step resolves its top-k selection through the table and fills the pages it missed from the mirror; the QSA reader gathers K/V at the pool slots while the mask stays cell-indexed. LLAMA_KV_REGION_POOL=<cells>, unset/0 = off = byte-identical. Contents. - ggml/src/ggml-cuda/kv-pool.{cu,cuh}: GGML_OP_KV_POOL. MARK sets use[slot] = epoch for every page this launch reads AND every page the batch just wrote (the graph's k_idxs), and queues the written ones for re-fill; CLAIM takes a slot for each DISTINCT missing block (the table CAS is the dedupe) and never takes a slot MARK protected; MAP+FILL writes each selected cell's pool position into the reader's K/V id list and copies the claimed and dirty pages from the mirror, K and V sharing slots. The epoch is a device counter incremented once per launch: the graph bakes pointers, never counters, and nothing is allocated per launch. - ggml-cuda.cu: the pool's pinned host mirror buffer type -- a DEVICE buffer type whose allocation is pinned host memory (`ROCm_Host` reports is_host, which would send the KV's writers and the FA read to the CPU on a discrete device), and its proc-address entry. - llama-kv-cache: the eligibility, the per-layer pool tensors (pool_k/pool_v, tbl, inv, use, one shared counter block), the resolve wiring into the QSA id list, kv_pool_serves() (a batch too wide for the pool takes the cell-indexed path), the teardown accounting (LLAMA_KV_POOL_STATS takes a PATH: a line on stderr sits inside the generated text), and memory_breakdown() charging the mirror to the host bucket so `--fit` does not reserve it as VRAM. - llama-memory-hybrid-idx / llama-memory-hybrid / llama-memory: the second id list (the K/V gather follows the page table while the mask stays cell-indexed), the flag threading, and the pool's byte accounting for `--fit` (llama_get_kv_pool_bytes()). - models/qwen4exp.cpp: a pooled cache reports is_streaming() and the sparse arm uses the pool's id list; the MTP draft's own cache is never pooled (its attention is dense). - llama-context / the async state copies: the mirror's buffer type is accepted by the batched save and restore (its bytes are host memory, staged through the pinned state_stage). - common/fit.cpp + src/llama-ext.h: the pool's split in --fit's arithmetic and report (the mirror is pinned host RAM, the pool is VRAM), and no context-reduction interpolation while the pool is active -- the pool's VRAM is fixed, so reducing -c frees nothing and the interpolation would divide by a near-zero bytes-per-context delta. Invariants, each one caught by the greedy text. 1. MARK then CLAIM: a claim must never evict a page the same launch reads. Without MARK the round-robin victim could be a page another row still needs (the text diverged ~400 chars in, and a pool larger than the whole cache hid it completely). 2. Claim ATTEMPTS are not distinct blocks: a slot per id attempt wrapped the cursor within one 4-row batch, so two blocks shared a slot and a just-resolved block went unresident. The table CAS dedupes first, so only distinct blocks consume a slot and kv_pool_serves() bounds the distinct count. 3. No transient scratch in a captured graph: the fill list lived in a ggml_cuda_pool_alloc that is freed at the end of the op, and a captured graph bakes the pointer, so a replay wrote into whatever op had been handed that block ("values verify clean, text differs run to run"). It lives in the counters tensor. 4. The mirror is AUTHORITATIVE: the writers land in it and a declared page is re-filled from it before the attention reads it, so an eviction costs nothing and nothing has to be invalidated -- except by a path that rewrites cells in place without going through the writers (the K-shift, a state restore), which calls kv_pool_invalidate(). 5. Eligibility is narrow on purpose: one stream, non-MLA, K and V both present, !v_trans, a uniform compress_ratio and cell geometry, no window active, a device-offloaded cache, and only the trunk context of a qwen4exp model. Anything else declines with one message and the KV is unchanged. 6. The pool is floored at one decode band's worth of blocks (8 x ceil(width/page) pages) so a verify batch cannot exhaust the slot budget, and the mirror is bounded at creation by LLAMA_KV_SPILL_RAM_PCT (it is pinned, non-swappable RAM) -- over the ceiling the pool is declined loudly instead of being OOM-killed. Measured (Flash-Next GSQ-IQ3_XXS, 1 GPU, -ncmoe 48, q8_0, the PLE flags, arms interleaved in one batch, -n 512, MTP depth 4; t/s and tokens/step): depth (ctx) dense sparse pool (204 MiB) text (-n 64) 5 298 (16 384) 72.09 71.58 71.27 pool == sparse: 332 chars dd1981213373 102 899 (131 072) 59.10 54.70 54.65 (5.3k / 51 475 references; dense differs) 180 035 (196 608) 48.94 43.16 43.41 pool == sparse: 861 chars 263c7f2be4d9 The pool lands ON the sparse ceiling at every depth (+0.5 / +0.6 / +0.58 %), so its placement is free and what remains against a resident KV (-7 % / -11 %) is the sparse decode arm's own indexer cost (block 11), not the KV's storage. A 204 MiB pool replaces the resident attention KV's 1 632 MiB at 103k / 2 448 MiB at 180k, and the freed VRAM goes to the expert arena: 103k plain decode, -n 2000, 23 579.8 -> 25 018.6 MiB (+1 438.8 MiB, +18 slots/table), expert hit 96.26 -> 97.02 %, cold reads 42.0 -> 31.6 GiB. The pool's own cost is 0.10-0.11 ms/token (mark/claim/map+fill) with fills 0.03-0.05 ms/step at 92-99 % hits, which is why a better page policy (LRU / F-LRU / a heat prior) is measured dead at this shape. Full numbers and the three-depth table: ../wip/kv-residency/BA-POOL-DESIGN.md §7-§8. PURITY (the pool). Greedy text pool == the resident sparse arm at 5.3k (332 dd1981213373), 51 475 depth (854 43b30de151b9) and 180k (861 263c7f2be4d9), with the dense arm differing as documented (GREEDY-PURITY §45/§63); LLAMA_KV_POOL_VERIFY=1 0 mismatches on every arm; gate-prefill-logits --ab "LLAMA_KV_REGION_POOL=..." 0.000000 / 100.000 % on the pool arm (base PPL 2.9225, bit-identical to the campaign's own base); gate-park-idle-slots, gate-ckpt-reuse and gate-state-pipe PASS on a pooled cache (the mirror is authoritative, which is what makes them trivial); test-backend-ops -o FLASH_ATTN_QSA pass; no GPU faults; and `--fit` accepts the arms that only fit with the pool (-ncmoe 21/22 at -c 262144: refused without it, accepted with it; -fitp moves 3 264 MiB from the device row to Host). ========================================================================== PART 3 -- a STREAMED cache takes the sparse decode arm (B2) ========================================================================== A cache that is streaming at the depth it reads -- a window the used extent has passed, or a pool -- takes the sparse QSA decode arm; a resident cache keeps the dense one. llama_kv_cache::is_streaming() plus the qwen4exp arm policy, LLAMA_QSA_DENSE_DECODE_STREAM=0 to restore the old behaviour. Measured on a spilled KV (Flash-Next IQ3_XXS, -ncmoe 48, q8_0, 1 GPU, -n 400, 2 reps): +34.3 % at 102 899 depth (23.42 -> 31.43 t/s) and +47.3 % at 180 035 (16.51 -> 24.31); a resident cache byte-identical (853 77a40bf40be1). This is a decode-ARM choice, i.e. a different attention regime (like GREEDY-PURITY §45/§63), so a streamed arm's text differs from the old dense-arm text by construction and a resident arm is the oracle. ========================================================================== DEFAULT OFF, for both placements ========================================================================== Neither knob is a speed feature on a config whose KV fits: the window costs the depth below W (11-26 %) and the pool costs the sparse-vs-dense gap (-7 % at 103k, -11 % at 180k). They are FITTABILITY features -- they turn an OOM into a run and they hand the freed VRAM to the expert arena -- so both are opt-in and both stay byte-identical, including the OOM, with their knobs unset. Do not "fix" the defaults. Goal C (the MTP drafter ring, TODO ggml-org#121) joins the same block -- it is the same claim applied to the draft context, and its default follows the delivery's own rule because it measures positive. `LLAMA_SPEC_DRAFT_WINDOW` gives the MTP draft context a sliding window instead of a `-c`-sized KV: unset or `auto` is the adaptive policy (a quarter of the context, clamped to [32768, 65536] cells), `0` is off (byte-identical to a build without it) and `N` is a cell count. The drafter reads its last few thousand tokens, so a window at or above that is free and one far below it costs 7-9 % of decode; the clamps keep it above that band, and the target verifies every token it proposes, so a truncated draft can only be slower. The ring is the shipped reclaim in `llama_kv_cache::find_slot` (`n_swa`), not a new allocator, and the derived kq mask stays valid -- its predicate compares each cell's POSITION, so a recycled cell reports its new one. The VRAM win needed one more piece: an embedded MTP head has no GGUF of its own, so the slab's draft reserve was the flat 3584 MiB and the freed VRAM never reached the expert arena. For an embedded MTP head with an active window the reserve is now derived from the model's own metadata with the weights zeroed (they are the target's) and the KV sized by the window: aux 3.50 -> 0.76 GiB, i.e. the arena gains ~2.8 GiB. A separate MTP draft GGUF (qwen4exp/Flash-Next) and an un-windowed run keep the flat constant exactly as before, and a declined arena preflight now re-evaluates when the smaller real value arrives instead of latching on the load-time estimate. Measured (1 GPU; one R9700; `-n 2000`/`-n 3000`; static depth 3; interleaved): * 35B-A3B Q8_0 `-ncmoe 48 -c 262144` q8_0 KV, 51 433-token prompt: arena 20 910 -> 23 715 MiB (residency 64.1 -> 72.7 %), decode 111.2 -> 113.7 t/s at `-n 3000` (+2.2 %; +2.8-4.9 % at `-n 2000`), prefill +3.4 %, drafts byte-for-byte the same count (1995/3011) -- the window truncates nothing the drafter used. * dense 27B UD-Q4_K_XL `-c 102400`, MTP Protocol A `-n 3000`, reasoning-pinned: layer 71.9 -> 72.1, tensor 72.6 -> 72.5 (neutral), acceptance 2083/2747 identical in all four arms. * target greedy text byte-identical across off/auto/4096, and plain == draft-mtp == draft-mtp(W=512) at `-c 16384` with a 5256-token prompt and 3000 generated tokens (10 158 chars, sha 99b267e8dc3e), i.e. no wrong answer under constant cell reuse. * gates on a windowed draft: `gate-park-idle-slots.sh` (35B, -ncmoe 48, `-c 65536`: 3 park moves, park == lazyoff), `gate-ckpt-reuse.sh` (4B, `-c 131072`: draft cache 33280 of 131072), `gate-state-pipe.sh` (35B, `-c 65536`: all five arms) -- all PASS with `MTP draft KV window = 32768 cells` in their logs. r194 corner fixes (found by a configuration battery against Flash-Next after r193): * LLAMA_KV_REGION_POOL is capped at the cache's own cell count. =1000000 on a 262144-cell context used to take a 12451 MiB device pool of 250000 pages where only 65536 blocks exist (never claimed, arena -4 GiB); it is now 3264 MiB / 65536 pages, and a small context clamps the same way. * the draft KV window sizes only the reserve of the cache it actually windows. A separate -md MTP head (Flash-Next) keeps its full -c cache, but the reserve was derived with the window: 921 MiB where the honest number is 1566 (kv 217 vs 862) at -c 262144, the under-charge direction. Embedded heads (qwen3.5/3.6/3.8) are unchanged (776 MiB on the 35B). The VRAM cliff at -c 262144 is documented (not code): the 768 MiB default headroom is one hipBLASLt workspace short for the first prefill, GGML_CUDA_SLAB_HEADROOM_MIB=1536 is 3/3 requests clean. Amendment (TODO ggml-org#129's sibling): `-nkvo` declines the window, and the streamed arm keys on the placement. The window is a DEVICE region plus a pinned host tail, but its guard did not test `offload`: with `-nkvo` the per-layer buffer is chosen inside `if (offload)` and stays plain pageable host memory, while the plan block still logged "WINDOWED KV ENABLED", reserved pinned-RAM spill budget and left `kv_resident_cells` set. `is_streaming()` then keyed the streamed (sparse) decode arm on that plan -- qwen4exp consumes it -- for a KV with no region at all. Measured: `-nkvo LLAMA_KV_RESIDENT_CELLS=64` built a plain `CPU KV buffer` of the whole context while announcing a 64-cell VRAM window. The window now declines once, with the reason (the pool already declines on `!offload`), so `-nkvo` means "no streamed placement"; `is_streaming()` tests `kv_region`, the placement actually taken, which also covers a device cache whose region buft the backend refused. Text is unchanged in every arm (the decline is a no-op: `-nkvo` + window already read as `-nkvo` alone). Amendment (issue ggml-org#264): the draft window is PER SEQUENCE, and under `--kv-unified` its cell count is `(win + one batch) x n_seq_max`. A unified cache holds every sequence in ONE stream, so the r193 sizing (`win + n_ubatch` cells) was shared by all of them: once the first sequence had filled its window the tail was all the room left, the tail is where that sequence's own ring writes, and a second sequence's first batch had no contiguous run to be placed in -- `find_slot` refused, and every request on that slot answered `decode() failed: failed to process speculative batch` (HTTP 500) while the drafter ran. Reported on `--kv-unified -np 2` with a 65 536-cell window at `-c 262144` after slot 0 held ~100k tokens; reproduced here with a forced 8192-cell window. A per-stream cache (no `--kv-unified`) already sized each stream separately and is unchanged. `llama_spec_draft_kv_cells()` is now the one geometry function -- the cache (`create_memory`), the slab's draft reserve estimate and the "is a window active" test in `common` all call it, so the reserve can never under-charge an allocation. It grants `win` per sequence plus one placeable batch (`(win + n_ubatch) * n_seq_max`, capped at the context), and DECLINES the window when that does not fit the context per sequence rather than lowering it to `per_seq - n_ubatch`: a window that small saves one batch of cells per sequence and masks the drafter's newest cells to do it. `llama_spec_draft_window_cells()` stays the policy (it is the per-sequence window). n_seq_max == 1 -- every `llama-cli`/`llama-bench` run -- measures exactly what it did (cells 1536 for a 1024-cell window at `-c 8192`), so no single-sequence arm changes at all. Measured (dense 27B, 1 GPU, `-np 2 --kv-unified`): the issue's scenario now answers both slots, and `scripts/gate-spec-draft-window.sh` (new) drives 6 requests over 2 slots with a 1024-cell window -- both rings wrapping, prompts full re-prefilled by swapping them between slots -- with output byte-identical to `LLAMA_SPEC_DRAFT_WINDOW=0` on every step and draft acceptance identical (17/36, 23/23). Greedy text `plain == draft-mtp == draft-mtp(W=1024) == draft-mtp(W=0)` (876 chars, sha 8c8fd395402f) at `-c 16384`. And the reserve now charges a per-STREAM (no `--kv-unified`) draft cache for every stream it allocates: `n_seq_max x` the per-stream cell count. Before, a multi-slot windowed MTP server without `--kv-unified` (35B-A3B `-ncmoe 40 -np 2 -c 8192`, window 1024: 2 x 1536 = 3072 cells allocated, 1536 charged) under-charged the slab's aux reserve by one stream's window -- the direction the reserve header calls dangerous. Measured: 3072 cells reported on both the unified and the per-stream arm now. ========================================================================== PART 4 -- `-sm tensor`: the window across a split (r204, `TODO` ggml-org#124) ========================================================================== A Meta (tensor-split) device carries no backend reg, so the r181 answer was "not provided" and the window was declined on every split. `TODO` ggml-org#124 designed the fix on a one-GPU box (`archive/work/kv-residency/ A6-TENSOR-SPLIT-WINDOW.md`, changes C1-C5); it is implemented and measured here, on a 3x R9700 host, and the decline is gone. * `ggml_backend_meta_kv_region_buft / _is_kv_buft / _grow` (new, `ggml-backend.h`): the Meta buffer type over the per-child region buffer types (ALL children or nothing), the is-a-region predicate `--fit` needs (the CUDA predicate is an identity on the child's `alloc_buffer` and cannot answer for a Meta buffer type), and a grow that fans out to every child. A child that cannot be reached is a REFUSAL (-1), never the 0 the CUDA hook returns for "not a region buffer": for a Meta buffer that 0 was a silent success on unmapped VA, i.e. a batch that page-faults the GPU. * `llama_kv_cache` resolves capability, the buffer type, the spill ceiling and the link through the Meta side; a MIRRORED cache (dsv4 / HRM, `llama_model::kv_cache_split_mirrored()`) declines the window with its own message, because every device holds the whole cache there (`n_devices x W x cell_bytes`) and the pinned-spill plan is per logical cache. * `common/fit.cpp` decides the window inside the tensor-split branch: charged at its PHYSICAL `W x cell_bytes` (what all devices commit together) against `min_i(target_i / ratio_i)`, which makes the aggregate check imply every device's (the loader shards the KV along the KV-head axis by the same ratio it shards the weights), and the Meta entry's margin is now the SUM of the children's `--fit-target`s (it was child 0's, so `(n_devices - 1) x target` silently vanished from the budget). The corrected KV term applies ONLY where a window is asked for: a run without `LLAMA_KV_RESIDENT_CELLS` keeps this branch's old arithmetic exactly, so the split's pre-existing `n_devices x` KV over-count is untouched outside the window arm. Four defects the arms found, fixed in the same block: 1. the init-time window commit was rounded up to a whole map unit past the tensor's own extent, and on a split each child is its own VA reservation -- the last tensor's inflated window was refused (`the KV window (4.00 MiB) could not be committed in VRAM on device 1`). Clamped to the region's END, in whole units (clamping to the tensor's own extent was tried first and is wrong: it leaves a short mapping off the unit grid and the next slide refuses to flip). 2. `ensure_span` refused a request that covered several WHOLE mappings; one batch can advance the boundary by more than one unit, and a 1 MiB unit is floored to the driver's 2 MiB granularity, so the request covered two mappings and aborted the batch. Whole mappings now flip one at a time; a request that covers a mapping only in PART is still refused (that loses bytes on this driver). 3. the batched state save issued a 2-D D2H per device and `hipMemcpy2DAsync` fails (`invalid argument`) when the range begins in a spilled region's pinned host mapping (the tensor-split checkpoint save aborted: `cache_k_l64 (view)`, 1024 B x 4782 rows). The region-backed directions of `get/set_tensor_2d_async` now go through the region buffer's own copy, ordered behind the compute stream like the pool mirror (a blocking default-stream copy does not wait for it, and the state saved mid-batch is torn). 4. that fallback's "contiguous rows = one copy" shortcut ignored the caller's destination pitch, which for a split splice is the FULL row, wider than one device's slice: the state-pipe gate failed on every cycle of all four async arms until a tight block required BOTH pitches to equal the width. Verified (gfx1201, `ROCBLAS_USE_HIPBLASLT=0` for every fresh-process pair): text byte-identical on `win3 == ref3` (3 devices, 4B, `057ea27b1009`) and `win2 == ref2 == win2mtp == ref2mtp` (2 devices, 27B, a 5246-token prompt, `7a7430617465`; draft acceptance 0.46154 in both MTP arms), also at a 1 MiB map unit; the spill is real on EVERY device (32 mapping flips each at 4 MiB, 128 at 1 MiB); a `-c 1048576` 2-device split (64 GiB of f16 KV) runs only because of the window; the single-device and `-nkvo` arms are unchanged; `--fit` on the split reports a WINDOWED cache and keeps the pinned `-c 524288` (plus the pinned-RAM ceiling's widen and drop arms, and `LLAMA_KV_REGION=0` silent); coherence identical to the r203 build on four no-window arms (3-GPU 4B, 2-GPU and 1-GPU 27B, 2-GPU host-expert 35B-A3B); prefill-logit 0.000000 / 100.000 %; Protocol A four-axis R/P/C/K 1.91x / 2.43x / 2.58x / 2.74x (acceptance 0.5869 / 0.8391 / 0.9112 / 0.9920, the r90 shape); `gate-spec-draft-window.sh` 6/6; `gate-state-pipe.sh` 2-GPU `-sm tensor` PASS with and without the window (the windowed arm failed before (3) and (4)); `GGML_CUDA_VMM_REGION_SELFTEST=1` PASS with a new multi-mapping arm; per-block build 1/1; `validate-set.sh` strict 16/16. Gate: `scripts/gate-kv-window-split.sh`. Record: `benchmarks/2026-11-01-kv-window-tensor-split-124.md`.
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Nov 3, 2026
…W (Goal A) and an attendance POOL (Goal B), both opt-in Goals A and B of TODO ggml-org#118, promoted from the `wip/kv-residency` campaign. This block is the delivery's "the KV does not have to be O(-c) of VRAM" work: TWO opt-in placements of the same cache, and each one is byte-identical to a build without it when its knob is unset. * the WINDOW (`LLAMA_KV_RESIDENT_CELLS=<cells>|auto`): the newest W cells stay in VRAM, everything older spills to pinned system RAM in the SAME VA reservation -- a positional window, no kernel or op change; * the POOL (`LLAMA_KV_REGION_POOL=<cells>`): the authoritative copy of the WHOLE context in a pinned host mirror, and a compact device pool of the pages a decode step actually attends to, which the QSA sparse read resolves through a page table (`GGML_OP_KV_POOL`). They are mutually exclusive by construction (the pool declines while a window is active) and they answer the same question from opposite ends: the window keeps the *newest* cells hot, the pool keeps the *attended* cells hot. Both report `is_streaming()`, so a streamed cache takes the sparse QSA decode arm (B2, below). ========================================================================== PART 1 -- the WINDOW (Goal A, promoted in r178) ========================================================================== Goal A of TODO ggml-org#118, promoted from the `wip/kv-residency` campaign. WHAT IT DOES. The KV cache's VRAM cost becomes a WINDOW of the newest `W` cells instead of `-c` cells: one VA reservation (a CUDA/HIP VMM region) holds the whole cache, the window's cells are backed by VRAM and everything below them by pinned system RAM. `set_rows`, the in-place rope shift, `state_write/read`, the kq mask and the FA kernels keep addressing one contiguous range, so no kernel and no op changes. The window slides with the watermark in whole map units, so a remap happens once per few thousand tokens and the apparatus itself is free (a zero-spill arm measures the same as plain). WHY. (a) A context that OOMs today runs: 27B Q8_0 `-c 262144` (8704 MiB of KV) now runs on one 32 GiB card at 128 MiB VRAM + 8576 MiB pinned host for the KV. (b) With host-resident MoE experts, the VRAM the KV does not need *yet* goes to the expert-cache arena: measured at `-c 262144`, `-n 2000`, `-ncmoe` = the model's full layer count, 51 433-token prompt, W at or above the run's depth = **+2.2 to +2.9 GiB of arena** (+3.9 to +6.7 points of residency) for free -- 122B-A10B Q4_K_XL +3.8 % decode and +4.7 % prefill, 35B-A3B Q8_0 -0.9 % decode and +3 % prefill; a `W` 35 k cells BELOW the run depth costs 11-26 % (the spill is read every token). OPT-IN, AND ONLY WHEN ASKED FOR. `LLAMA_KV_RESIDENT_CELLS=<cells>` (a number) or `=auto` (`--fit` sizes it, and only spills a context the user pinned with `-c`); unset/0 = no window. With no window the KV takes the PLAIN device buffer, so a run without the knob is byte-identical to a build without this block -- including its OOM (verified). `LLAMA_KV_SPILL_RAM_PCT` (85 % of MemAvailable) caps the pinned spill and widens the window rather than being OOM-killed; `LLAMA_KV_REGION=0` disables the provider; `LLAMA_KV_REGION_QUARANTINE=0` and `LLAMA_KV_REGION_DEBUG/TRACE/CANARY/DUMP` are the diagnosis switches. PURITY (the window). A spilled KV is numerically transparent: prefill-logit **KLD -0.000000 / 100.000 %** on a spilling 27B arm and -0.000000 / 99.994 % on a spilling Flash-Next (two KV caches: the attention KV and the QSA indexer), text byte-identical on 27B (f16 and q8_0), 4B, 35B-A3B and Flash-Next, and the state paths, the context-checkpoint path and the MTP verify widths all green on arms that provably spill. Two driver hazards are held: a kind flip zeroes a neighbouring live host mapping unless the released physical is held across the create (`LLAMA_KV_REGION_QUARANTINE`, default on -- `=0` reproduces the corruption), and every tensor in a windowed region is placed on the driver's map granularity so a slide step coincides with a mapping. An idle-slot park is REFUSED on a region-backed cache (the server then saves the slot to the prompt cache and clears it, which is byte-identical to the parking gate's reference) because a park moves cells above the region's mapped watermark through the copy engine, which faults the GPU. FIT. `--fit` sizes and reports the window (`auto`), or honours and reports a numeric `W`: the resident/spill split, the VRAM saved, and the per-token read cost at the model's full context from the backend's calibrated link rate. The fit identifies the KV's bytes by the region buffer TYPE, and its measurement context is a `no_alloc` probe that declines a window -- so the probe takes the region buffer explicitly (`llama_kv_region_set_probe`); without that the fit cannot see the KV, reports an over-budget config and aborts instead of sizing the window (the r178 regression). GATES (1 GPU, gfx1201): default path byte-identical (`5ba44647188f`) and still OOMs; VMM selftest PASS and FAIL with the hold disabled; windowed arms 305 `e2cea6fa6670` = plain at W=1024/2048/4096 (spilling at 1024: 128 MiB host), `QUARANTINE=0` -> 325 `fb65430049e9` (the hazard); `--fit` sizes `auto` (96680 of 262144 cells, 3210 MiB resident) and reports a numeric W; `gate-ckpt-reuse.sh` / `gate-state-pipe.sh` / MTP verify widths on spilling arms; `test-backend-ops -o FLASH_ATTN_QSA` 26/26; `check-gpu-faults.sh` clean. Not in this block: the campaign's Goal B (a sparse attended set) and Goal C (the MTP drafter ring, `LLAMA_SPEC_DRAFT_WINDOW`) -- both remain campaign work -- and A1 (the superseded two-base FA read). Records: `wip/kv-residency/A2-MIXED-BACKING.md` (§3.7.9, §3.7.11), `HANDOVER.md`. MULTI-DEVICE `--fit` (r181; the window itself reaches a tensor split in r204, at the end of this message): the KV-region glue is now safe on a Meta (tensor-split) device, and `auto`'s decision reaches the cache as a decision. r178 made default `--fit` abort on ANY `-sm tensor` run with more than one device: the fit's KV probes and the cache's own region lookups call `ggml_backend_dev_backend_reg(dev)` and hand it to `ggml_backend_reg_get_proc_address`, and a Meta device has no backend reg (`device->reg == NULL`), so `GGML_ASSERT(reg)` fired at model load. Three paths asserted: the fit probe (any run), the runtime buft lookup (a numeric W), and the spill budget/link lookups (a numeric W below `-c`). r181 makes a null reg read as "not provided" and declines the window with one message naming the tensor split (fit and cache), keeping the KV fully resident -- which is the r181 state; r204, below, is what makes the backend answer there. Three wiring defects in the same code, all visible on ONE device: - `auto`'s "no window needed" decision (0) was indistinguishable from "nobody decided", so the cache warned "--fit did not run" immediately after the fit had decided exactly that. `llama_kv_region_set_resident_cells` now records that a decision was made (`llama_kv_region_resident_cells_decided`), and a decided 0 is silent. - every run without the knob logged "the windowed KV is unavailable for this cache (no spilled cells)". That message now only fires when a window was actually requested and declined for a real reason. - the pinned-RAM ceiling clamp could raise W past the VRAM budget and then be reported as "does not make this fit either". It is now only taken while the wider window still meets the VRAM target; otherwise the fit says the ceiling cannot be served at this `-c` and drops the window (which the fit then fits by reducing the context). That ordering is not cosmetic: an intermediate form of this fix accepted a 235 GiB pinned spill plan for a 4B at `-c 8388608`, and creating it OOM-killed the test box. GATES (the window, gfx1201): `--fit on` (default) at 2 and 3 devices, `-sm tensor`, with no knob / a numeric W / `auto`, fit on and off: no assert, tokens produced, exactly one message per requested window. `-sm layer` 2 devices and 1 GPU still take the window per device (numeric W), and `auto` still sizes the 27B Q8_0 `-c 262144` q8_0 arm identically (123265 of 262144 cells, 4092.8 MiB resident / 4611.2 MiB spilling). One device, no knob: no KV message at all. Purity unchanged: plain vs a SPILLING windowed arm prefill-logit KLD 0.000000 / 99.990 % (q8_0 KV), greedy text byte-identical on that arm; 35B-A3B (1 GPU and 2-GPU `-sm tensor`), dense 27B and the canonical 27B Q8_0 prefill-logit gate (0.000000 / 100.000 %) byte-identical to r180; MTP Protocol A unchanged (tensor acceptance 0.60816 = 1937/3185, plain == draft-mtp); no GPU faults. ========================================================================== PART 2 -- the ATTENDANCE POOL (Goal B, promoted in r190) ========================================================================== The attention KV lives twice: its AUTHORITATIVE copy in a pinned host MIRROR (cell-indexed, so the writers, state_write/state_read, the K-shift, defrag and seq_park all work on it unchanged -- the writer rule) and a compact DEVICE POOL of pages of one indexer block (compress_ratio cells) with a page table block -> slot and its inverse. A decode step resolves its top-k selection through the table and fills the pages it missed from the mirror; the QSA reader gathers K/V at the pool slots while the mask stays cell-indexed. LLAMA_KV_REGION_POOL=<cells>, unset/0 = off = byte-identical. Contents. - ggml/src/ggml-cuda/kv-pool.{cu,cuh}: GGML_OP_KV_POOL. MARK sets use[slot] = epoch for every page this launch reads AND every page the batch just wrote (the graph's k_idxs), and queues the written ones for re-fill; CLAIM takes a slot for each DISTINCT missing block (the table CAS is the dedupe) and never takes a slot MARK protected; MAP+FILL writes each selected cell's pool position into the reader's K/V id list and copies the claimed and dirty pages from the mirror, K and V sharing slots. The epoch is a device counter incremented once per launch: the graph bakes pointers, never counters, and nothing is allocated per launch. - ggml-cuda.cu: the pool's pinned host mirror buffer type -- a DEVICE buffer type whose allocation is pinned host memory (`ROCm_Host` reports is_host, which would send the KV's writers and the FA read to the CPU on a discrete device), and its proc-address entry. - llama-kv-cache: the eligibility, the per-layer pool tensors (pool_k/pool_v, tbl, inv, use, one shared counter block), the resolve wiring into the QSA id list, kv_pool_serves() (a batch too wide for the pool takes the cell-indexed path), the teardown accounting (LLAMA_KV_POOL_STATS takes a PATH: a line on stderr sits inside the generated text), and memory_breakdown() charging the mirror to the host bucket so `--fit` does not reserve it as VRAM. - llama-memory-hybrid-idx / llama-memory-hybrid / llama-memory: the second id list (the K/V gather follows the page table while the mask stays cell-indexed), the flag threading, and the pool's byte accounting for `--fit` (llama_get_kv_pool_bytes()). - models/qwen4exp.cpp: a pooled cache reports is_streaming() and the sparse arm uses the pool's id list; the MTP draft's own cache is never pooled (its attention is dense). - llama-context / the async state copies: the mirror's buffer type is accepted by the batched save and restore (its bytes are host memory, staged through the pinned state_stage). - common/fit.cpp + src/llama-ext.h: the pool's split in --fit's arithmetic and report (the mirror is pinned host RAM, the pool is VRAM), and no context-reduction interpolation while the pool is active -- the pool's VRAM is fixed, so reducing -c frees nothing and the interpolation would divide by a near-zero bytes-per-context delta. Invariants, each one caught by the greedy text. 1. MARK then CLAIM: a claim must never evict a page the same launch reads. Without MARK the round-robin victim could be a page another row still needs (the text diverged ~400 chars in, and a pool larger than the whole cache hid it completely). 2. Claim ATTEMPTS are not distinct blocks: a slot per id attempt wrapped the cursor within one 4-row batch, so two blocks shared a slot and a just-resolved block went unresident. The table CAS dedupes first, so only distinct blocks consume a slot and kv_pool_serves() bounds the distinct count. 3. No transient scratch in a captured graph: the fill list lived in a ggml_cuda_pool_alloc that is freed at the end of the op, and a captured graph bakes the pointer, so a replay wrote into whatever op had been handed that block ("values verify clean, text differs run to run"). It lives in the counters tensor. 4. The mirror is AUTHORITATIVE: the writers land in it and a declared page is re-filled from it before the attention reads it, so an eviction costs nothing and nothing has to be invalidated -- except by a path that rewrites cells in place without going through the writers (the K-shift, a state restore), which calls kv_pool_invalidate(). 5. Eligibility is narrow on purpose: one stream, non-MLA, K and V both present, !v_trans, a uniform compress_ratio and cell geometry, no window active, a device-offloaded cache, and only the trunk context of a qwen4exp model. Anything else declines with one message and the KV is unchanged. 6. The pool is floored at one decode band's worth of blocks (8 x ceil(width/page) pages) so a verify batch cannot exhaust the slot budget, and the mirror is bounded at creation by LLAMA_KV_SPILL_RAM_PCT (it is pinned, non-swappable RAM) -- over the ceiling the pool is declined loudly instead of being OOM-killed. Measured (Flash-Next GSQ-IQ3_XXS, 1 GPU, -ncmoe 48, q8_0, the PLE flags, arms interleaved in one batch, -n 512, MTP depth 4; t/s and tokens/step): depth (ctx) dense sparse pool (204 MiB) text (-n 64) 5 298 (16 384) 72.09 71.58 71.27 pool == sparse: 332 chars dd1981213373 102 899 (131 072) 59.10 54.70 54.65 (5.3k / 51 475 references; dense differs) 180 035 (196 608) 48.94 43.16 43.41 pool == sparse: 861 chars 263c7f2be4d9 The pool lands ON the sparse ceiling at every depth (+0.5 / +0.6 / +0.58 %), so its placement is free and what remains against a resident KV (-7 % / -11 %) is the sparse decode arm's own indexer cost (block 11), not the KV's storage. A 204 MiB pool replaces the resident attention KV's 1 632 MiB at 103k / 2 448 MiB at 180k, and the freed VRAM goes to the expert arena: 103k plain decode, -n 2000, 23 579.8 -> 25 018.6 MiB (+1 438.8 MiB, +18 slots/table), expert hit 96.26 -> 97.02 %, cold reads 42.0 -> 31.6 GiB. The pool's own cost is 0.10-0.11 ms/token (mark/claim/map+fill) with fills 0.03-0.05 ms/step at 92-99 % hits, which is why a better page policy (LRU / F-LRU / a heat prior) is measured dead at this shape. Full numbers and the three-depth table: ../wip/kv-residency/BA-POOL-DESIGN.md §7-§8. PURITY (the pool). Greedy text pool == the resident sparse arm at 5.3k (332 dd1981213373), 51 475 depth (854 43b30de151b9) and 180k (861 263c7f2be4d9), with the dense arm differing as documented (GREEDY-PURITY §45/§63); LLAMA_KV_POOL_VERIFY=1 0 mismatches on every arm; gate-prefill-logits --ab "LLAMA_KV_REGION_POOL=..." 0.000000 / 100.000 % on the pool arm (base PPL 2.9225, bit-identical to the campaign's own base); gate-park-idle-slots, gate-ckpt-reuse and gate-state-pipe PASS on a pooled cache (the mirror is authoritative, which is what makes them trivial); test-backend-ops -o FLASH_ATTN_QSA pass; no GPU faults; and `--fit` accepts the arms that only fit with the pool (-ncmoe 21/22 at -c 262144: refused without it, accepted with it; -fitp moves 3 264 MiB from the device row to Host). ========================================================================== PART 3 -- a STREAMED cache takes the sparse decode arm (B2) ========================================================================== A cache that is streaming at the depth it reads -- a window the used extent has passed, or a pool -- takes the sparse QSA decode arm; a resident cache keeps the dense one. llama_kv_cache::is_streaming() plus the qwen4exp arm policy, LLAMA_QSA_DENSE_DECODE_STREAM=0 to restore the old behaviour. Measured on a spilled KV (Flash-Next IQ3_XXS, -ncmoe 48, q8_0, 1 GPU, -n 400, 2 reps): +34.3 % at 102 899 depth (23.42 -> 31.43 t/s) and +47.3 % at 180 035 (16.51 -> 24.31); a resident cache byte-identical (853 77a40bf40be1). This is a decode-ARM choice, i.e. a different attention regime (like GREEDY-PURITY §45/§63), so a streamed arm's text differs from the old dense-arm text by construction and a resident arm is the oracle. ========================================================================== DEFAULT OFF, for both placements ========================================================================== Neither knob is a speed feature on a config whose KV fits: the window costs the depth below W (11-26 %) and the pool costs the sparse-vs-dense gap (-7 % at 103k, -11 % at 180k). They are FITTABILITY features -- they turn an OOM into a run and they hand the freed VRAM to the expert arena -- so both are opt-in and both stay byte-identical, including the OOM, with their knobs unset. Do not "fix" the defaults. Goal C (the MTP drafter ring, TODO ggml-org#121) joins the same block -- it is the same claim applied to the draft context, and its default follows the delivery's own rule because it measures positive. `LLAMA_SPEC_DRAFT_WINDOW` gives the MTP draft context a sliding window instead of a `-c`-sized KV: unset or `auto` is the adaptive policy (a quarter of the context, clamped to [32768, 65536] cells), `0` is off (byte-identical to a build without it) and `N` is a cell count. The drafter reads its last few thousand tokens, so a window at or above that is free and one far below it costs 7-9 % of decode; the clamps keep it above that band, and the target verifies every token it proposes, so a truncated draft can only be slower. The ring is the shipped reclaim in `llama_kv_cache::find_slot` (`n_swa`), not a new allocator, and the derived kq mask stays valid -- its predicate compares each cell's POSITION, so a recycled cell reports its new one. The VRAM win needed one more piece: an embedded MTP head has no GGUF of its own, so the slab's draft reserve was the flat 3584 MiB and the freed VRAM never reached the expert arena. For an embedded MTP head with an active window the reserve is now derived from the model's own metadata with the weights zeroed (they are the target's) and the KV sized by the window: aux 3.50 -> 0.76 GiB, i.e. the arena gains ~2.8 GiB. A separate MTP draft GGUF (qwen4exp/Flash-Next) and an un-windowed run keep the flat constant exactly as before, and a declined arena preflight now re-evaluates when the smaller real value arrives instead of latching on the load-time estimate. Measured (1 GPU; one R9700; `-n 2000`/`-n 3000`; static depth 3; interleaved): * 35B-A3B Q8_0 `-ncmoe 48 -c 262144` q8_0 KV, 51 433-token prompt: arena 20 910 -> 23 715 MiB (residency 64.1 -> 72.7 %), decode 111.2 -> 113.7 t/s at `-n 3000` (+2.2 %; +2.8-4.9 % at `-n 2000`), prefill +3.4 %, drafts byte-for-byte the same count (1995/3011) -- the window truncates nothing the drafter used. * dense 27B UD-Q4_K_XL `-c 102400`, MTP Protocol A `-n 3000`, reasoning-pinned: layer 71.9 -> 72.1, tensor 72.6 -> 72.5 (neutral), acceptance 2083/2747 identical in all four arms. * target greedy text byte-identical across off/auto/4096, and plain == draft-mtp == draft-mtp(W=512) at `-c 16384` with a 5256-token prompt and 3000 generated tokens (10 158 chars, sha 99b267e8dc3e), i.e. no wrong answer under constant cell reuse. * gates on a windowed draft: `gate-park-idle-slots.sh` (35B, -ncmoe 48, `-c 65536`: 3 park moves, park == lazyoff), `gate-ckpt-reuse.sh` (4B, `-c 131072`: draft cache 33280 of 131072), `gate-state-pipe.sh` (35B, `-c 65536`: all five arms) -- all PASS with `MTP draft KV window = 32768 cells` in their logs. r194 corner fixes (found by a configuration battery against Flash-Next after r193): * LLAMA_KV_REGION_POOL is capped at the cache's own cell count. =1000000 on a 262144-cell context used to take a 12451 MiB device pool of 250000 pages where only 65536 blocks exist (never claimed, arena -4 GiB); it is now 3264 MiB / 65536 pages, and a small context clamps the same way. * the draft KV window sizes only the reserve of the cache it actually windows. A separate -md MTP head (Flash-Next) keeps its full -c cache, but the reserve was derived with the window: 921 MiB where the honest number is 1566 (kv 217 vs 862) at -c 262144, the under-charge direction. Embedded heads (qwen3.5/3.6/3.8) are unchanged (776 MiB on the 35B). The VRAM cliff at -c 262144 is documented (not code): the 768 MiB default headroom is one hipBLASLt workspace short for the first prefill, GGML_CUDA_SLAB_HEADROOM_MIB=1536 is 3/3 requests clean. Amendment (TODO ggml-org#129's sibling): `-nkvo` declines the window, and the streamed arm keys on the placement. The window is a DEVICE region plus a pinned host tail, but its guard did not test `offload`: with `-nkvo` the per-layer buffer is chosen inside `if (offload)` and stays plain pageable host memory, while the plan block still logged "WINDOWED KV ENABLED", reserved pinned-RAM spill budget and left `kv_resident_cells` set. `is_streaming()` then keyed the streamed (sparse) decode arm on that plan -- qwen4exp consumes it -- for a KV with no region at all. Measured: `-nkvo LLAMA_KV_RESIDENT_CELLS=64` built a plain `CPU KV buffer` of the whole context while announcing a 64-cell VRAM window. The window now declines once, with the reason (the pool already declines on `!offload`), so `-nkvo` means "no streamed placement"; `is_streaming()` tests `kv_region`, the placement actually taken, which also covers a device cache whose region buft the backend refused. Text is unchanged in every arm (the decline is a no-op: `-nkvo` + window already read as `-nkvo` alone). Amendment (issue ggml-org#264): the draft window is PER SEQUENCE, and under `--kv-unified` its cell count is `(win + one batch) x n_seq_max`. A unified cache holds every sequence in ONE stream, so the r193 sizing (`win + n_ubatch` cells) was shared by all of them: once the first sequence had filled its window the tail was all the room left, the tail is where that sequence's own ring writes, and a second sequence's first batch had no contiguous run to be placed in -- `find_slot` refused, and every request on that slot answered `decode() failed: failed to process speculative batch` (HTTP 500) while the drafter ran. Reported on `--kv-unified -np 2` with a 65 536-cell window at `-c 262144` after slot 0 held ~100k tokens; reproduced here with a forced 8192-cell window. A per-stream cache (no `--kv-unified`) already sized each stream separately and is unchanged. `llama_spec_draft_kv_cells()` is now the one geometry function -- the cache (`create_memory`), the slab's draft reserve estimate and the "is a window active" test in `common` all call it, so the reserve can never under-charge an allocation. It grants `win` per sequence plus one placeable batch (`(win + n_ubatch) * n_seq_max`, capped at the context), and DECLINES the window when that does not fit the context per sequence rather than lowering it to `per_seq - n_ubatch`: a window that small saves one batch of cells per sequence and masks the drafter's newest cells to do it. `llama_spec_draft_window_cells()` stays the policy (it is the per-sequence window). n_seq_max == 1 -- every `llama-cli`/`llama-bench` run -- measures exactly what it did (cells 1536 for a 1024-cell window at `-c 8192`), so no single-sequence arm changes at all. Measured (dense 27B, 1 GPU, `-np 2 --kv-unified`): the issue's scenario now answers both slots, and `scripts/gate-spec-draft-window.sh` (new) drives 6 requests over 2 slots with a 1024-cell window -- both rings wrapping, prompts full re-prefilled by swapping them between slots -- with output byte-identical to `LLAMA_SPEC_DRAFT_WINDOW=0` on every step and draft acceptance identical (17/36, 23/23). Greedy text `plain == draft-mtp == draft-mtp(W=1024) == draft-mtp(W=0)` (876 chars, sha 8c8fd395402f) at `-c 16384`. And the reserve now charges a per-STREAM (no `--kv-unified`) draft cache for every stream it allocates: `n_seq_max x` the per-stream cell count. Before, a multi-slot windowed MTP server without `--kv-unified` (35B-A3B `-ncmoe 40 -np 2 -c 8192`, window 1024: 2 x 1536 = 3072 cells allocated, 1536 charged) under-charged the slab's aux reserve by one stream's window -- the direction the reserve header calls dangerous. Measured: 3072 cells reported on both the unified and the per-stream arm now. ========================================================================== PART 4 -- `-sm tensor`: the window across a split (r204, `TODO` ggml-org#124) ========================================================================== A Meta (tensor-split) device carries no backend reg, so the r181 answer was "not provided" and the window was declined on every split. `TODO` ggml-org#124 designed the fix on a one-GPU box (`archive/work/kv-residency/ A6-TENSOR-SPLIT-WINDOW.md`, changes C1-C5); it is implemented and measured here, on a 3x R9700 host, and the decline is gone. * `ggml_backend_meta_kv_region_buft / _is_kv_buft / _grow` (new, `ggml-backend.h`): the Meta buffer type over the per-child region buffer types (ALL children or nothing), the is-a-region predicate `--fit` needs (the CUDA predicate is an identity on the child's `alloc_buffer` and cannot answer for a Meta buffer type), and a grow that fans out to every child. A child that cannot be reached is a REFUSAL (-1), never the 0 the CUDA hook returns for "not a region buffer": for a Meta buffer that 0 was a silent success on unmapped VA, i.e. a batch that page-faults the GPU. * `llama_kv_cache` resolves capability, the buffer type, the spill ceiling and the link through the Meta side; a MIRRORED cache (dsv4 / HRM, `llama_model::kv_cache_split_mirrored()`) declines the window with its own message, because every device holds the whole cache there (`n_devices x W x cell_bytes`) and the pinned-spill plan is per logical cache. * `common/fit.cpp` decides the window inside the tensor-split branch: charged at its PHYSICAL `W x cell_bytes` (what all devices commit together) against `min_i(target_i / ratio_i)`, which makes the aggregate check imply every device's (the loader shards the KV along the KV-head axis by the same ratio it shards the weights), and the Meta entry's margin is now the SUM of the children's `--fit-target`s (it was child 0's, so `(n_devices - 1) x target` silently vanished from the budget). The corrected KV term applies ONLY where a window is asked for: a run without `LLAMA_KV_RESIDENT_CELLS` keeps this branch's old arithmetic exactly, so the split's pre-existing `n_devices x` KV over-count is untouched outside the window arm. Four defects the arms found, fixed in the same block: 1. the init-time window commit was rounded up to a whole map unit past the tensor's own extent, and on a split each child is its own VA reservation -- the last tensor's inflated window was refused (`the KV window (4.00 MiB) could not be committed in VRAM on device 1`). Clamped to the region's END, in whole units (clamping to the tensor's own extent was tried first and is wrong: it leaves a short mapping off the unit grid and the next slide refuses to flip). 2. `ensure_span` refused a request that covered several WHOLE mappings; one batch can advance the boundary by more than one unit, and a 1 MiB unit is floored to the driver's 2 MiB granularity, so the request covered two mappings and aborted the batch. Whole mappings now flip one at a time; a request that covers a mapping only in PART is still refused (that loses bytes on this driver). 3. the batched state save issued a 2-D D2H per device and `hipMemcpy2DAsync` fails (`invalid argument`) when the range begins in a spilled region's pinned host mapping (the tensor-split checkpoint save aborted: `cache_k_l64 (view)`, 1024 B x 4782 rows). The region-backed directions of `get/set_tensor_2d_async` now go through the region buffer's own copy, ordered behind the compute stream like the pool mirror (a blocking default-stream copy does not wait for it, and the state saved mid-batch is torn). 4. that fallback's "contiguous rows = one copy" shortcut ignored the caller's destination pitch, which for a split splice is the FULL row, wider than one device's slice: the state-pipe gate failed on every cycle of all four async arms until a tight block required BOTH pitches to equal the width. Verified (gfx1201, `ROCBLAS_USE_HIPBLASLT=0` for every fresh-process pair): text byte-identical on `win3 == ref3` (3 devices, 4B, `057ea27b1009`) and `win2 == ref2 == win2mtp == ref2mtp` (2 devices, 27B, a 5246-token prompt, `7a7430617465`; draft acceptance 0.46154 in both MTP arms), also at a 1 MiB map unit; the spill is real on EVERY device (32 mapping flips each at 4 MiB, 128 at 1 MiB); a `-c 1048576` 2-device split (64 GiB of f16 KV) runs only because of the window; the single-device and `-nkvo` arms are unchanged; `--fit` on the split reports a WINDOWED cache and keeps the pinned `-c 524288` (plus the pinned-RAM ceiling's widen and drop arms, and `LLAMA_KV_REGION=0` silent); coherence identical to the r203 build on four no-window arms (3-GPU 4B, 2-GPU and 1-GPU 27B, 2-GPU host-expert 35B-A3B); prefill-logit 0.000000 / 100.000 %; Protocol A four-axis R/P/C/K 1.91x / 2.43x / 2.58x / 2.74x (acceptance 0.5869 / 0.8391 / 0.9112 / 0.9920, the r90 shape); `gate-spec-draft-window.sh` 6/6; `gate-state-pipe.sh` 2-GPU `-sm tensor` PASS with and without the window (the windowed arm failed before (3) and (4)); `GGML_CUDA_VMM_REGION_SELFTEST=1` PASS with a new multi-mapping arm; per-block build 1/1; `validate-set.sh` strict 16/16. Gate: `scripts/gate-kv-window-split.sh`. Record: `benchmarks/2026-11-01-kv-window-tensor-split-124.md`.
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Nov 3, 2026
…W (Goal A) and an attendance POOL (Goal B), both opt-in Goals A and B of TODO ggml-org#118, promoted from the `wip/kv-residency` campaign. This block is the delivery's "the KV does not have to be O(-c) of VRAM" work: TWO opt-in placements of the same cache, and each one is byte-identical to a build without it when its knob is unset. * the WINDOW (`LLAMA_KV_RESIDENT_CELLS=<cells>|auto`): the newest W cells stay in VRAM, everything older spills to pinned system RAM in the SAME VA reservation -- a positional window, no kernel or op change; * the POOL (`LLAMA_KV_REGION_POOL=<cells>`): the authoritative copy of the WHOLE context in a pinned host mirror, and a compact device pool of the pages a decode step actually attends to, which the QSA sparse read resolves through a page table (`GGML_OP_KV_POOL`). They are mutually exclusive by construction (the pool declines while a window is active) and they answer the same question from opposite ends: the window keeps the *newest* cells hot, the pool keeps the *attended* cells hot. Both report `is_streaming()`, so a streamed cache takes the sparse QSA decode arm (B2, below). ========================================================================== PART 1 -- the WINDOW (Goal A, promoted in r178) ========================================================================== Goal A of TODO ggml-org#118, promoted from the `wip/kv-residency` campaign. WHAT IT DOES. The KV cache's VRAM cost becomes a WINDOW of the newest `W` cells instead of `-c` cells: one VA reservation (a CUDA/HIP VMM region) holds the whole cache, the window's cells are backed by VRAM and everything below them by pinned system RAM. `set_rows`, the in-place rope shift, `state_write/read`, the kq mask and the FA kernels keep addressing one contiguous range, so no kernel and no op changes. The window slides with the watermark in whole map units, so a remap happens once per few thousand tokens and the apparatus itself is free (a zero-spill arm measures the same as plain). WHY. (a) A context that OOMs today runs: 27B Q8_0 `-c 262144` (8704 MiB of KV) now runs on one 32 GiB card at 128 MiB VRAM + 8576 MiB pinned host for the KV. (b) With host-resident MoE experts, the VRAM the KV does not need *yet* goes to the expert-cache arena: measured at `-c 262144`, `-n 2000`, `-ncmoe` = the model's full layer count, 51 433-token prompt, W at or above the run's depth = **+2.2 to +2.9 GiB of arena** (+3.9 to +6.7 points of residency) for free -- 122B-A10B Q4_K_XL +3.8 % decode and +4.7 % prefill, 35B-A3B Q8_0 -0.9 % decode and +3 % prefill; a `W` 35 k cells BELOW the run depth costs 11-26 % (the spill is read every token). OPT-IN, AND ONLY WHEN ASKED FOR. `LLAMA_KV_RESIDENT_CELLS=<cells>` (a number) or `=auto` (`--fit` sizes it, and only spills a context the user pinned with `-c`); unset/0 = no window. With no window the KV takes the PLAIN device buffer, so a run without the knob is byte-identical to a build without this block -- including its OOM (verified). `LLAMA_KV_SPILL_RAM_PCT` (85 % of MemAvailable) caps the pinned spill and widens the window rather than being OOM-killed; `LLAMA_KV_REGION=0` disables the provider; `LLAMA_KV_REGION_QUARANTINE=0` and `LLAMA_KV_REGION_DEBUG/TRACE/CANARY/DUMP` are the diagnosis switches. PURITY (the window). A spilled KV is numerically transparent: prefill-logit **KLD -0.000000 / 100.000 %** on a spilling 27B arm and -0.000000 / 99.994 % on a spilling Flash-Next (two KV caches: the attention KV and the QSA indexer), text byte-identical on 27B (f16 and q8_0), 4B, 35B-A3B and Flash-Next, and the state paths, the context-checkpoint path and the MTP verify widths all green on arms that provably spill. Two driver hazards are held: a kind flip zeroes a neighbouring live host mapping unless the released physical is held across the create (`LLAMA_KV_REGION_QUARANTINE`, default on -- `=0` reproduces the corruption), and every tensor in a windowed region is placed on the driver's map granularity so a slide step coincides with a mapping. An idle-slot park is REFUSED on a region-backed cache (the server then saves the slot to the prompt cache and clears it, which is byte-identical to the parking gate's reference) because a park moves cells above the region's mapped watermark through the copy engine, which faults the GPU. FIT. `--fit` sizes and reports the window (`auto`), or honours and reports a numeric `W`: the resident/spill split, the VRAM saved, and the per-token read cost at the model's full context from the backend's calibrated link rate. The fit identifies the KV's bytes by the region buffer TYPE, and its measurement context is a `no_alloc` probe that declines a window -- so the probe takes the region buffer explicitly (`llama_kv_region_set_probe`); without that the fit cannot see the KV, reports an over-budget config and aborts instead of sizing the window (the r178 regression). GATES (1 GPU, gfx1201): default path byte-identical (`5ba44647188f`) and still OOMs; VMM selftest PASS and FAIL with the hold disabled; windowed arms 305 `e2cea6fa6670` = plain at W=1024/2048/4096 (spilling at 1024: 128 MiB host), `QUARANTINE=0` -> 325 `fb65430049e9` (the hazard); `--fit` sizes `auto` (96680 of 262144 cells, 3210 MiB resident) and reports a numeric W; `gate-ckpt-reuse.sh` / `gate-state-pipe.sh` / MTP verify widths on spilling arms; `test-backend-ops -o FLASH_ATTN_QSA` 26/26; `check-gpu-faults.sh` clean. Not in this block: the campaign's Goal B (a sparse attended set) and Goal C (the MTP drafter ring, `LLAMA_SPEC_DRAFT_WINDOW`) -- both remain campaign work -- and A1 (the superseded two-base FA read). Records: `wip/kv-residency/A2-MIXED-BACKING.md` (§3.7.9, §3.7.11), `HANDOVER.md`. MULTI-DEVICE `--fit` (r181; the window itself reaches a tensor split in r204, at the end of this message): the KV-region glue is now safe on a Meta (tensor-split) device, and `auto`'s decision reaches the cache as a decision. r178 made default `--fit` abort on ANY `-sm tensor` run with more than one device: the fit's KV probes and the cache's own region lookups call `ggml_backend_dev_backend_reg(dev)` and hand it to `ggml_backend_reg_get_proc_address`, and a Meta device has no backend reg (`device->reg == NULL`), so `GGML_ASSERT(reg)` fired at model load. Three paths asserted: the fit probe (any run), the runtime buft lookup (a numeric W), and the spill budget/link lookups (a numeric W below `-c`). r181 makes a null reg read as "not provided" and declines the window with one message naming the tensor split (fit and cache), keeping the KV fully resident -- which is the r181 state; r204, below, is what makes the backend answer there. Three wiring defects in the same code, all visible on ONE device: - `auto`'s "no window needed" decision (0) was indistinguishable from "nobody decided", so the cache warned "--fit did not run" immediately after the fit had decided exactly that. `llama_kv_region_set_resident_cells` now records that a decision was made (`llama_kv_region_resident_cells_decided`), and a decided 0 is silent. - every run without the knob logged "the windowed KV is unavailable for this cache (no spilled cells)". That message now only fires when a window was actually requested and declined for a real reason. - the pinned-RAM ceiling clamp could raise W past the VRAM budget and then be reported as "does not make this fit either". It is now only taken while the wider window still meets the VRAM target; otherwise the fit says the ceiling cannot be served at this `-c` and drops the window (which the fit then fits by reducing the context). That ordering is not cosmetic: an intermediate form of this fix accepted a 235 GiB pinned spill plan for a 4B at `-c 8388608`, and creating it OOM-killed the test box. GATES (the window, gfx1201): `--fit on` (default) at 2 and 3 devices, `-sm tensor`, with no knob / a numeric W / `auto`, fit on and off: no assert, tokens produced, exactly one message per requested window. `-sm layer` 2 devices and 1 GPU still take the window per device (numeric W), and `auto` still sizes the 27B Q8_0 `-c 262144` q8_0 arm identically (123265 of 262144 cells, 4092.8 MiB resident / 4611.2 MiB spilling). One device, no knob: no KV message at all. Purity unchanged: plain vs a SPILLING windowed arm prefill-logit KLD 0.000000 / 99.990 % (q8_0 KV), greedy text byte-identical on that arm; 35B-A3B (1 GPU and 2-GPU `-sm tensor`), dense 27B and the canonical 27B Q8_0 prefill-logit gate (0.000000 / 100.000 %) byte-identical to r180; MTP Protocol A unchanged (tensor acceptance 0.60816 = 1937/3185, plain == draft-mtp); no GPU faults. ========================================================================== PART 2 -- the ATTENDANCE POOL (Goal B, promoted in r190) ========================================================================== The attention KV lives twice: its AUTHORITATIVE copy in a pinned host MIRROR (cell-indexed, so the writers, state_write/state_read, the K-shift, defrag and seq_park all work on it unchanged -- the writer rule) and a compact DEVICE POOL of pages of one indexer block (compress_ratio cells) with a page table block -> slot and its inverse. A decode step resolves its top-k selection through the table and fills the pages it missed from the mirror; the QSA reader gathers K/V at the pool slots while the mask stays cell-indexed. LLAMA_KV_REGION_POOL=<cells>, unset/0 = off = byte-identical. Contents. - ggml/src/ggml-cuda/kv-pool.{cu,cuh}: GGML_OP_KV_POOL. MARK sets use[slot] = epoch for every page this launch reads AND every page the batch just wrote (the graph's k_idxs), and queues the written ones for re-fill; CLAIM takes a slot for each DISTINCT missing block (the table CAS is the dedupe) and never takes a slot MARK protected; MAP+FILL writes each selected cell's pool position into the reader's K/V id list and copies the claimed and dirty pages from the mirror, K and V sharing slots. The epoch is a device counter incremented once per launch: the graph bakes pointers, never counters, and nothing is allocated per launch. - ggml-cuda.cu: the pool's pinned host mirror buffer type -- a DEVICE buffer type whose allocation is pinned host memory (`ROCm_Host` reports is_host, which would send the KV's writers and the FA read to the CPU on a discrete device), and its proc-address entry. - llama-kv-cache: the eligibility, the per-layer pool tensors (pool_k/pool_v, tbl, inv, use, one shared counter block), the resolve wiring into the QSA id list, kv_pool_serves() (a batch too wide for the pool takes the cell-indexed path), the teardown accounting (LLAMA_KV_POOL_STATS takes a PATH: a line on stderr sits inside the generated text), and memory_breakdown() charging the mirror to the host bucket so `--fit` does not reserve it as VRAM. - llama-memory-hybrid-idx / llama-memory-hybrid / llama-memory: the second id list (the K/V gather follows the page table while the mask stays cell-indexed), the flag threading, and the pool's byte accounting for `--fit` (llama_get_kv_pool_bytes()). - models/qwen4exp.cpp: a pooled cache reports is_streaming() and the sparse arm uses the pool's id list; the MTP draft's own cache is never pooled (its attention is dense). - llama-context / the async state copies: the mirror's buffer type is accepted by the batched save and restore (its bytes are host memory, staged through the pinned state_stage). - common/fit.cpp + src/llama-ext.h: the pool's split in --fit's arithmetic and report (the mirror is pinned host RAM, the pool is VRAM), and no context-reduction interpolation while the pool is active -- the pool's VRAM is fixed, so reducing -c frees nothing and the interpolation would divide by a near-zero bytes-per-context delta. Invariants, each one caught by the greedy text. 1. MARK then CLAIM: a claim must never evict a page the same launch reads. Without MARK the round-robin victim could be a page another row still needs (the text diverged ~400 chars in, and a pool larger than the whole cache hid it completely). 2. Claim ATTEMPTS are not distinct blocks: a slot per id attempt wrapped the cursor within one 4-row batch, so two blocks shared a slot and a just-resolved block went unresident. The table CAS dedupes first, so only distinct blocks consume a slot and kv_pool_serves() bounds the distinct count. 3. No transient scratch in a captured graph: the fill list lived in a ggml_cuda_pool_alloc that is freed at the end of the op, and a captured graph bakes the pointer, so a replay wrote into whatever op had been handed that block ("values verify clean, text differs run to run"). It lives in the counters tensor. 4. The mirror is AUTHORITATIVE: the writers land in it and a declared page is re-filled from it before the attention reads it, so an eviction costs nothing and nothing has to be invalidated -- except by a path that rewrites cells in place without going through the writers (the K-shift, a state restore), which calls kv_pool_invalidate(). 5. Eligibility is narrow on purpose: one stream, non-MLA, K and V both present, !v_trans, a uniform compress_ratio and cell geometry, no window active, a device-offloaded cache, and only the trunk context of a qwen4exp model. Anything else declines with one message and the KV is unchanged. 6. The pool is floored at one decode band's worth of blocks (8 x ceil(width/page) pages) so a verify batch cannot exhaust the slot budget, and the mirror is bounded at creation by LLAMA_KV_SPILL_RAM_PCT (it is pinned, non-swappable RAM) -- over the ceiling the pool is declined loudly instead of being OOM-killed. Measured (Flash-Next GSQ-IQ3_XXS, 1 GPU, -ncmoe 48, q8_0, the PLE flags, arms interleaved in one batch, -n 512, MTP depth 4; t/s and tokens/step): depth (ctx) dense sparse pool (204 MiB) text (-n 64) 5 298 (16 384) 72.09 71.58 71.27 pool == sparse: 332 chars dd1981213373 102 899 (131 072) 59.10 54.70 54.65 (5.3k / 51 475 references; dense differs) 180 035 (196 608) 48.94 43.16 43.41 pool == sparse: 861 chars 263c7f2be4d9 The pool lands ON the sparse ceiling at every depth (+0.5 / +0.6 / +0.58 %), so its placement is free and what remains against a resident KV (-7 % / -11 %) is the sparse decode arm's own indexer cost (block 11), not the KV's storage. A 204 MiB pool replaces the resident attention KV's 1 632 MiB at 103k / 2 448 MiB at 180k, and the freed VRAM goes to the expert arena: 103k plain decode, -n 2000, 23 579.8 -> 25 018.6 MiB (+1 438.8 MiB, +18 slots/table), expert hit 96.26 -> 97.02 %, cold reads 42.0 -> 31.6 GiB. The pool's own cost is 0.10-0.11 ms/token (mark/claim/map+fill) with fills 0.03-0.05 ms/step at 92-99 % hits, which is why a better page policy (LRU / F-LRU / a heat prior) is measured dead at this shape. Full numbers and the three-depth table: ../wip/kv-residency/BA-POOL-DESIGN.md §7-§8. PURITY (the pool). Greedy text pool == the resident sparse arm at 5.3k (332 dd1981213373), 51 475 depth (854 43b30de151b9) and 180k (861 263c7f2be4d9), with the dense arm differing as documented (GREEDY-PURITY §45/§63); LLAMA_KV_POOL_VERIFY=1 0 mismatches on every arm; gate-prefill-logits --ab "LLAMA_KV_REGION_POOL=..." 0.000000 / 100.000 % on the pool arm (base PPL 2.9225, bit-identical to the campaign's own base); gate-park-idle-slots, gate-ckpt-reuse and gate-state-pipe PASS on a pooled cache (the mirror is authoritative, which is what makes them trivial); test-backend-ops -o FLASH_ATTN_QSA pass; no GPU faults; and `--fit` accepts the arms that only fit with the pool (-ncmoe 21/22 at -c 262144: refused without it, accepted with it; -fitp moves 3 264 MiB from the device row to Host). ========================================================================== PART 3 -- a STREAMED cache takes the sparse decode arm (B2) ========================================================================== A cache that is streaming at the depth it reads -- a window the used extent has passed, or a pool -- takes the sparse QSA decode arm; a resident cache keeps the dense one. llama_kv_cache::is_streaming() plus the qwen4exp arm policy, LLAMA_QSA_DENSE_DECODE_STREAM=0 to restore the old behaviour. Measured on a spilled KV (Flash-Next IQ3_XXS, -ncmoe 48, q8_0, 1 GPU, -n 400, 2 reps): +34.3 % at 102 899 depth (23.42 -> 31.43 t/s) and +47.3 % at 180 035 (16.51 -> 24.31); a resident cache byte-identical (853 77a40bf40be1). This is a decode-ARM choice, i.e. a different attention regime (like GREEDY-PURITY §45/§63), so a streamed arm's text differs from the old dense-arm text by construction and a resident arm is the oracle. ========================================================================== DEFAULT OFF, for both placements ========================================================================== Neither knob is a speed feature on a config whose KV fits: the window costs the depth below W (11-26 %) and the pool costs the sparse-vs-dense gap (-7 % at 103k, -11 % at 180k). They are FITTABILITY features -- they turn an OOM into a run and they hand the freed VRAM to the expert arena -- so both are opt-in and both stay byte-identical, including the OOM, with their knobs unset. Do not "fix" the defaults. Goal C (the MTP drafter ring, TODO ggml-org#121) joins the same block -- it is the same claim applied to the draft context, and its default follows the delivery's own rule because it measures positive. `LLAMA_SPEC_DRAFT_WINDOW` gives the MTP draft context a sliding window instead of a `-c`-sized KV: unset or `auto` is the adaptive policy (a quarter of the context, clamped to [32768, 65536] cells), `0` is off (byte-identical to a build without it) and `N` is a cell count. The drafter reads its last few thousand tokens, so a window at or above that is free and one far below it costs 7-9 % of decode; the clamps keep it above that band, and the target verifies every token it proposes, so a truncated draft can only be slower. The ring is the shipped reclaim in `llama_kv_cache::find_slot` (`n_swa`), not a new allocator, and the derived kq mask stays valid -- its predicate compares each cell's POSITION, so a recycled cell reports its new one. The VRAM win needed one more piece: an embedded MTP head has no GGUF of its own, so the slab's draft reserve was the flat 3584 MiB and the freed VRAM never reached the expert arena. For an embedded MTP head with an active window the reserve is now derived from the model's own metadata with the weights zeroed (they are the target's) and the KV sized by the window: aux 3.50 -> 0.76 GiB, i.e. the arena gains ~2.8 GiB. A separate MTP draft GGUF (qwen4exp/Flash-Next) and an un-windowed run keep the flat constant exactly as before, and a declined arena preflight now re-evaluates when the smaller real value arrives instead of latching on the load-time estimate. Measured (1 GPU; one R9700; `-n 2000`/`-n 3000`; static depth 3; interleaved): * 35B-A3B Q8_0 `-ncmoe 48 -c 262144` q8_0 KV, 51 433-token prompt: arena 20 910 -> 23 715 MiB (residency 64.1 -> 72.7 %), decode 111.2 -> 113.7 t/s at `-n 3000` (+2.2 %; +2.8-4.9 % at `-n 2000`), prefill +3.4 %, drafts byte-for-byte the same count (1995/3011) -- the window truncates nothing the drafter used. * dense 27B UD-Q4_K_XL `-c 102400`, MTP Protocol A `-n 3000`, reasoning-pinned: layer 71.9 -> 72.1, tensor 72.6 -> 72.5 (neutral), acceptance 2083/2747 identical in all four arms. * target greedy text byte-identical across off/auto/4096, and plain == draft-mtp == draft-mtp(W=512) at `-c 16384` with a 5256-token prompt and 3000 generated tokens (10 158 chars, sha 99b267e8dc3e), i.e. no wrong answer under constant cell reuse. * gates on a windowed draft: `gate-park-idle-slots.sh` (35B, -ncmoe 48, `-c 65536`: 3 park moves, park == lazyoff), `gate-ckpt-reuse.sh` (4B, `-c 131072`: draft cache 33280 of 131072), `gate-state-pipe.sh` (35B, `-c 65536`: all five arms) -- all PASS with `MTP draft KV window = 32768 cells` in their logs. r194 corner fixes (found by a configuration battery against Flash-Next after r193): * LLAMA_KV_REGION_POOL is capped at the cache's own cell count. =1000000 on a 262144-cell context used to take a 12451 MiB device pool of 250000 pages where only 65536 blocks exist (never claimed, arena -4 GiB); it is now 3264 MiB / 65536 pages, and a small context clamps the same way. * the draft KV window sizes only the reserve of the cache it actually windows. A separate -md MTP head (Flash-Next) keeps its full -c cache, but the reserve was derived with the window: 921 MiB where the honest number is 1566 (kv 217 vs 862) at -c 262144, the under-charge direction. Embedded heads (qwen3.5/3.6/3.8) are unchanged (776 MiB on the 35B). The VRAM cliff at -c 262144 is documented (not code): the 768 MiB default headroom is one hipBLASLt workspace short for the first prefill, GGML_CUDA_SLAB_HEADROOM_MIB=1536 is 3/3 requests clean. Amendment (TODO ggml-org#129's sibling): `-nkvo` declines the window, and the streamed arm keys on the placement. The window is a DEVICE region plus a pinned host tail, but its guard did not test `offload`: with `-nkvo` the per-layer buffer is chosen inside `if (offload)` and stays plain pageable host memory, while the plan block still logged "WINDOWED KV ENABLED", reserved pinned-RAM spill budget and left `kv_resident_cells` set. `is_streaming()` then keyed the streamed (sparse) decode arm on that plan -- qwen4exp consumes it -- for a KV with no region at all. Measured: `-nkvo LLAMA_KV_RESIDENT_CELLS=64` built a plain `CPU KV buffer` of the whole context while announcing a 64-cell VRAM window. The window now declines once, with the reason (the pool already declines on `!offload`), so `-nkvo` means "no streamed placement"; `is_streaming()` tests `kv_region`, the placement actually taken, which also covers a device cache whose region buft the backend refused. Text is unchanged in every arm (the decline is a no-op: `-nkvo` + window already read as `-nkvo` alone). Amendment (issue ggml-org#264): the draft window is PER SEQUENCE, and under `--kv-unified` its cell count is `(win + one batch) x n_seq_max`. A unified cache holds every sequence in ONE stream, so the r193 sizing (`win + n_ubatch` cells) was shared by all of them: once the first sequence had filled its window the tail was all the room left, the tail is where that sequence's own ring writes, and a second sequence's first batch had no contiguous run to be placed in -- `find_slot` refused, and every request on that slot answered `decode() failed: failed to process speculative batch` (HTTP 500) while the drafter ran. Reported on `--kv-unified -np 2` with a 65 536-cell window at `-c 262144` after slot 0 held ~100k tokens; reproduced here with a forced 8192-cell window. A per-stream cache (no `--kv-unified`) already sized each stream separately and is unchanged. `llama_spec_draft_kv_cells()` is now the one geometry function -- the cache (`create_memory`), the slab's draft reserve estimate and the "is a window active" test in `common` all call it, so the reserve can never under-charge an allocation. It grants `win` per sequence plus one placeable batch (`(win + n_ubatch) * n_seq_max`, capped at the context), and DECLINES the window when that does not fit the context per sequence rather than lowering it to `per_seq - n_ubatch`: a window that small saves one batch of cells per sequence and masks the drafter's newest cells to do it. `llama_spec_draft_window_cells()` stays the policy (it is the per-sequence window). n_seq_max == 1 -- every `llama-cli`/`llama-bench` run -- measures exactly what it did (cells 1536 for a 1024-cell window at `-c 8192`), so no single-sequence arm changes at all. Measured (dense 27B, 1 GPU, `-np 2 --kv-unified`): the issue's scenario now answers both slots, and `scripts/gate-spec-draft-window.sh` (new) drives 6 requests over 2 slots with a 1024-cell window -- both rings wrapping, prompts full re-prefilled by swapping them between slots -- with output byte-identical to `LLAMA_SPEC_DRAFT_WINDOW=0` on every step and draft acceptance identical (17/36, 23/23). Greedy text `plain == draft-mtp == draft-mtp(W=1024) == draft-mtp(W=0)` (876 chars, sha 8c8fd395402f) at `-c 16384`. And the reserve now charges a per-STREAM (no `--kv-unified`) draft cache for every stream it allocates: `n_seq_max x` the per-stream cell count. Before, a multi-slot windowed MTP server without `--kv-unified` (35B-A3B `-ncmoe 40 -np 2 -c 8192`, window 1024: 2 x 1536 = 3072 cells allocated, 1536 charged) under-charged the slab's aux reserve by one stream's window -- the direction the reserve header calls dangerous. Measured: 3072 cells reported on both the unified and the per-stream arm now. ========================================================================== PART 4 -- `-sm tensor`: the window across a split (r204, `TODO` ggml-org#124) ========================================================================== A Meta (tensor-split) device carries no backend reg, so the r181 answer was "not provided" and the window was declined on every split. `TODO` ggml-org#124 designed the fix on a one-GPU box (`archive/work/kv-residency/ A6-TENSOR-SPLIT-WINDOW.md`, changes C1-C5); it is implemented and measured here, on a 3x R9700 host, and the decline is gone. * `ggml_backend_meta_kv_region_buft / _is_kv_buft / _grow` (new, `ggml-backend.h`): the Meta buffer type over the per-child region buffer types (ALL children or nothing), the is-a-region predicate `--fit` needs (the CUDA predicate is an identity on the child's `alloc_buffer` and cannot answer for a Meta buffer type), and a grow that fans out to every child. A child that cannot be reached is a REFUSAL (-1), never the 0 the CUDA hook returns for "not a region buffer": for a Meta buffer that 0 was a silent success on unmapped VA, i.e. a batch that page-faults the GPU. * `llama_kv_cache` resolves capability, the buffer type, the spill ceiling and the link through the Meta side; a MIRRORED cache (dsv4 / HRM, `llama_model::kv_cache_split_mirrored()`) declines the window with its own message, because every device holds the whole cache there (`n_devices x W x cell_bytes`) and the pinned-spill plan is per logical cache. * `common/fit.cpp` decides the window inside the tensor-split branch: charged at its PHYSICAL `W x cell_bytes` (what all devices commit together) against `min_i(target_i / ratio_i)`, which makes the aggregate check imply every device's (the loader shards the KV along the KV-head axis by the same ratio it shards the weights), and the Meta entry's margin is now the SUM of the children's `--fit-target`s (it was child 0's, so `(n_devices - 1) x target` silently vanished from the budget). The corrected KV term applies ONLY where a window is asked for: a run without `LLAMA_KV_RESIDENT_CELLS` keeps this branch's old arithmetic exactly, so the split's pre-existing `n_devices x` KV over-count is untouched outside the window arm. Four defects the arms found, fixed in the same block: 1. the init-time window commit was rounded up to a whole map unit past the tensor's own extent, and on a split each child is its own VA reservation -- the last tensor's inflated window was refused (`the KV window (4.00 MiB) could not be committed in VRAM on device 1`). Clamped to the region's END, in whole units (clamping to the tensor's own extent was tried first and is wrong: it leaves a short mapping off the unit grid and the next slide refuses to flip). 2. `ensure_span` refused a request that covered several WHOLE mappings; one batch can advance the boundary by more than one unit, and a 1 MiB unit is floored to the driver's 2 MiB granularity, so the request covered two mappings and aborted the batch. Whole mappings now flip one at a time; a request that covers a mapping only in PART is still refused (that loses bytes on this driver). 3. the batched state save issued a 2-D D2H per device and `hipMemcpy2DAsync` fails (`invalid argument`) when the range begins in a spilled region's pinned host mapping (the tensor-split checkpoint save aborted: `cache_k_l64 (view)`, 1024 B x 4782 rows). The region-backed directions of `get/set_tensor_2d_async` now go through the region buffer's own copy, ordered behind the compute stream like the pool mirror (a blocking default-stream copy does not wait for it, and the state saved mid-batch is torn). 4. that fallback's "contiguous rows = one copy" shortcut ignored the caller's destination pitch, which for a split splice is the FULL row, wider than one device's slice: the state-pipe gate failed on every cycle of all four async arms until a tight block required BOTH pitches to equal the width. Verified (gfx1201, `ROCBLAS_USE_HIPBLASLT=0` for every fresh-process pair): text byte-identical on `win3 == ref3` (3 devices, 4B, `057ea27b1009`) and `win2 == ref2 == win2mtp == ref2mtp` (2 devices, 27B, a 5246-token prompt, `7a7430617465`; draft acceptance 0.46154 in both MTP arms), also at a 1 MiB map unit; the spill is real on EVERY device (32 mapping flips each at 4 MiB, 128 at 1 MiB); a `-c 1048576` 2-device split (64 GiB of f16 KV) runs only because of the window; the single-device and `-nkvo` arms are unchanged; `--fit` on the split reports a WINDOWED cache and keeps the pinned `-c 524288` (plus the pinned-RAM ceiling's widen and drop arms, and `LLAMA_KV_REGION=0` silent); coherence identical to the r203 build on four no-window arms (3-GPU 4B, 2-GPU and 1-GPU 27B, 2-GPU host-expert 35B-A3B); prefill-logit 0.000000 / 100.000 %; Protocol A four-axis R/P/C/K 1.91x / 2.43x / 2.58x / 2.74x (acceptance 0.5869 / 0.8391 / 0.9112 / 0.9920, the r90 shape); `gate-spec-draft-window.sh` 6/6; `gate-state-pipe.sh` 2-GPU `-sm tensor` PASS with and without the window (the windowed arm failed before (3) and (4)); `GGML_CUDA_VMM_REGION_SELFTEST=1` PASS with a new multi-mapping arm; per-block build 1/1; `validate-set.sh` strict 16/16. Gate: `scripts/gate-kv-window-split.sh`. Record: `benchmarks/2026-11-01-kv-window-tensor-split-124.md`.
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Nov 4, 2026
…W (Goal A) and an attendance POOL (Goal B), both opt-in Goals A and B of TODO ggml-org#118, promoted from the `wip/kv-residency` campaign. This block is the delivery's "the KV does not have to be O(-c) of VRAM" work: TWO opt-in placements of the same cache, and each one is byte-identical to a build without it when its knob is unset. * the WINDOW (`LLAMA_KV_RESIDENT_CELLS=<cells>|auto`): the newest W cells stay in VRAM, everything older spills to pinned system RAM in the SAME VA reservation -- a positional window, no kernel or op change; * the POOL (`LLAMA_KV_REGION_POOL=<cells>`): the authoritative copy of the WHOLE context in a pinned host mirror, and a compact device pool of the pages a decode step actually attends to, which the QSA sparse read resolves through a page table (`GGML_OP_KV_POOL`). They are mutually exclusive by construction (the pool declines while a window is active) and they answer the same question from opposite ends: the window keeps the *newest* cells hot, the pool keeps the *attended* cells hot. Both report `is_streaming()`, so a streamed cache takes the sparse QSA decode arm (B2, below). ========================================================================== PART 1 -- the WINDOW (Goal A, promoted in r178) ========================================================================== Goal A of TODO ggml-org#118, promoted from the `wip/kv-residency` campaign. WHAT IT DOES. The KV cache's VRAM cost becomes a WINDOW of the newest `W` cells instead of `-c` cells: one VA reservation (a CUDA/HIP VMM region) holds the whole cache, the window's cells are backed by VRAM and everything below them by pinned system RAM. `set_rows`, the in-place rope shift, `state_write/read`, the kq mask and the FA kernels keep addressing one contiguous range, so no kernel and no op changes. The window slides with the watermark in whole map units, so a remap happens once per few thousand tokens and the apparatus itself is free (a zero-spill arm measures the same as plain). WHY. (a) A context that OOMs today runs: 27B Q8_0 `-c 262144` (8704 MiB of KV) now runs on one 32 GiB card at 128 MiB VRAM + 8576 MiB pinned host for the KV. (b) With host-resident MoE experts, the VRAM the KV does not need *yet* goes to the expert-cache arena: measured at `-c 262144`, `-n 2000`, `-ncmoe` = the model's full layer count, 51 433-token prompt, W at or above the run's depth = **+2.2 to +2.9 GiB of arena** (+3.9 to +6.7 points of residency) for free -- 122B-A10B Q4_K_XL +3.8 % decode and +4.7 % prefill, 35B-A3B Q8_0 -0.9 % decode and +3 % prefill; a `W` 35 k cells BELOW the run depth costs 11-26 % (the spill is read every token). OPT-IN, AND ONLY WHEN ASKED FOR. `LLAMA_KV_RESIDENT_CELLS=<cells>` (a number) or `=auto` (`--fit` sizes it, and only spills a context the user pinned with `-c`); unset/0 = no window. With no window the KV takes the PLAIN device buffer, so a run without the knob is byte-identical to a build without this block -- including its OOM (verified). `LLAMA_KV_SPILL_RAM_PCT` (85 % of MemAvailable) caps the pinned spill and widens the window rather than being OOM-killed; `LLAMA_KV_REGION=0` disables the provider; `LLAMA_KV_REGION_QUARANTINE=0` and `LLAMA_KV_REGION_DEBUG/TRACE/CANARY/DUMP` are the diagnosis switches. PURITY (the window). A spilled KV is numerically transparent: prefill-logit **KLD -0.000000 / 100.000 %** on a spilling 27B arm and -0.000000 / 99.994 % on a spilling Flash-Next (two KV caches: the attention KV and the QSA indexer), text byte-identical on 27B (f16 and q8_0), 4B, 35B-A3B and Flash-Next, and the state paths, the context-checkpoint path and the MTP verify widths all green on arms that provably spill. Two driver hazards are held: a kind flip zeroes a neighbouring live host mapping unless the released physical is held across the create (`LLAMA_KV_REGION_QUARANTINE`, default on -- `=0` reproduces the corruption), and every tensor in a windowed region is placed on the driver's map granularity so a slide step coincides with a mapping. An idle-slot park is REFUSED on a region-backed cache (the server then saves the slot to the prompt cache and clears it, which is byte-identical to the parking gate's reference) because a park moves cells above the region's mapped watermark through the copy engine, which faults the GPU. FIT. `--fit` sizes and reports the window (`auto`), or honours and reports a numeric `W`: the resident/spill split, the VRAM saved, and the per-token read cost at the model's full context from the backend's calibrated link rate. The fit identifies the KV's bytes by the region buffer TYPE, and its measurement context is a `no_alloc` probe that declines a window -- so the probe takes the region buffer explicitly (`llama_kv_region_set_probe`); without that the fit cannot see the KV, reports an over-budget config and aborts instead of sizing the window (the r178 regression). GATES (1 GPU, gfx1201): default path byte-identical (`5ba44647188f`) and still OOMs; VMM selftest PASS and FAIL with the hold disabled; windowed arms 305 `e2cea6fa6670` = plain at W=1024/2048/4096 (spilling at 1024: 128 MiB host), `QUARANTINE=0` -> 325 `fb65430049e9` (the hazard); `--fit` sizes `auto` (96680 of 262144 cells, 3210 MiB resident) and reports a numeric W; `gate-ckpt-reuse.sh` / `gate-state-pipe.sh` / MTP verify widths on spilling arms; `test-backend-ops -o FLASH_ATTN_QSA` 26/26; `check-gpu-faults.sh` clean. Not in this block: the campaign's Goal B (a sparse attended set) and Goal C (the MTP drafter ring, `LLAMA_SPEC_DRAFT_WINDOW`) -- both remain campaign work -- and A1 (the superseded two-base FA read). Records: `wip/kv-residency/A2-MIXED-BACKING.md` (§3.7.9, §3.7.11), `HANDOVER.md`. MULTI-DEVICE `--fit` (r181; the window itself reaches a tensor split in r204, at the end of this message): the KV-region glue is now safe on a Meta (tensor-split) device, and `auto`'s decision reaches the cache as a decision. r178 made default `--fit` abort on ANY `-sm tensor` run with more than one device: the fit's KV probes and the cache's own region lookups call `ggml_backend_dev_backend_reg(dev)` and hand it to `ggml_backend_reg_get_proc_address`, and a Meta device has no backend reg (`device->reg == NULL`), so `GGML_ASSERT(reg)` fired at model load. Three paths asserted: the fit probe (any run), the runtime buft lookup (a numeric W), and the spill budget/link lookups (a numeric W below `-c`). r181 makes a null reg read as "not provided" and declines the window with one message naming the tensor split (fit and cache), keeping the KV fully resident -- which is the r181 state; r204, below, is what makes the backend answer there. Three wiring defects in the same code, all visible on ONE device: - `auto`'s "no window needed" decision (0) was indistinguishable from "nobody decided", so the cache warned "--fit did not run" immediately after the fit had decided exactly that. `llama_kv_region_set_resident_cells` now records that a decision was made (`llama_kv_region_resident_cells_decided`), and a decided 0 is silent. - every run without the knob logged "the windowed KV is unavailable for this cache (no spilled cells)". That message now only fires when a window was actually requested and declined for a real reason. - the pinned-RAM ceiling clamp could raise W past the VRAM budget and then be reported as "does not make this fit either". It is now only taken while the wider window still meets the VRAM target; otherwise the fit says the ceiling cannot be served at this `-c` and drops the window (which the fit then fits by reducing the context). That ordering is not cosmetic: an intermediate form of this fix accepted a 235 GiB pinned spill plan for a 4B at `-c 8388608`, and creating it OOM-killed the test box. GATES (the window, gfx1201): `--fit on` (default) at 2 and 3 devices, `-sm tensor`, with no knob / a numeric W / `auto`, fit on and off: no assert, tokens produced, exactly one message per requested window. `-sm layer` 2 devices and 1 GPU still take the window per device (numeric W), and `auto` still sizes the 27B Q8_0 `-c 262144` q8_0 arm identically (123265 of 262144 cells, 4092.8 MiB resident / 4611.2 MiB spilling). One device, no knob: no KV message at all. Purity unchanged: plain vs a SPILLING windowed arm prefill-logit KLD 0.000000 / 99.990 % (q8_0 KV), greedy text byte-identical on that arm; 35B-A3B (1 GPU and 2-GPU `-sm tensor`), dense 27B and the canonical 27B Q8_0 prefill-logit gate (0.000000 / 100.000 %) byte-identical to r180; MTP Protocol A unchanged (tensor acceptance 0.60816 = 1937/3185, plain == draft-mtp); no GPU faults. ========================================================================== PART 2 -- the ATTENDANCE POOL (Goal B, promoted in r190) ========================================================================== The attention KV lives twice: its AUTHORITATIVE copy in a pinned host MIRROR (cell-indexed, so the writers, state_write/state_read, the K-shift, defrag and seq_park all work on it unchanged -- the writer rule) and a compact DEVICE POOL of pages of one indexer block (compress_ratio cells) with a page table block -> slot and its inverse. A decode step resolves its top-k selection through the table and fills the pages it missed from the mirror; the QSA reader gathers K/V at the pool slots while the mask stays cell-indexed. LLAMA_KV_REGION_POOL=<cells>, unset/0 = off = byte-identical. Contents. - ggml/src/ggml-cuda/kv-pool.{cu,cuh}: GGML_OP_KV_POOL. MARK sets use[slot] = epoch for every page this launch reads AND every page the batch just wrote (the graph's k_idxs), and queues the written ones for re-fill; CLAIM takes a slot for each DISTINCT missing block (the table CAS is the dedupe) and never takes a slot MARK protected; MAP+FILL writes each selected cell's pool position into the reader's K/V id list and copies the claimed and dirty pages from the mirror, K and V sharing slots. The epoch is a device counter incremented once per launch: the graph bakes pointers, never counters, and nothing is allocated per launch. - ggml-cuda.cu: the pool's pinned host mirror buffer type -- a DEVICE buffer type whose allocation is pinned host memory (`ROCm_Host` reports is_host, which would send the KV's writers and the FA read to the CPU on a discrete device), and its proc-address entry. - llama-kv-cache: the eligibility, the per-layer pool tensors (pool_k/pool_v, tbl, inv, use, one shared counter block), the resolve wiring into the QSA id list, kv_pool_serves() (a batch too wide for the pool takes the cell-indexed path), the teardown accounting (LLAMA_KV_POOL_STATS takes a PATH: a line on stderr sits inside the generated text), and memory_breakdown() charging the mirror to the host bucket so `--fit` does not reserve it as VRAM. - llama-memory-hybrid-idx / llama-memory-hybrid / llama-memory: the second id list (the K/V gather follows the page table while the mask stays cell-indexed), the flag threading, and the pool's byte accounting for `--fit` (llama_get_kv_pool_bytes()). - models/qwen4exp.cpp: a pooled cache reports is_streaming() and the sparse arm uses the pool's id list; the MTP draft's own cache is never pooled (its attention is dense). - llama-context / the async state copies: the mirror's buffer type is accepted by the batched save and restore (its bytes are host memory, staged through the pinned state_stage). - common/fit.cpp + src/llama-ext.h: the pool's split in --fit's arithmetic and report (the mirror is pinned host RAM, the pool is VRAM), and no context-reduction interpolation while the pool is active -- the pool's VRAM is fixed, so reducing -c frees nothing and the interpolation would divide by a near-zero bytes-per-context delta. Invariants, each one caught by the greedy text. 1. MARK then CLAIM: a claim must never evict a page the same launch reads. Without MARK the round-robin victim could be a page another row still needs (the text diverged ~400 chars in, and a pool larger than the whole cache hid it completely). 2. Claim ATTEMPTS are not distinct blocks: a slot per id attempt wrapped the cursor within one 4-row batch, so two blocks shared a slot and a just-resolved block went unresident. The table CAS dedupes first, so only distinct blocks consume a slot and kv_pool_serves() bounds the distinct count. 3. No transient scratch in a captured graph: the fill list lived in a ggml_cuda_pool_alloc that is freed at the end of the op, and a captured graph bakes the pointer, so a replay wrote into whatever op had been handed that block ("values verify clean, text differs run to run"). It lives in the counters tensor. 4. The mirror is AUTHORITATIVE: the writers land in it and a declared page is re-filled from it before the attention reads it, so an eviction costs nothing and nothing has to be invalidated -- except by a path that rewrites cells in place without going through the writers (the K-shift, a state restore), which calls kv_pool_invalidate(). 5. Eligibility is narrow on purpose: one stream, non-MLA, K and V both present, !v_trans, a uniform compress_ratio and cell geometry, no window active, a device-offloaded cache, and only the trunk context of a qwen4exp model. Anything else declines with one message and the KV is unchanged. 6. The pool is floored at one decode band's worth of blocks (8 x ceil(width/page) pages) so a verify batch cannot exhaust the slot budget, and the mirror is bounded at creation by LLAMA_KV_SPILL_RAM_PCT (it is pinned, non-swappable RAM) -- over the ceiling the pool is declined loudly instead of being OOM-killed. Measured (Flash-Next GSQ-IQ3_XXS, 1 GPU, -ncmoe 48, q8_0, the PLE flags, arms interleaved in one batch, -n 512, MTP depth 4; t/s and tokens/step): depth (ctx) dense sparse pool (204 MiB) text (-n 64) 5 298 (16 384) 72.09 71.58 71.27 pool == sparse: 332 chars dd1981213373 102 899 (131 072) 59.10 54.70 54.65 (5.3k / 51 475 references; dense differs) 180 035 (196 608) 48.94 43.16 43.41 pool == sparse: 861 chars 263c7f2be4d9 The pool lands ON the sparse ceiling at every depth (+0.5 / +0.6 / +0.58 %), so its placement is free and what remains against a resident KV (-7 % / -11 %) is the sparse decode arm's own indexer cost (block 11), not the KV's storage. A 204 MiB pool replaces the resident attention KV's 1 632 MiB at 103k / 2 448 MiB at 180k, and the freed VRAM goes to the expert arena: 103k plain decode, -n 2000, 23 579.8 -> 25 018.6 MiB (+1 438.8 MiB, +18 slots/table), expert hit 96.26 -> 97.02 %, cold reads 42.0 -> 31.6 GiB. The pool's own cost is 0.10-0.11 ms/token (mark/claim/map+fill) with fills 0.03-0.05 ms/step at 92-99 % hits, which is why a better page policy (LRU / F-LRU / a heat prior) is measured dead at this shape. Full numbers and the three-depth table: ../wip/kv-residency/BA-POOL-DESIGN.md §7-§8. PURITY (the pool). Greedy text pool == the resident sparse arm at 5.3k (332 dd1981213373), 51 475 depth (854 43b30de151b9) and 180k (861 263c7f2be4d9), with the dense arm differing as documented (GREEDY-PURITY §45/§63); LLAMA_KV_POOL_VERIFY=1 0 mismatches on every arm; gate-prefill-logits --ab "LLAMA_KV_REGION_POOL=..." 0.000000 / 100.000 % on the pool arm (base PPL 2.9225, bit-identical to the campaign's own base); gate-park-idle-slots, gate-ckpt-reuse and gate-state-pipe PASS on a pooled cache (the mirror is authoritative, which is what makes them trivial); test-backend-ops -o FLASH_ATTN_QSA pass; no GPU faults; and `--fit` accepts the arms that only fit with the pool (-ncmoe 21/22 at -c 262144: refused without it, accepted with it; -fitp moves 3 264 MiB from the device row to Host). ========================================================================== PART 3 -- a STREAMED cache takes the sparse decode arm (B2) ========================================================================== A cache that is streaming at the depth it reads -- a window the used extent has passed, or a pool -- takes the sparse QSA decode arm; a resident cache keeps the dense one. llama_kv_cache::is_streaming() plus the qwen4exp arm policy, LLAMA_QSA_DENSE_DECODE_STREAM=0 to restore the old behaviour. Measured on a spilled KV (Flash-Next IQ3_XXS, -ncmoe 48, q8_0, 1 GPU, -n 400, 2 reps): +34.3 % at 102 899 depth (23.42 -> 31.43 t/s) and +47.3 % at 180 035 (16.51 -> 24.31); a resident cache byte-identical (853 77a40bf40be1). This is a decode-ARM choice, i.e. a different attention regime (like GREEDY-PURITY §45/§63), so a streamed arm's text differs from the old dense-arm text by construction and a resident arm is the oracle. ========================================================================== DEFAULT OFF, for both placements ========================================================================== Neither knob is a speed feature on a config whose KV fits: the window costs the depth below W (11-26 %) and the pool costs the sparse-vs-dense gap (-7 % at 103k, -11 % at 180k). They are FITTABILITY features -- they turn an OOM into a run and they hand the freed VRAM to the expert arena -- so both are opt-in and both stay byte-identical, including the OOM, with their knobs unset. Do not "fix" the defaults. Goal C (the MTP drafter ring, TODO ggml-org#121) joins the same block -- it is the same claim applied to the draft context, and its default follows the delivery's own rule because it measures positive. `LLAMA_SPEC_DRAFT_WINDOW` gives the MTP draft context a sliding window instead of a `-c`-sized KV: unset or `auto` is the adaptive policy (a quarter of the context, clamped to [32768, 65536] cells), `0` is off (byte-identical to a build without it) and `N` is a cell count. The drafter reads its last few thousand tokens, so a window at or above that is free and one far below it costs 7-9 % of decode; the clamps keep it above that band, and the target verifies every token it proposes, so a truncated draft can only be slower. The ring is the shipped reclaim in `llama_kv_cache::find_slot` (`n_swa`), not a new allocator, and the derived kq mask stays valid -- its predicate compares each cell's POSITION, so a recycled cell reports its new one. The VRAM win needed one more piece: an embedded MTP head has no GGUF of its own, so the slab's draft reserve was the flat 3584 MiB and the freed VRAM never reached the expert arena. For an embedded MTP head with an active window the reserve is now derived from the model's own metadata with the weights zeroed (they are the target's) and the KV sized by the window: aux 3.50 -> 0.76 GiB, i.e. the arena gains ~2.8 GiB. A separate MTP draft GGUF (qwen4exp/Flash-Next) and an un-windowed run keep the flat constant exactly as before, and a declined arena preflight now re-evaluates when the smaller real value arrives instead of latching on the load-time estimate. Measured (1 GPU; one R9700; `-n 2000`/`-n 3000`; static depth 3; interleaved): * 35B-A3B Q8_0 `-ncmoe 48 -c 262144` q8_0 KV, 51 433-token prompt: arena 20 910 -> 23 715 MiB (residency 64.1 -> 72.7 %), decode 111.2 -> 113.7 t/s at `-n 3000` (+2.2 %; +2.8-4.9 % at `-n 2000`), prefill +3.4 %, drafts byte-for-byte the same count (1995/3011) -- the window truncates nothing the drafter used. * dense 27B UD-Q4_K_XL `-c 102400`, MTP Protocol A `-n 3000`, reasoning-pinned: layer 71.9 -> 72.1, tensor 72.6 -> 72.5 (neutral), acceptance 2083/2747 identical in all four arms. * target greedy text byte-identical across off/auto/4096, and plain == draft-mtp == draft-mtp(W=512) at `-c 16384` with a 5256-token prompt and 3000 generated tokens (10 158 chars, sha 99b267e8dc3e), i.e. no wrong answer under constant cell reuse. * gates on a windowed draft: `gate-park-idle-slots.sh` (35B, -ncmoe 48, `-c 65536`: 3 park moves, park == lazyoff), `gate-ckpt-reuse.sh` (4B, `-c 131072`: draft cache 33280 of 131072), `gate-state-pipe.sh` (35B, `-c 65536`: all five arms) -- all PASS with `MTP draft KV window = 32768 cells` in their logs. r194 corner fixes (found by a configuration battery against Flash-Next after r193): * LLAMA_KV_REGION_POOL is capped at the cache's own cell count. =1000000 on a 262144-cell context used to take a 12451 MiB device pool of 250000 pages where only 65536 blocks exist (never claimed, arena -4 GiB); it is now 3264 MiB / 65536 pages, and a small context clamps the same way. * the draft KV window sizes only the reserve of the cache it actually windows. A separate -md MTP head (Flash-Next) keeps its full -c cache, but the reserve was derived with the window: 921 MiB where the honest number is 1566 (kv 217 vs 862) at -c 262144, the under-charge direction. Embedded heads (qwen3.5/3.6/3.8) are unchanged (776 MiB on the 35B). The VRAM cliff at -c 262144 is documented (not code): the 768 MiB default headroom is one hipBLASLt workspace short for the first prefill, GGML_CUDA_SLAB_HEADROOM_MIB=1536 is 3/3 requests clean. Amendment (TODO ggml-org#129's sibling): `-nkvo` declines the window, and the streamed arm keys on the placement. The window is a DEVICE region plus a pinned host tail, but its guard did not test `offload`: with `-nkvo` the per-layer buffer is chosen inside `if (offload)` and stays plain pageable host memory, while the plan block still logged "WINDOWED KV ENABLED", reserved pinned-RAM spill budget and left `kv_resident_cells` set. `is_streaming()` then keyed the streamed (sparse) decode arm on that plan -- qwen4exp consumes it -- for a KV with no region at all. Measured: `-nkvo LLAMA_KV_RESIDENT_CELLS=64` built a plain `CPU KV buffer` of the whole context while announcing a 64-cell VRAM window. The window now declines once, with the reason (the pool already declines on `!offload`), so `-nkvo` means "no streamed placement"; `is_streaming()` tests `kv_region`, the placement actually taken, which also covers a device cache whose region buft the backend refused. Text is unchanged in every arm (the decline is a no-op: `-nkvo` + window already read as `-nkvo` alone). Amendment (issue ggml-org#264): the draft window is PER SEQUENCE, and under `--kv-unified` its cell count is `(win + one batch) x n_seq_max`. A unified cache holds every sequence in ONE stream, so the r193 sizing (`win + n_ubatch` cells) was shared by all of them: once the first sequence had filled its window the tail was all the room left, the tail is where that sequence's own ring writes, and a second sequence's first batch had no contiguous run to be placed in -- `find_slot` refused, and every request on that slot answered `decode() failed: failed to process speculative batch` (HTTP 500) while the drafter ran. Reported on `--kv-unified -np 2` with a 65 536-cell window at `-c 262144` after slot 0 held ~100k tokens; reproduced here with a forced 8192-cell window. A per-stream cache (no `--kv-unified`) already sized each stream separately and is unchanged. `llama_spec_draft_kv_cells()` is now the one geometry function -- the cache (`create_memory`), the slab's draft reserve estimate and the "is a window active" test in `common` all call it, so the reserve can never under-charge an allocation. It grants `win` per sequence plus one placeable batch (`(win + n_ubatch) * n_seq_max`, capped at the context), and DECLINES the window when that does not fit the context per sequence rather than lowering it to `per_seq - n_ubatch`: a window that small saves one batch of cells per sequence and masks the drafter's newest cells to do it. `llama_spec_draft_window_cells()` stays the policy (it is the per-sequence window). n_seq_max == 1 -- every `llama-cli`/`llama-bench` run -- measures exactly what it did (cells 1536 for a 1024-cell window at `-c 8192`), so no single-sequence arm changes at all. Measured (dense 27B, 1 GPU, `-np 2 --kv-unified`): the issue's scenario now answers both slots, and `scripts/gate-spec-draft-window.sh` (new) drives 6 requests over 2 slots with a 1024-cell window -- both rings wrapping, prompts full re-prefilled by swapping them between slots -- with output byte-identical to `LLAMA_SPEC_DRAFT_WINDOW=0` on every step and draft acceptance identical (17/36, 23/23). Greedy text `plain == draft-mtp == draft-mtp(W=1024) == draft-mtp(W=0)` (876 chars, sha 8c8fd395402f) at `-c 16384`. And the reserve now charges a per-STREAM (no `--kv-unified`) draft cache for every stream it allocates: `n_seq_max x` the per-stream cell count. Before, a multi-slot windowed MTP server without `--kv-unified` (35B-A3B `-ncmoe 40 -np 2 -c 8192`, window 1024: 2 x 1536 = 3072 cells allocated, 1536 charged) under-charged the slab's aux reserve by one stream's window -- the direction the reserve header calls dangerous. Measured: 3072 cells reported on both the unified and the per-stream arm now. ========================================================================== PART 4 -- `-sm tensor`: the window across a split (r204, `TODO` ggml-org#124) ========================================================================== A Meta (tensor-split) device carries no backend reg, so the r181 answer was "not provided" and the window was declined on every split. `TODO` ggml-org#124 designed the fix on a one-GPU box (`archive/work/kv-residency/ A6-TENSOR-SPLIT-WINDOW.md`, changes C1-C5); it is implemented and measured here, on a 3x R9700 host, and the decline is gone. * `ggml_backend_meta_kv_region_buft / _is_kv_buft / _grow` (new, `ggml-backend.h`): the Meta buffer type over the per-child region buffer types (ALL children or nothing), the is-a-region predicate `--fit` needs (the CUDA predicate is an identity on the child's `alloc_buffer` and cannot answer for a Meta buffer type), and a grow that fans out to every child. A child that cannot be reached is a REFUSAL (-1), never the 0 the CUDA hook returns for "not a region buffer": for a Meta buffer that 0 was a silent success on unmapped VA, i.e. a batch that page-faults the GPU. * `llama_kv_cache` resolves capability, the buffer type, the spill ceiling and the link through the Meta side; a MIRRORED cache (dsv4 / HRM, `llama_model::kv_cache_split_mirrored()`) declines the window with its own message, because every device holds the whole cache there (`n_devices x W x cell_bytes`) and the pinned-spill plan is per logical cache. * `common/fit.cpp` decides the window inside the tensor-split branch: charged at its PHYSICAL `W x cell_bytes` (what all devices commit together) against `min_i(target_i / ratio_i)`, which makes the aggregate check imply every device's (the loader shards the KV along the KV-head axis by the same ratio it shards the weights), and the Meta entry's margin is now the SUM of the children's `--fit-target`s (it was child 0's, so `(n_devices - 1) x target` silently vanished from the budget). The corrected KV term applies ONLY where a window is asked for: a run without `LLAMA_KV_RESIDENT_CELLS` keeps this branch's old arithmetic exactly, so the split's pre-existing `n_devices x` KV over-count is untouched outside the window arm. Four defects the arms found, fixed in the same block: 1. the init-time window commit was rounded up to a whole map unit past the tensor's own extent, and on a split each child is its own VA reservation -- the last tensor's inflated window was refused (`the KV window (4.00 MiB) could not be committed in VRAM on device 1`). Clamped to the region's END, in whole units (clamping to the tensor's own extent was tried first and is wrong: it leaves a short mapping off the unit grid and the next slide refuses to flip). 2. `ensure_span` refused a request that covered several WHOLE mappings; one batch can advance the boundary by more than one unit, and a 1 MiB unit is floored to the driver's 2 MiB granularity, so the request covered two mappings and aborted the batch. Whole mappings now flip one at a time; a request that covers a mapping only in PART is still refused (that loses bytes on this driver). 3. the batched state save issued a 2-D D2H per device and `hipMemcpy2DAsync` fails (`invalid argument`) when the range begins in a spilled region's pinned host mapping (the tensor-split checkpoint save aborted: `cache_k_l64 (view)`, 1024 B x 4782 rows). The region-backed directions of `get/set_tensor_2d_async` now go through the region buffer's own copy, ordered behind the compute stream like the pool mirror (a blocking default-stream copy does not wait for it, and the state saved mid-batch is torn). 4. that fallback's "contiguous rows = one copy" shortcut ignored the caller's destination pitch, which for a split splice is the FULL row, wider than one device's slice: the state-pipe gate failed on every cycle of all four async arms until a tight block required BOTH pitches to equal the width. Verified (gfx1201, `ROCBLAS_USE_HIPBLASLT=0` for every fresh-process pair): text byte-identical on `win3 == ref3` (3 devices, 4B, `057ea27b1009`) and `win2 == ref2 == win2mtp == ref2mtp` (2 devices, 27B, a 5246-token prompt, `7a7430617465`; draft acceptance 0.46154 in both MTP arms), also at a 1 MiB map unit; the spill is real on EVERY device (32 mapping flips each at 4 MiB, 128 at 1 MiB); a `-c 1048576` 2-device split (64 GiB of f16 KV) runs only because of the window; the single-device and `-nkvo` arms are unchanged; `--fit` on the split reports a WINDOWED cache and keeps the pinned `-c 524288` (plus the pinned-RAM ceiling's widen and drop arms, and `LLAMA_KV_REGION=0` silent); coherence identical to the r203 build on four no-window arms (3-GPU 4B, 2-GPU and 1-GPU 27B, 2-GPU host-expert 35B-A3B); prefill-logit 0.000000 / 100.000 %; Protocol A four-axis R/P/C/K 1.91x / 2.43x / 2.58x / 2.74x (acceptance 0.5869 / 0.8391 / 0.9112 / 0.9920, the r90 shape); `gate-spec-draft-window.sh` 6/6; `gate-state-pipe.sh` 2-GPU `-sm tensor` PASS with and without the window (the windowed arm failed before (3) and (4)); `GGML_CUDA_VMM_REGION_SELFTEST=1` PASS with a new multi-mapping arm; per-block build 1/1; `validate-set.sh` strict 16/16. Gate: `scripts/gate-kv-window-split.sh`. Record: `benchmarks/2026-11-01-kv-window-tensor-split-124.md`.
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Nov 4, 2026
…W (Goal A) and an attendance POOL (Goal B), both opt-in Goals A and B of TODO ggml-org#118, promoted from the `wip/kv-residency` campaign. This block is the delivery's "the KV does not have to be O(-c) of VRAM" work: TWO opt-in placements of the same cache, and each one is byte-identical to a build without it when its knob is unset. * the WINDOW (`LLAMA_KV_RESIDENT_CELLS=<cells>|auto`): the newest W cells stay in VRAM, everything older spills to pinned system RAM in the SAME VA reservation -- a positional window, no kernel or op change; * the POOL (`LLAMA_KV_REGION_POOL=<cells>`): the authoritative copy of the WHOLE context in a pinned host mirror, and a compact device pool of the pages a decode step actually attends to, which the QSA sparse read resolves through a page table (`GGML_OP_KV_POOL`). They are mutually exclusive by construction (the pool declines while a window is active) and they answer the same question from opposite ends: the window keeps the *newest* cells hot, the pool keeps the *attended* cells hot. Both report `is_streaming()`, so a streamed cache takes the sparse QSA decode arm (B2, below). ========================================================================== PART 1 -- the WINDOW (Goal A, promoted in r178) ========================================================================== Goal A of TODO ggml-org#118, promoted from the `wip/kv-residency` campaign. WHAT IT DOES. The KV cache's VRAM cost becomes a WINDOW of the newest `W` cells instead of `-c` cells: one VA reservation (a CUDA/HIP VMM region) holds the whole cache, the window's cells are backed by VRAM and everything below them by pinned system RAM. `set_rows`, the in-place rope shift, `state_write/read`, the kq mask and the FA kernels keep addressing one contiguous range, so no kernel and no op changes. The window slides with the watermark in whole map units, so a remap happens once per few thousand tokens and the apparatus itself is free (a zero-spill arm measures the same as plain). WHY. (a) A context that OOMs today runs: 27B Q8_0 `-c 262144` (8704 MiB of KV) now runs on one 32 GiB card at 128 MiB VRAM + 8576 MiB pinned host for the KV. (b) With host-resident MoE experts, the VRAM the KV does not need *yet* goes to the expert-cache arena: measured at `-c 262144`, `-n 2000`, `-ncmoe` = the model's full layer count, 51 433-token prompt, W at or above the run's depth = **+2.2 to +2.9 GiB of arena** (+3.9 to +6.7 points of residency) for free -- 122B-A10B Q4_K_XL +3.8 % decode and +4.7 % prefill, 35B-A3B Q8_0 -0.9 % decode and +3 % prefill; a `W` 35 k cells BELOW the run depth costs 11-26 % (the spill is read every token). OPT-IN, AND ONLY WHEN ASKED FOR. `LLAMA_KV_RESIDENT_CELLS=<cells>` (a number) or `=auto` (`--fit` sizes it, and only spills a context the user pinned with `-c`); unset/0 = no window. With no window the KV takes the PLAIN device buffer, so a run without the knob is byte-identical to a build without this block -- including its OOM (verified). `LLAMA_KV_SPILL_RAM_PCT` (85 % of MemAvailable) caps the pinned spill and widens the window rather than being OOM-killed; `LLAMA_KV_REGION=0` disables the provider; `LLAMA_KV_REGION_QUARANTINE=0` and `LLAMA_KV_REGION_DEBUG/TRACE/CANARY/DUMP` are the diagnosis switches. PURITY (the window). A spilled KV is numerically transparent: prefill-logit **KLD -0.000000 / 100.000 %** on a spilling 27B arm and -0.000000 / 99.994 % on a spilling Flash-Next (two KV caches: the attention KV and the QSA indexer), text byte-identical on 27B (f16 and q8_0), 4B, 35B-A3B and Flash-Next, and the state paths, the context-checkpoint path and the MTP verify widths all green on arms that provably spill. Two driver hazards are held: a kind flip zeroes a neighbouring live host mapping unless the released physical is held across the create (`LLAMA_KV_REGION_QUARANTINE`, default on -- `=0` reproduces the corruption), and every tensor in a windowed region is placed on the driver's map granularity so a slide step coincides with a mapping. An idle-slot park is REFUSED on a region-backed cache (the server then saves the slot to the prompt cache and clears it, which is byte-identical to the parking gate's reference) because a park moves cells above the region's mapped watermark through the copy engine, which faults the GPU. FIT. `--fit` sizes and reports the window (`auto`), or honours and reports a numeric `W`: the resident/spill split, the VRAM saved, and the per-token read cost at the model's full context from the backend's calibrated link rate. The fit identifies the KV's bytes by the region buffer TYPE, and its measurement context is a `no_alloc` probe that declines a window -- so the probe takes the region buffer explicitly (`llama_kv_region_set_probe`); without that the fit cannot see the KV, reports an over-budget config and aborts instead of sizing the window (the r178 regression). GATES (1 GPU, gfx1201): default path byte-identical (`5ba44647188f`) and still OOMs; VMM selftest PASS and FAIL with the hold disabled; windowed arms 305 `e2cea6fa6670` = plain at W=1024/2048/4096 (spilling at 1024: 128 MiB host), `QUARANTINE=0` -> 325 `fb65430049e9` (the hazard); `--fit` sizes `auto` (96680 of 262144 cells, 3210 MiB resident) and reports a numeric W; `gate-ckpt-reuse.sh` / `gate-state-pipe.sh` / MTP verify widths on spilling arms; `test-backend-ops -o FLASH_ATTN_QSA` 26/26; `check-gpu-faults.sh` clean. Not in this block: the campaign's Goal B (a sparse attended set) and Goal C (the MTP drafter ring, `LLAMA_SPEC_DRAFT_WINDOW`) -- both remain campaign work -- and A1 (the superseded two-base FA read). Records: `wip/kv-residency/A2-MIXED-BACKING.md` (§3.7.9, §3.7.11), `HANDOVER.md`. MULTI-DEVICE `--fit` (r181; the window itself reaches a tensor split in r204, at the end of this message): the KV-region glue is now safe on a Meta (tensor-split) device, and `auto`'s decision reaches the cache as a decision. r178 made default `--fit` abort on ANY `-sm tensor` run with more than one device: the fit's KV probes and the cache's own region lookups call `ggml_backend_dev_backend_reg(dev)` and hand it to `ggml_backend_reg_get_proc_address`, and a Meta device has no backend reg (`device->reg == NULL`), so `GGML_ASSERT(reg)` fired at model load. Three paths asserted: the fit probe (any run), the runtime buft lookup (a numeric W), and the spill budget/link lookups (a numeric W below `-c`). r181 makes a null reg read as "not provided" and declines the window with one message naming the tensor split (fit and cache), keeping the KV fully resident -- which is the r181 state; r204, below, is what makes the backend answer there. Three wiring defects in the same code, all visible on ONE device: - `auto`'s "no window needed" decision (0) was indistinguishable from "nobody decided", so the cache warned "--fit did not run" immediately after the fit had decided exactly that. `llama_kv_region_set_resident_cells` now records that a decision was made (`llama_kv_region_resident_cells_decided`), and a decided 0 is silent. - every run without the knob logged "the windowed KV is unavailable for this cache (no spilled cells)". That message now only fires when a window was actually requested and declined for a real reason. - the pinned-RAM ceiling clamp could raise W past the VRAM budget and then be reported as "does not make this fit either". It is now only taken while the wider window still meets the VRAM target; otherwise the fit says the ceiling cannot be served at this `-c` and drops the window (which the fit then fits by reducing the context). That ordering is not cosmetic: an intermediate form of this fix accepted a 235 GiB pinned spill plan for a 4B at `-c 8388608`, and creating it OOM-killed the test box. GATES (the window, gfx1201): `--fit on` (default) at 2 and 3 devices, `-sm tensor`, with no knob / a numeric W / `auto`, fit on and off: no assert, tokens produced, exactly one message per requested window. `-sm layer` 2 devices and 1 GPU still take the window per device (numeric W), and `auto` still sizes the 27B Q8_0 `-c 262144` q8_0 arm identically (123265 of 262144 cells, 4092.8 MiB resident / 4611.2 MiB spilling). One device, no knob: no KV message at all. Purity unchanged: plain vs a SPILLING windowed arm prefill-logit KLD 0.000000 / 99.990 % (q8_0 KV), greedy text byte-identical on that arm; 35B-A3B (1 GPU and 2-GPU `-sm tensor`), dense 27B and the canonical 27B Q8_0 prefill-logit gate (0.000000 / 100.000 %) byte-identical to r180; MTP Protocol A unchanged (tensor acceptance 0.60816 = 1937/3185, plain == draft-mtp); no GPU faults. ========================================================================== PART 2 -- the ATTENDANCE POOL (Goal B, promoted in r190) ========================================================================== The attention KV lives twice: its AUTHORITATIVE copy in a pinned host MIRROR (cell-indexed, so the writers, state_write/state_read, the K-shift, defrag and seq_park all work on it unchanged -- the writer rule) and a compact DEVICE POOL of pages of one indexer block (compress_ratio cells) with a page table block -> slot and its inverse. A decode step resolves its top-k selection through the table and fills the pages it missed from the mirror; the QSA reader gathers K/V at the pool slots while the mask stays cell-indexed. LLAMA_KV_REGION_POOL=<cells>, unset/0 = off = byte-identical. Contents. - ggml/src/ggml-cuda/kv-pool.{cu,cuh}: GGML_OP_KV_POOL. MARK sets use[slot] = epoch for every page this launch reads AND every page the batch just wrote (the graph's k_idxs), and queues the written ones for re-fill; CLAIM takes a slot for each DISTINCT missing block (the table CAS is the dedupe) and never takes a slot MARK protected; MAP+FILL writes each selected cell's pool position into the reader's K/V id list and copies the claimed and dirty pages from the mirror, K and V sharing slots. The epoch is a device counter incremented once per launch: the graph bakes pointers, never counters, and nothing is allocated per launch. - ggml-cuda.cu: the pool's pinned host mirror buffer type -- a DEVICE buffer type whose allocation is pinned host memory (`ROCm_Host` reports is_host, which would send the KV's writers and the FA read to the CPU on a discrete device), and its proc-address entry. - llama-kv-cache: the eligibility, the per-layer pool tensors (pool_k/pool_v, tbl, inv, use, one shared counter block), the resolve wiring into the QSA id list, kv_pool_serves() (a batch too wide for the pool takes the cell-indexed path), the teardown accounting (LLAMA_KV_POOL_STATS takes a PATH: a line on stderr sits inside the generated text), and memory_breakdown() charging the mirror to the host bucket so `--fit` does not reserve it as VRAM. - llama-memory-hybrid-idx / llama-memory-hybrid / llama-memory: the second id list (the K/V gather follows the page table while the mask stays cell-indexed), the flag threading, and the pool's byte accounting for `--fit` (llama_get_kv_pool_bytes()). - models/qwen4exp.cpp: a pooled cache reports is_streaming() and the sparse arm uses the pool's id list; the MTP draft's own cache is never pooled (its attention is dense). - llama-context / the async state copies: the mirror's buffer type is accepted by the batched save and restore (its bytes are host memory, staged through the pinned state_stage). - common/fit.cpp + src/llama-ext.h: the pool's split in --fit's arithmetic and report (the mirror is pinned host RAM, the pool is VRAM), and no context-reduction interpolation while the pool is active -- the pool's VRAM is fixed, so reducing -c frees nothing and the interpolation would divide by a near-zero bytes-per-context delta. Invariants, each one caught by the greedy text. 1. MARK then CLAIM: a claim must never evict a page the same launch reads. Without MARK the round-robin victim could be a page another row still needs (the text diverged ~400 chars in, and a pool larger than the whole cache hid it completely). 2. Claim ATTEMPTS are not distinct blocks: a slot per id attempt wrapped the cursor within one 4-row batch, so two blocks shared a slot and a just-resolved block went unresident. The table CAS dedupes first, so only distinct blocks consume a slot and kv_pool_serves() bounds the distinct count. 3. No transient scratch in a captured graph: the fill list lived in a ggml_cuda_pool_alloc that is freed at the end of the op, and a captured graph bakes the pointer, so a replay wrote into whatever op had been handed that block ("values verify clean, text differs run to run"). It lives in the counters tensor. 4. The mirror is AUTHORITATIVE: the writers land in it and a declared page is re-filled from it before the attention reads it, so an eviction costs nothing and nothing has to be invalidated -- except by a path that rewrites cells in place without going through the writers (the K-shift, a state restore), which calls kv_pool_invalidate(). 5. Eligibility is narrow on purpose: one stream, non-MLA, K and V both present, !v_trans, a uniform compress_ratio and cell geometry, no window active, a device-offloaded cache, and only the trunk context of a qwen4exp model. Anything else declines with one message and the KV is unchanged. 6. The pool is floored at one decode band's worth of blocks (8 x ceil(width/page) pages) so a verify batch cannot exhaust the slot budget, and the mirror is bounded at creation by LLAMA_KV_SPILL_RAM_PCT (it is pinned, non-swappable RAM) -- over the ceiling the pool is declined loudly instead of being OOM-killed. Measured (Flash-Next GSQ-IQ3_XXS, 1 GPU, -ncmoe 48, q8_0, the PLE flags, arms interleaved in one batch, -n 512, MTP depth 4; t/s and tokens/step): depth (ctx) dense sparse pool (204 MiB) text (-n 64) 5 298 (16 384) 72.09 71.58 71.27 pool == sparse: 332 chars dd1981213373 102 899 (131 072) 59.10 54.70 54.65 (5.3k / 51 475 references; dense differs) 180 035 (196 608) 48.94 43.16 43.41 pool == sparse: 861 chars 263c7f2be4d9 The pool lands ON the sparse ceiling at every depth (+0.5 / +0.6 / +0.58 %), so its placement is free and what remains against a resident KV (-7 % / -11 %) is the sparse decode arm's own indexer cost (block 11), not the KV's storage. A 204 MiB pool replaces the resident attention KV's 1 632 MiB at 103k / 2 448 MiB at 180k, and the freed VRAM goes to the expert arena: 103k plain decode, -n 2000, 23 579.8 -> 25 018.6 MiB (+1 438.8 MiB, +18 slots/table), expert hit 96.26 -> 97.02 %, cold reads 42.0 -> 31.6 GiB. The pool's own cost is 0.10-0.11 ms/token (mark/claim/map+fill) with fills 0.03-0.05 ms/step at 92-99 % hits, which is why a better page policy (LRU / F-LRU / a heat prior) is measured dead at this shape. Full numbers and the three-depth table: ../wip/kv-residency/BA-POOL-DESIGN.md §7-§8. PURITY (the pool). Greedy text pool == the resident sparse arm at 5.3k (332 dd1981213373), 51 475 depth (854 43b30de151b9) and 180k (861 263c7f2be4d9), with the dense arm differing as documented (GREEDY-PURITY §45/§63); LLAMA_KV_POOL_VERIFY=1 0 mismatches on every arm; gate-prefill-logits --ab "LLAMA_KV_REGION_POOL=..." 0.000000 / 100.000 % on the pool arm (base PPL 2.9225, bit-identical to the campaign's own base); gate-park-idle-slots, gate-ckpt-reuse and gate-state-pipe PASS on a pooled cache (the mirror is authoritative, which is what makes them trivial); test-backend-ops -o FLASH_ATTN_QSA pass; no GPU faults; and `--fit` accepts the arms that only fit with the pool (-ncmoe 21/22 at -c 262144: refused without it, accepted with it; -fitp moves 3 264 MiB from the device row to Host). ========================================================================== PART 3 -- a STREAMED cache takes the sparse decode arm (B2) ========================================================================== A cache that is streaming at the depth it reads -- a window the used extent has passed, or a pool -- takes the sparse QSA decode arm; a resident cache keeps the dense one. llama_kv_cache::is_streaming() plus the qwen4exp arm policy, LLAMA_QSA_DENSE_DECODE_STREAM=0 to restore the old behaviour. Measured on a spilled KV (Flash-Next IQ3_XXS, -ncmoe 48, q8_0, 1 GPU, -n 400, 2 reps): +34.3 % at 102 899 depth (23.42 -> 31.43 t/s) and +47.3 % at 180 035 (16.51 -> 24.31); a resident cache byte-identical (853 77a40bf40be1). This is a decode-ARM choice, i.e. a different attention regime (like GREEDY-PURITY §45/§63), so a streamed arm's text differs from the old dense-arm text by construction and a resident arm is the oracle. ========================================================================== DEFAULT OFF, for both placements ========================================================================== Neither knob is a speed feature on a config whose KV fits: the window costs the depth below W (11-26 %) and the pool costs the sparse-vs-dense gap (-7 % at 103k, -11 % at 180k). They are FITTABILITY features -- they turn an OOM into a run and they hand the freed VRAM to the expert arena -- so both are opt-in and both stay byte-identical, including the OOM, with their knobs unset. Do not "fix" the defaults. Goal C (the MTP drafter ring, TODO ggml-org#121) joins the same block -- it is the same claim applied to the draft context, and its default follows the delivery's own rule because it measures positive. `LLAMA_SPEC_DRAFT_WINDOW` gives the MTP draft context a sliding window instead of a `-c`-sized KV: unset or `auto` is the adaptive policy (a quarter of the context, clamped to [32768, 65536] cells), `0` is off (byte-identical to a build without it) and `N` is a cell count. The drafter reads its last few thousand tokens, so a window at or above that is free and one far below it costs 7-9 % of decode; the clamps keep it above that band, and the target verifies every token it proposes, so a truncated draft can only be slower. The ring is the shipped reclaim in `llama_kv_cache::find_slot` (`n_swa`), not a new allocator, and the derived kq mask stays valid -- its predicate compares each cell's POSITION, so a recycled cell reports its new one. The VRAM win needed one more piece: an embedded MTP head has no GGUF of its own, so the slab's draft reserve was the flat 3584 MiB and the freed VRAM never reached the expert arena. For an embedded MTP head with an active window the reserve is now derived from the model's own metadata with the weights zeroed (they are the target's) and the KV sized by the window: aux 3.50 -> 0.76 GiB, i.e. the arena gains ~2.8 GiB. A separate MTP draft GGUF (qwen4exp/Flash-Next) and an un-windowed run keep the flat constant exactly as before, and a declined arena preflight now re-evaluates when the smaller real value arrives instead of latching on the load-time estimate. Measured (1 GPU; one R9700; `-n 2000`/`-n 3000`; static depth 3; interleaved): * 35B-A3B Q8_0 `-ncmoe 48 -c 262144` q8_0 KV, 51 433-token prompt: arena 20 910 -> 23 715 MiB (residency 64.1 -> 72.7 %), decode 111.2 -> 113.7 t/s at `-n 3000` (+2.2 %; +2.8-4.9 % at `-n 2000`), prefill +3.4 %, drafts byte-for-byte the same count (1995/3011) -- the window truncates nothing the drafter used. * dense 27B UD-Q4_K_XL `-c 102400`, MTP Protocol A `-n 3000`, reasoning-pinned: layer 71.9 -> 72.1, tensor 72.6 -> 72.5 (neutral), acceptance 2083/2747 identical in all four arms. * target greedy text byte-identical across off/auto/4096, and plain == draft-mtp == draft-mtp(W=512) at `-c 16384` with a 5256-token prompt and 3000 generated tokens (10 158 chars, sha 99b267e8dc3e), i.e. no wrong answer under constant cell reuse. * gates on a windowed draft: `gate-park-idle-slots.sh` (35B, -ncmoe 48, `-c 65536`: 3 park moves, park == lazyoff), `gate-ckpt-reuse.sh` (4B, `-c 131072`: draft cache 33280 of 131072), `gate-state-pipe.sh` (35B, `-c 65536`: all five arms) -- all PASS with `MTP draft KV window = 32768 cells` in their logs. r194 corner fixes (found by a configuration battery against Flash-Next after r193): * LLAMA_KV_REGION_POOL is capped at the cache's own cell count. =1000000 on a 262144-cell context used to take a 12451 MiB device pool of 250000 pages where only 65536 blocks exist (never claimed, arena -4 GiB); it is now 3264 MiB / 65536 pages, and a small context clamps the same way. * the draft KV window sizes only the reserve of the cache it actually windows. A separate -md MTP head (Flash-Next) keeps its full -c cache, but the reserve was derived with the window: 921 MiB where the honest number is 1566 (kv 217 vs 862) at -c 262144, the under-charge direction. Embedded heads (qwen3.5/3.6/3.8) are unchanged (776 MiB on the 35B). The VRAM cliff at -c 262144 is documented (not code): the 768 MiB default headroom is one hipBLASLt workspace short for the first prefill, GGML_CUDA_SLAB_HEADROOM_MIB=1536 is 3/3 requests clean. Amendment (TODO ggml-org#129's sibling): `-nkvo` declines the window, and the streamed arm keys on the placement. The window is a DEVICE region plus a pinned host tail, but its guard did not test `offload`: with `-nkvo` the per-layer buffer is chosen inside `if (offload)` and stays plain pageable host memory, while the plan block still logged "WINDOWED KV ENABLED", reserved pinned-RAM spill budget and left `kv_resident_cells` set. `is_streaming()` then keyed the streamed (sparse) decode arm on that plan -- qwen4exp consumes it -- for a KV with no region at all. Measured: `-nkvo LLAMA_KV_RESIDENT_CELLS=64` built a plain `CPU KV buffer` of the whole context while announcing a 64-cell VRAM window. The window now declines once, with the reason (the pool already declines on `!offload`), so `-nkvo` means "no streamed placement"; `is_streaming()` tests `kv_region`, the placement actually taken, which also covers a device cache whose region buft the backend refused. Text is unchanged in every arm (the decline is a no-op: `-nkvo` + window already read as `-nkvo` alone). Amendment (issue ggml-org#264): the draft window is PER SEQUENCE, and under `--kv-unified` its cell count is `(win + one batch) x n_seq_max`. A unified cache holds every sequence in ONE stream, so the r193 sizing (`win + n_ubatch` cells) was shared by all of them: once the first sequence had filled its window the tail was all the room left, the tail is where that sequence's own ring writes, and a second sequence's first batch had no contiguous run to be placed in -- `find_slot` refused, and every request on that slot answered `decode() failed: failed to process speculative batch` (HTTP 500) while the drafter ran. Reported on `--kv-unified -np 2` with a 65 536-cell window at `-c 262144` after slot 0 held ~100k tokens; reproduced here with a forced 8192-cell window. A per-stream cache (no `--kv-unified`) already sized each stream separately and is unchanged. `llama_spec_draft_kv_cells()` is now the one geometry function -- the cache (`create_memory`), the slab's draft reserve estimate and the "is a window active" test in `common` all call it, so the reserve can never under-charge an allocation. It grants `win` per sequence plus one placeable batch (`(win + n_ubatch) * n_seq_max`, capped at the context), and DECLINES the window when that does not fit the context per sequence rather than lowering it to `per_seq - n_ubatch`: a window that small saves one batch of cells per sequence and masks the drafter's newest cells to do it. `llama_spec_draft_window_cells()` stays the policy (it is the per-sequence window). n_seq_max == 1 -- every `llama-cli`/`llama-bench` run -- measures exactly what it did (cells 1536 for a 1024-cell window at `-c 8192`), so no single-sequence arm changes at all. Measured (dense 27B, 1 GPU, `-np 2 --kv-unified`): the issue's scenario now answers both slots, and `scripts/gate-spec-draft-window.sh` (new) drives 6 requests over 2 slots with a 1024-cell window -- both rings wrapping, prompts full re-prefilled by swapping them between slots -- with output byte-identical to `LLAMA_SPEC_DRAFT_WINDOW=0` on every step and draft acceptance identical (17/36, 23/23). Greedy text `plain == draft-mtp == draft-mtp(W=1024) == draft-mtp(W=0)` (876 chars, sha 8c8fd395402f) at `-c 16384`. And the reserve now charges a per-STREAM (no `--kv-unified`) draft cache for every stream it allocates: `n_seq_max x` the per-stream cell count. Before, a multi-slot windowed MTP server without `--kv-unified` (35B-A3B `-ncmoe 40 -np 2 -c 8192`, window 1024: 2 x 1536 = 3072 cells allocated, 1536 charged) under-charged the slab's aux reserve by one stream's window -- the direction the reserve header calls dangerous. Measured: 3072 cells reported on both the unified and the per-stream arm now. ========================================================================== PART 4 -- `-sm tensor`: the window across a split (r204, `TODO` ggml-org#124) ========================================================================== A Meta (tensor-split) device carries no backend reg, so the r181 answer was "not provided" and the window was declined on every split. `TODO` ggml-org#124 designed the fix on a one-GPU box (`archive/work/kv-residency/ A6-TENSOR-SPLIT-WINDOW.md`, changes C1-C5); it is implemented and measured here, on a 3x R9700 host, and the decline is gone. * `ggml_backend_meta_kv_region_buft / _is_kv_buft / _grow` (new, `ggml-backend.h`): the Meta buffer type over the per-child region buffer types (ALL children or nothing), the is-a-region predicate `--fit` needs (the CUDA predicate is an identity on the child's `alloc_buffer` and cannot answer for a Meta buffer type), and a grow that fans out to every child. A child that cannot be reached is a REFUSAL (-1), never the 0 the CUDA hook returns for "not a region buffer": for a Meta buffer that 0 was a silent success on unmapped VA, i.e. a batch that page-faults the GPU. * `llama_kv_cache` resolves capability, the buffer type, the spill ceiling and the link through the Meta side; a MIRRORED cache (dsv4 / HRM, `llama_model::kv_cache_split_mirrored()`) declines the window with its own message, because every device holds the whole cache there (`n_devices x W x cell_bytes`) and the pinned-spill plan is per logical cache. * `common/fit.cpp` decides the window inside the tensor-split branch: charged at its PHYSICAL `W x cell_bytes` (what all devices commit together) against `min_i(target_i / ratio_i)`, which makes the aggregate check imply every device's (the loader shards the KV along the KV-head axis by the same ratio it shards the weights), and the Meta entry's margin is now the SUM of the children's `--fit-target`s (it was child 0's, so `(n_devices - 1) x target` silently vanished from the budget). The corrected KV term applies ONLY where a window is asked for: a run without `LLAMA_KV_RESIDENT_CELLS` keeps this branch's old arithmetic exactly, so the split's pre-existing `n_devices x` KV over-count is untouched outside the window arm. Four defects the arms found, fixed in the same block: 1. the init-time window commit was rounded up to a whole map unit past the tensor's own extent, and on a split each child is its own VA reservation -- the last tensor's inflated window was refused (`the KV window (4.00 MiB) could not be committed in VRAM on device 1`). Clamped to the region's END, in whole units (clamping to the tensor's own extent was tried first and is wrong: it leaves a short mapping off the unit grid and the next slide refuses to flip). 2. `ensure_span` refused a request that covered several WHOLE mappings; one batch can advance the boundary by more than one unit, and a 1 MiB unit is floored to the driver's 2 MiB granularity, so the request covered two mappings and aborted the batch. Whole mappings now flip one at a time; a request that covers a mapping only in PART is still refused (that loses bytes on this driver). 3. the batched state save issued a 2-D D2H per device and `hipMemcpy2DAsync` fails (`invalid argument`) when the range begins in a spilled region's pinned host mapping (the tensor-split checkpoint save aborted: `cache_k_l64 (view)`, 1024 B x 4782 rows). The region-backed directions of `get/set_tensor_2d_async` now go through the region buffer's own copy, ordered behind the compute stream like the pool mirror (a blocking default-stream copy does not wait for it, and the state saved mid-batch is torn). 4. that fallback's "contiguous rows = one copy" shortcut ignored the caller's destination pitch, which for a split splice is the FULL row, wider than one device's slice: the state-pipe gate failed on every cycle of all four async arms until a tight block required BOTH pitches to equal the width. Verified (gfx1201, `ROCBLAS_USE_HIPBLASLT=0` for every fresh-process pair): text byte-identical on `win3 == ref3` (3 devices, 4B, `057ea27b1009`) and `win2 == ref2 == win2mtp == ref2mtp` (2 devices, 27B, a 5246-token prompt, `7a7430617465`; draft acceptance 0.46154 in both MTP arms), also at a 1 MiB map unit; the spill is real on EVERY device (32 mapping flips each at 4 MiB, 128 at 1 MiB); a `-c 1048576` 2-device split (64 GiB of f16 KV) runs only because of the window; the single-device and `-nkvo` arms are unchanged; `--fit` on the split reports a WINDOWED cache and keeps the pinned `-c 524288` (plus the pinned-RAM ceiling's widen and drop arms, and `LLAMA_KV_REGION=0` silent); coherence identical to the r203 build on four no-window arms (3-GPU 4B, 2-GPU and 1-GPU 27B, 2-GPU host-expert 35B-A3B); prefill-logit 0.000000 / 100.000 %; Protocol A four-axis R/P/C/K 1.91x / 2.43x / 2.58x / 2.74x (acceptance 0.5869 / 0.8391 / 0.9112 / 0.9920, the r90 shape); `gate-spec-draft-window.sh` 6/6; `gate-state-pipe.sh` 2-GPU `-sm tensor` PASS with and without the window (the windowed arm failed before (3) and (4)); `GGML_CUDA_VMM_REGION_SELFTEST=1` PASS with a new multi-mapping arm; per-block build 1/1; `validate-set.sh` strict 16/16. Gate: `scripts/gate-kv-window-split.sh`. Record: `benchmarks/2026-11-01-kv-window-tensor-split-124.md`.
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Nov 4, 2026
…W (Goal A) and an attendance POOL (Goal B), both opt-in Goals A and B of TODO ggml-org#118, promoted from the `wip/kv-residency` campaign. This block is the delivery's "the KV does not have to be O(-c) of VRAM" work: TWO opt-in placements of the same cache, and each one is byte-identical to a build without it when its knob is unset. * the WINDOW (`LLAMA_KV_RESIDENT_CELLS=<cells>|auto`): the newest W cells stay in VRAM, everything older spills to pinned system RAM in the SAME VA reservation -- a positional window, no kernel or op change; * the POOL (`LLAMA_KV_REGION_POOL=<cells>`): the authoritative copy of the WHOLE context in a pinned host mirror, and a compact device pool of the pages a decode step actually attends to, which the QSA sparse read resolves through a page table (`GGML_OP_KV_POOL`). They are mutually exclusive by construction (the pool declines while a window is active) and they answer the same question from opposite ends: the window keeps the *newest* cells hot, the pool keeps the *attended* cells hot. Both report `is_streaming()`, so a streamed cache takes the sparse QSA decode arm (B2, below). ========================================================================== PART 1 -- the WINDOW (Goal A, promoted in r178) ========================================================================== Goal A of TODO ggml-org#118, promoted from the `wip/kv-residency` campaign. WHAT IT DOES. The KV cache's VRAM cost becomes a WINDOW of the newest `W` cells instead of `-c` cells: one VA reservation (a CUDA/HIP VMM region) holds the whole cache, the window's cells are backed by VRAM and everything below them by pinned system RAM. `set_rows`, the in-place rope shift, `state_write/read`, the kq mask and the FA kernels keep addressing one contiguous range, so no kernel and no op changes. The window slides with the watermark in whole map units, so a remap happens once per few thousand tokens and the apparatus itself is free (a zero-spill arm measures the same as plain). WHY. (a) A context that OOMs today runs: 27B Q8_0 `-c 262144` (8704 MiB of KV) now runs on one 32 GiB card at 128 MiB VRAM + 8576 MiB pinned host for the KV. (b) With host-resident MoE experts, the VRAM the KV does not need *yet* goes to the expert-cache arena: measured at `-c 262144`, `-n 2000`, `-ncmoe` = the model's full layer count, 51 433-token prompt, W at or above the run's depth = **+2.2 to +2.9 GiB of arena** (+3.9 to +6.7 points of residency) for free -- 122B-A10B Q4_K_XL +3.8 % decode and +4.7 % prefill, 35B-A3B Q8_0 -0.9 % decode and +3 % prefill; a `W` 35 k cells BELOW the run depth costs 11-26 % (the spill is read every token). OPT-IN, AND ONLY WHEN ASKED FOR. `LLAMA_KV_RESIDENT_CELLS=<cells>` (a number) or `=auto` (`--fit` sizes it, and only spills a context the user pinned with `-c`); unset/0 = no window. With no window the KV takes the PLAIN device buffer, so a run without the knob is byte-identical to a build without this block -- including its OOM (verified). `LLAMA_KV_SPILL_RAM_PCT` (85 % of MemAvailable) caps the pinned spill and widens the window rather than being OOM-killed; `LLAMA_KV_REGION=0` disables the provider; `LLAMA_KV_REGION_QUARANTINE=0` and `LLAMA_KV_REGION_DEBUG/TRACE/CANARY/DUMP` are the diagnosis switches. PURITY (the window). A spilled KV is numerically transparent: prefill-logit **KLD -0.000000 / 100.000 %** on a spilling 27B arm and -0.000000 / 99.994 % on a spilling Flash-Next (two KV caches: the attention KV and the QSA indexer), text byte-identical on 27B (f16 and q8_0), 4B, 35B-A3B and Flash-Next, and the state paths, the context-checkpoint path and the MTP verify widths all green on arms that provably spill. Two driver hazards are held: a kind flip zeroes a neighbouring live host mapping unless the released physical is held across the create (`LLAMA_KV_REGION_QUARANTINE`, default on -- `=0` reproduces the corruption), and every tensor in a windowed region is placed on the driver's map granularity so a slide step coincides with a mapping. An idle-slot park is REFUSED on a region-backed cache (the server then saves the slot to the prompt cache and clears it, which is byte-identical to the parking gate's reference) because a park moves cells above the region's mapped watermark through the copy engine, which faults the GPU. FIT. `--fit` sizes and reports the window (`auto`), or honours and reports a numeric `W`: the resident/spill split, the VRAM saved, and the per-token read cost at the model's full context from the backend's calibrated link rate. The fit identifies the KV's bytes by the region buffer TYPE, and its measurement context is a `no_alloc` probe that declines a window -- so the probe takes the region buffer explicitly (`llama_kv_region_set_probe`); without that the fit cannot see the KV, reports an over-budget config and aborts instead of sizing the window (the r178 regression). GATES (1 GPU, gfx1201): default path byte-identical (`5ba44647188f`) and still OOMs; VMM selftest PASS and FAIL with the hold disabled; windowed arms 305 `e2cea6fa6670` = plain at W=1024/2048/4096 (spilling at 1024: 128 MiB host), `QUARANTINE=0` -> 325 `fb65430049e9` (the hazard); `--fit` sizes `auto` (96680 of 262144 cells, 3210 MiB resident) and reports a numeric W; `gate-ckpt-reuse.sh` / `gate-state-pipe.sh` / MTP verify widths on spilling arms; `test-backend-ops -o FLASH_ATTN_QSA` 26/26; `check-gpu-faults.sh` clean. Not in this block: the campaign's Goal B (a sparse attended set) and Goal C (the MTP drafter ring, `LLAMA_SPEC_DRAFT_WINDOW`) -- both remain campaign work -- and A1 (the superseded two-base FA read). Records: `wip/kv-residency/A2-MIXED-BACKING.md` (§3.7.9, §3.7.11), `HANDOVER.md`. MULTI-DEVICE `--fit` (r181; the window itself reaches a tensor split in r204, at the end of this message): the KV-region glue is now safe on a Meta (tensor-split) device, and `auto`'s decision reaches the cache as a decision. r178 made default `--fit` abort on ANY `-sm tensor` run with more than one device: the fit's KV probes and the cache's own region lookups call `ggml_backend_dev_backend_reg(dev)` and hand it to `ggml_backend_reg_get_proc_address`, and a Meta device has no backend reg (`device->reg == NULL`), so `GGML_ASSERT(reg)` fired at model load. Three paths asserted: the fit probe (any run), the runtime buft lookup (a numeric W), and the spill budget/link lookups (a numeric W below `-c`). r181 makes a null reg read as "not provided" and declines the window with one message naming the tensor split (fit and cache), keeping the KV fully resident -- which is the r181 state; r204, below, is what makes the backend answer there. Three wiring defects in the same code, all visible on ONE device: - `auto`'s "no window needed" decision (0) was indistinguishable from "nobody decided", so the cache warned "--fit did not run" immediately after the fit had decided exactly that. `llama_kv_region_set_resident_cells` now records that a decision was made (`llama_kv_region_resident_cells_decided`), and a decided 0 is silent. - every run without the knob logged "the windowed KV is unavailable for this cache (no spilled cells)". That message now only fires when a window was actually requested and declined for a real reason. - the pinned-RAM ceiling clamp could raise W past the VRAM budget and then be reported as "does not make this fit either". It is now only taken while the wider window still meets the VRAM target; otherwise the fit says the ceiling cannot be served at this `-c` and drops the window (which the fit then fits by reducing the context). That ordering is not cosmetic: an intermediate form of this fix accepted a 235 GiB pinned spill plan for a 4B at `-c 8388608`, and creating it OOM-killed the test box. GATES (the window, gfx1201): `--fit on` (default) at 2 and 3 devices, `-sm tensor`, with no knob / a numeric W / `auto`, fit on and off: no assert, tokens produced, exactly one message per requested window. `-sm layer` 2 devices and 1 GPU still take the window per device (numeric W), and `auto` still sizes the 27B Q8_0 `-c 262144` q8_0 arm identically (123265 of 262144 cells, 4092.8 MiB resident / 4611.2 MiB spilling). One device, no knob: no KV message at all. Purity unchanged: plain vs a SPILLING windowed arm prefill-logit KLD 0.000000 / 99.990 % (q8_0 KV), greedy text byte-identical on that arm; 35B-A3B (1 GPU and 2-GPU `-sm tensor`), dense 27B and the canonical 27B Q8_0 prefill-logit gate (0.000000 / 100.000 %) byte-identical to r180; MTP Protocol A unchanged (tensor acceptance 0.60816 = 1937/3185, plain == draft-mtp); no GPU faults. ========================================================================== PART 2 -- the ATTENDANCE POOL (Goal B, promoted in r190) ========================================================================== The attention KV lives twice: its AUTHORITATIVE copy in a pinned host MIRROR (cell-indexed, so the writers, state_write/state_read, the K-shift, defrag and seq_park all work on it unchanged -- the writer rule) and a compact DEVICE POOL of pages of one indexer block (compress_ratio cells) with a page table block -> slot and its inverse. A decode step resolves its top-k selection through the table and fills the pages it missed from the mirror; the QSA reader gathers K/V at the pool slots while the mask stays cell-indexed. LLAMA_KV_REGION_POOL=<cells>, unset/0 = off = byte-identical. Contents. - ggml/src/ggml-cuda/kv-pool.{cu,cuh}: GGML_OP_KV_POOL. MARK sets use[slot] = epoch for every page this launch reads AND every page the batch just wrote (the graph's k_idxs), and queues the written ones for re-fill; CLAIM takes a slot for each DISTINCT missing block (the table CAS is the dedupe) and never takes a slot MARK protected; MAP+FILL writes each selected cell's pool position into the reader's K/V id list and copies the claimed and dirty pages from the mirror, K and V sharing slots. The epoch is a device counter incremented once per launch: the graph bakes pointers, never counters, and nothing is allocated per launch. - ggml-cuda.cu: the pool's pinned host mirror buffer type -- a DEVICE buffer type whose allocation is pinned host memory (`ROCm_Host` reports is_host, which would send the KV's writers and the FA read to the CPU on a discrete device), and its proc-address entry. - llama-kv-cache: the eligibility, the per-layer pool tensors (pool_k/pool_v, tbl, inv, use, one shared counter block), the resolve wiring into the QSA id list, kv_pool_serves() (a batch too wide for the pool takes the cell-indexed path), the teardown accounting (LLAMA_KV_POOL_STATS takes a PATH: a line on stderr sits inside the generated text), and memory_breakdown() charging the mirror to the host bucket so `--fit` does not reserve it as VRAM. - llama-memory-hybrid-idx / llama-memory-hybrid / llama-memory: the second id list (the K/V gather follows the page table while the mask stays cell-indexed), the flag threading, and the pool's byte accounting for `--fit` (llama_get_kv_pool_bytes()). - models/qwen4exp.cpp: a pooled cache reports is_streaming() and the sparse arm uses the pool's id list; the MTP draft's own cache is never pooled (its attention is dense). - llama-context / the async state copies: the mirror's buffer type is accepted by the batched save and restore (its bytes are host memory, staged through the pinned state_stage). - common/fit.cpp + src/llama-ext.h: the pool's split in --fit's arithmetic and report (the mirror is pinned host RAM, the pool is VRAM), and no context-reduction interpolation while the pool is active -- the pool's VRAM is fixed, so reducing -c frees nothing and the interpolation would divide by a near-zero bytes-per-context delta. Invariants, each one caught by the greedy text. 1. MARK then CLAIM: a claim must never evict a page the same launch reads. Without MARK the round-robin victim could be a page another row still needs (the text diverged ~400 chars in, and a pool larger than the whole cache hid it completely). 2. Claim ATTEMPTS are not distinct blocks: a slot per id attempt wrapped the cursor within one 4-row batch, so two blocks shared a slot and a just-resolved block went unresident. The table CAS dedupes first, so only distinct blocks consume a slot and kv_pool_serves() bounds the distinct count. 3. No transient scratch in a captured graph: the fill list lived in a ggml_cuda_pool_alloc that is freed at the end of the op, and a captured graph bakes the pointer, so a replay wrote into whatever op had been handed that block ("values verify clean, text differs run to run"). It lives in the counters tensor. 4. The mirror is AUTHORITATIVE: the writers land in it and a declared page is re-filled from it before the attention reads it, so an eviction costs nothing and nothing has to be invalidated -- except by a path that rewrites cells in place without going through the writers (the K-shift, a state restore), which calls kv_pool_invalidate(). 5. Eligibility is narrow on purpose: one stream, non-MLA, K and V both present, !v_trans, a uniform compress_ratio and cell geometry, no window active, a device-offloaded cache, and only the trunk context of a qwen4exp model. Anything else declines with one message and the KV is unchanged. 6. The pool is floored at one decode band's worth of blocks (8 x ceil(width/page) pages) so a verify batch cannot exhaust the slot budget, and the mirror is bounded at creation by LLAMA_KV_SPILL_RAM_PCT (it is pinned, non-swappable RAM) -- over the ceiling the pool is declined loudly instead of being OOM-killed. Measured (Flash-Next GSQ-IQ3_XXS, 1 GPU, -ncmoe 48, q8_0, the PLE flags, arms interleaved in one batch, -n 512, MTP depth 4; t/s and tokens/step): depth (ctx) dense sparse pool (204 MiB) text (-n 64) 5 298 (16 384) 72.09 71.58 71.27 pool == sparse: 332 chars dd1981213373 102 899 (131 072) 59.10 54.70 54.65 (5.3k / 51 475 references; dense differs) 180 035 (196 608) 48.94 43.16 43.41 pool == sparse: 861 chars 263c7f2be4d9 The pool lands ON the sparse ceiling at every depth (+0.5 / +0.6 / +0.58 %), so its placement is free and what remains against a resident KV (-7 % / -11 %) is the sparse decode arm's own indexer cost (block 11), not the KV's storage. A 204 MiB pool replaces the resident attention KV's 1 632 MiB at 103k / 2 448 MiB at 180k, and the freed VRAM goes to the expert arena: 103k plain decode, -n 2000, 23 579.8 -> 25 018.6 MiB (+1 438.8 MiB, +18 slots/table), expert hit 96.26 -> 97.02 %, cold reads 42.0 -> 31.6 GiB. The pool's own cost is 0.10-0.11 ms/token (mark/claim/map+fill) with fills 0.03-0.05 ms/step at 92-99 % hits, which is why a better page policy (LRU / F-LRU / a heat prior) is measured dead at this shape. Full numbers and the three-depth table: ../wip/kv-residency/BA-POOL-DESIGN.md §7-§8. PURITY (the pool). Greedy text pool == the resident sparse arm at 5.3k (332 dd1981213373), 51 475 depth (854 43b30de151b9) and 180k (861 263c7f2be4d9), with the dense arm differing as documented (GREEDY-PURITY §45/§63); LLAMA_KV_POOL_VERIFY=1 0 mismatches on every arm; gate-prefill-logits --ab "LLAMA_KV_REGION_POOL=..." 0.000000 / 100.000 % on the pool arm (base PPL 2.9225, bit-identical to the campaign's own base); gate-park-idle-slots, gate-ckpt-reuse and gate-state-pipe PASS on a pooled cache (the mirror is authoritative, which is what makes them trivial); test-backend-ops -o FLASH_ATTN_QSA pass; no GPU faults; and `--fit` accepts the arms that only fit with the pool (-ncmoe 21/22 at -c 262144: refused without it, accepted with it; -fitp moves 3 264 MiB from the device row to Host). ========================================================================== PART 3 -- a STREAMED cache takes the sparse decode arm (B2) ========================================================================== A cache that is streaming at the depth it reads -- a window the used extent has passed, or a pool -- takes the sparse QSA decode arm; a resident cache keeps the dense one. llama_kv_cache::is_streaming() plus the qwen4exp arm policy, LLAMA_QSA_DENSE_DECODE_STREAM=0 to restore the old behaviour. Measured on a spilled KV (Flash-Next IQ3_XXS, -ncmoe 48, q8_0, 1 GPU, -n 400, 2 reps): +34.3 % at 102 899 depth (23.42 -> 31.43 t/s) and +47.3 % at 180 035 (16.51 -> 24.31); a resident cache byte-identical (853 77a40bf40be1). This is a decode-ARM choice, i.e. a different attention regime (like GREEDY-PURITY §45/§63), so a streamed arm's text differs from the old dense-arm text by construction and a resident arm is the oracle. ========================================================================== DEFAULT OFF, for both placements ========================================================================== Neither knob is a speed feature on a config whose KV fits: the window costs the depth below W (11-26 %) and the pool costs the sparse-vs-dense gap (-7 % at 103k, -11 % at 180k). They are FITTABILITY features -- they turn an OOM into a run and they hand the freed VRAM to the expert arena -- so both are opt-in and both stay byte-identical, including the OOM, with their knobs unset. Do not "fix" the defaults. Goal C (the MTP drafter ring, TODO ggml-org#121) joins the same block -- it is the same claim applied to the draft context, and its default follows the delivery's own rule because it measures positive. `LLAMA_SPEC_DRAFT_WINDOW` gives the MTP draft context a sliding window instead of a `-c`-sized KV: unset or `auto` is the adaptive policy (a quarter of the context, clamped to [32768, 65536] cells), `0` is off (byte-identical to a build without it) and `N` is a cell count. The drafter reads its last few thousand tokens, so a window at or above that is free and one far below it costs 7-9 % of decode; the clamps keep it above that band, and the target verifies every token it proposes, so a truncated draft can only be slower. The ring is the shipped reclaim in `llama_kv_cache::find_slot` (`n_swa`), not a new allocator, and the derived kq mask stays valid -- its predicate compares each cell's POSITION, so a recycled cell reports its new one. The VRAM win needed one more piece: an embedded MTP head has no GGUF of its own, so the slab's draft reserve was the flat 3584 MiB and the freed VRAM never reached the expert arena. For an embedded MTP head with an active window the reserve is now derived from the model's own metadata with the weights zeroed (they are the target's) and the KV sized by the window: aux 3.50 -> 0.76 GiB, i.e. the arena gains ~2.8 GiB. A separate MTP draft GGUF (qwen4exp/Flash-Next) and an un-windowed run keep the flat constant exactly as before, and a declined arena preflight now re-evaluates when the smaller real value arrives instead of latching on the load-time estimate. Measured (1 GPU; one R9700; `-n 2000`/`-n 3000`; static depth 3; interleaved): * 35B-A3B Q8_0 `-ncmoe 48 -c 262144` q8_0 KV, 51 433-token prompt: arena 20 910 -> 23 715 MiB (residency 64.1 -> 72.7 %), decode 111.2 -> 113.7 t/s at `-n 3000` (+2.2 %; +2.8-4.9 % at `-n 2000`), prefill +3.4 %, drafts byte-for-byte the same count (1995/3011) -- the window truncates nothing the drafter used. * dense 27B UD-Q4_K_XL `-c 102400`, MTP Protocol A `-n 3000`, reasoning-pinned: layer 71.9 -> 72.1, tensor 72.6 -> 72.5 (neutral), acceptance 2083/2747 identical in all four arms. * target greedy text byte-identical across off/auto/4096, and plain == draft-mtp == draft-mtp(W=512) at `-c 16384` with a 5256-token prompt and 3000 generated tokens (10 158 chars, sha 99b267e8dc3e), i.e. no wrong answer under constant cell reuse. * gates on a windowed draft: `gate-park-idle-slots.sh` (35B, -ncmoe 48, `-c 65536`: 3 park moves, park == lazyoff), `gate-ckpt-reuse.sh` (4B, `-c 131072`: draft cache 33280 of 131072), `gate-state-pipe.sh` (35B, `-c 65536`: all five arms) -- all PASS with `MTP draft KV window = 32768 cells` in their logs. r194 corner fixes (found by a configuration battery against Flash-Next after r193): * LLAMA_KV_REGION_POOL is capped at the cache's own cell count. =1000000 on a 262144-cell context used to take a 12451 MiB device pool of 250000 pages where only 65536 blocks exist (never claimed, arena -4 GiB); it is now 3264 MiB / 65536 pages, and a small context clamps the same way. * the draft KV window sizes only the reserve of the cache it actually windows. A separate -md MTP head (Flash-Next) keeps its full -c cache, but the reserve was derived with the window: 921 MiB where the honest number is 1566 (kv 217 vs 862) at -c 262144, the under-charge direction. Embedded heads (qwen3.5/3.6/3.8) are unchanged (776 MiB on the 35B). The VRAM cliff at -c 262144 is documented (not code): the 768 MiB default headroom is one hipBLASLt workspace short for the first prefill, GGML_CUDA_SLAB_HEADROOM_MIB=1536 is 3/3 requests clean. Amendment (TODO ggml-org#129's sibling): `-nkvo` declines the window, and the streamed arm keys on the placement. The window is a DEVICE region plus a pinned host tail, but its guard did not test `offload`: with `-nkvo` the per-layer buffer is chosen inside `if (offload)` and stays plain pageable host memory, while the plan block still logged "WINDOWED KV ENABLED", reserved pinned-RAM spill budget and left `kv_resident_cells` set. `is_streaming()` then keyed the streamed (sparse) decode arm on that plan -- qwen4exp consumes it -- for a KV with no region at all. Measured: `-nkvo LLAMA_KV_RESIDENT_CELLS=64` built a plain `CPU KV buffer` of the whole context while announcing a 64-cell VRAM window. The window now declines once, with the reason (the pool already declines on `!offload`), so `-nkvo` means "no streamed placement"; `is_streaming()` tests `kv_region`, the placement actually taken, which also covers a device cache whose region buft the backend refused. Text is unchanged in every arm (the decline is a no-op: `-nkvo` + window already read as `-nkvo` alone). Amendment (issue ggml-org#264): the draft window is PER SEQUENCE, and under `--kv-unified` its cell count is `(win + one batch) x n_seq_max`. A unified cache holds every sequence in ONE stream, so the r193 sizing (`win + n_ubatch` cells) was shared by all of them: once the first sequence had filled its window the tail was all the room left, the tail is where that sequence's own ring writes, and a second sequence's first batch had no contiguous run to be placed in -- `find_slot` refused, and every request on that slot answered `decode() failed: failed to process speculative batch` (HTTP 500) while the drafter ran. Reported on `--kv-unified -np 2` with a 65 536-cell window at `-c 262144` after slot 0 held ~100k tokens; reproduced here with a forced 8192-cell window. A per-stream cache (no `--kv-unified`) already sized each stream separately and is unchanged. `llama_spec_draft_kv_cells()` is now the one geometry function -- the cache (`create_memory`), the slab's draft reserve estimate and the "is a window active" test in `common` all call it, so the reserve can never under-charge an allocation. It grants `win` per sequence plus one placeable batch (`(win + n_ubatch) * n_seq_max`, capped at the context), and DECLINES the window when that does not fit the context per sequence rather than lowering it to `per_seq - n_ubatch`: a window that small saves one batch of cells per sequence and masks the drafter's newest cells to do it. `llama_spec_draft_window_cells()` stays the policy (it is the per-sequence window). n_seq_max == 1 -- every `llama-cli`/`llama-bench` run -- measures exactly what it did (cells 1536 for a 1024-cell window at `-c 8192`), so no single-sequence arm changes at all. Measured (dense 27B, 1 GPU, `-np 2 --kv-unified`): the issue's scenario now answers both slots, and `scripts/gate-spec-draft-window.sh` (new) drives 6 requests over 2 slots with a 1024-cell window -- both rings wrapping, prompts full re-prefilled by swapping them between slots -- with output byte-identical to `LLAMA_SPEC_DRAFT_WINDOW=0` on every step and draft acceptance identical (17/36, 23/23). Greedy text `plain == draft-mtp == draft-mtp(W=1024) == draft-mtp(W=0)` (876 chars, sha 8c8fd395402f) at `-c 16384`. And the reserve now charges a per-STREAM (no `--kv-unified`) draft cache for every stream it allocates: `n_seq_max x` the per-stream cell count. Before, a multi-slot windowed MTP server without `--kv-unified` (35B-A3B `-ncmoe 40 -np 2 -c 8192`, window 1024: 2 x 1536 = 3072 cells allocated, 1536 charged) under-charged the slab's aux reserve by one stream's window -- the direction the reserve header calls dangerous. Measured: 3072 cells reported on both the unified and the per-stream arm now. ========================================================================== PART 4 -- `-sm tensor`: the window across a split (r204, `TODO` ggml-org#124) ========================================================================== A Meta (tensor-split) device carries no backend reg, so the r181 answer was "not provided" and the window was declined on every split. `TODO` ggml-org#124 designed the fix on a one-GPU box (`archive/work/kv-residency/ A6-TENSOR-SPLIT-WINDOW.md`, changes C1-C5); it is implemented and measured here, on a 3x R9700 host, and the decline is gone. * `ggml_backend_meta_kv_region_buft / _is_kv_buft / _grow` (new, `ggml-backend.h`): the Meta buffer type over the per-child region buffer types (ALL children or nothing), the is-a-region predicate `--fit` needs (the CUDA predicate is an identity on the child's `alloc_buffer` and cannot answer for a Meta buffer type), and a grow that fans out to every child. A child that cannot be reached is a REFUSAL (-1), never the 0 the CUDA hook returns for "not a region buffer": for a Meta buffer that 0 was a silent success on unmapped VA, i.e. a batch that page-faults the GPU. * `llama_kv_cache` resolves capability, the buffer type, the spill ceiling and the link through the Meta side; a MIRRORED cache (dsv4 / HRM, `llama_model::kv_cache_split_mirrored()`) declines the window with its own message, because every device holds the whole cache there (`n_devices x W x cell_bytes`) and the pinned-spill plan is per logical cache. * `common/fit.cpp` decides the window inside the tensor-split branch: charged at its PHYSICAL `W x cell_bytes` (what all devices commit together) against `min_i(target_i / ratio_i)`, which makes the aggregate check imply every device's (the loader shards the KV along the KV-head axis by the same ratio it shards the weights), and the Meta entry's margin is now the SUM of the children's `--fit-target`s (it was child 0's, so `(n_devices - 1) x target` silently vanished from the budget). The corrected KV term applies ONLY where a window is asked for: a run without `LLAMA_KV_RESIDENT_CELLS` keeps this branch's old arithmetic exactly, so the split's pre-existing `n_devices x` KV over-count is untouched outside the window arm. Four defects the arms found, fixed in the same block: 1. the init-time window commit was rounded up to a whole map unit past the tensor's own extent, and on a split each child is its own VA reservation -- the last tensor's inflated window was refused (`the KV window (4.00 MiB) could not be committed in VRAM on device 1`). Clamped to the region's END, in whole units (clamping to the tensor's own extent was tried first and is wrong: it leaves a short mapping off the unit grid and the next slide refuses to flip). 2. `ensure_span` refused a request that covered several WHOLE mappings; one batch can advance the boundary by more than one unit, and a 1 MiB unit is floored to the driver's 2 MiB granularity, so the request covered two mappings and aborted the batch. Whole mappings now flip one at a time; a request that covers a mapping only in PART is still refused (that loses bytes on this driver). 3. the batched state save issued a 2-D D2H per device and `hipMemcpy2DAsync` fails (`invalid argument`) when the range begins in a spilled region's pinned host mapping (the tensor-split checkpoint save aborted: `cache_k_l64 (view)`, 1024 B x 4782 rows). The region-backed directions of `get/set_tensor_2d_async` now go through the region buffer's own copy, ordered behind the compute stream like the pool mirror (a blocking default-stream copy does not wait for it, and the state saved mid-batch is torn). 4. that fallback's "contiguous rows = one copy" shortcut ignored the caller's destination pitch, which for a split splice is the FULL row, wider than one device's slice: the state-pipe gate failed on every cycle of all four async arms until a tight block required BOTH pitches to equal the width. Verified (gfx1201, `ROCBLAS_USE_HIPBLASLT=0` for every fresh-process pair): text byte-identical on `win3 == ref3` (3 devices, 4B, `057ea27b1009`) and `win2 == ref2 == win2mtp == ref2mtp` (2 devices, 27B, a 5246-token prompt, `7a7430617465`; draft acceptance 0.46154 in both MTP arms), also at a 1 MiB map unit; the spill is real on EVERY device (32 mapping flips each at 4 MiB, 128 at 1 MiB); a `-c 1048576` 2-device split (64 GiB of f16 KV) runs only because of the window; the single-device and `-nkvo` arms are unchanged; `--fit` on the split reports a WINDOWED cache and keeps the pinned `-c 524288` (plus the pinned-RAM ceiling's widen and drop arms, and `LLAMA_KV_REGION=0` silent); coherence identical to the r203 build on four no-window arms (3-GPU 4B, 2-GPU and 1-GPU 27B, 2-GPU host-expert 35B-A3B); prefill-logit 0.000000 / 100.000 %; Protocol A four-axis R/P/C/K 1.91x / 2.43x / 2.58x / 2.74x (acceptance 0.5869 / 0.8391 / 0.9112 / 0.9920, the r90 shape); `gate-spec-draft-window.sh` 6/6; `gate-state-pipe.sh` 2-GPU `-sm tensor` PASS with and without the window (the windowed arm failed before (3) and (4)); `GGML_CUDA_VMM_REGION_SELFTEST=1` PASS with a new multi-mapping arm; per-block build 1/1; `validate-set.sh` strict 16/16. Gate: `scripts/gate-kv-window-split.sh`. Record: `benchmarks/2026-11-01-kv-window-tensor-split-124.md`.
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Nov 4, 2026
…W (Goal A) and an attendance POOL (Goal B), both opt-in Goals A and B of TODO ggml-org#118, promoted from the `wip/kv-residency` campaign. This block is the delivery's "the KV does not have to be O(-c) of VRAM" work: TWO opt-in placements of the same cache, and each one is byte-identical to a build without it when its knob is unset. * the WINDOW (`LLAMA_KV_RESIDENT_CELLS=<cells>|auto`): the newest W cells stay in VRAM, everything older spills to pinned system RAM in the SAME VA reservation -- a positional window, no kernel or op change; * the POOL (`LLAMA_KV_REGION_POOL=<cells>`): the authoritative copy of the WHOLE context in a pinned host mirror, and a compact device pool of the pages a decode step actually attends to, which the QSA sparse read resolves through a page table (`GGML_OP_KV_POOL`). They are mutually exclusive by construction (the pool declines while a window is active) and they answer the same question from opposite ends: the window keeps the *newest* cells hot, the pool keeps the *attended* cells hot. Both report `is_streaming()`, so a streamed cache takes the sparse QSA decode arm (B2, below). ========================================================================== PART 1 -- the WINDOW (Goal A, promoted in r178) ========================================================================== Goal A of TODO ggml-org#118, promoted from the `wip/kv-residency` campaign. WHAT IT DOES. The KV cache's VRAM cost becomes a WINDOW of the newest `W` cells instead of `-c` cells: one VA reservation (a CUDA/HIP VMM region) holds the whole cache, the window's cells are backed by VRAM and everything below them by pinned system RAM. `set_rows`, the in-place rope shift, `state_write/read`, the kq mask and the FA kernels keep addressing one contiguous range, so no kernel and no op changes. The window slides with the watermark in whole map units, so a remap happens once per few thousand tokens and the apparatus itself is free (a zero-spill arm measures the same as plain). WHY. (a) A context that OOMs today runs: 27B Q8_0 `-c 262144` (8704 MiB of KV) now runs on one 32 GiB card at 128 MiB VRAM + 8576 MiB pinned host for the KV. (b) With host-resident MoE experts, the VRAM the KV does not need *yet* goes to the expert-cache arena: measured at `-c 262144`, `-n 2000`, `-ncmoe` = the model's full layer count, 51 433-token prompt, W at or above the run's depth = **+2.2 to +2.9 GiB of arena** (+3.9 to +6.7 points of residency) for free -- 122B-A10B Q4_K_XL +3.8 % decode and +4.7 % prefill, 35B-A3B Q8_0 -0.9 % decode and +3 % prefill; a `W` 35 k cells BELOW the run depth costs 11-26 % (the spill is read every token). OPT-IN, AND ONLY WHEN ASKED FOR. `LLAMA_KV_RESIDENT_CELLS=<cells>` (a number) or `=auto` (`--fit` sizes it, and only spills a context the user pinned with `-c`); unset/0 = no window. With no window the KV takes the PLAIN device buffer, so a run without the knob is byte-identical to a build without this block -- including its OOM (verified). `LLAMA_KV_SPILL_RAM_PCT` (85 % of MemAvailable) caps the pinned spill and widens the window rather than being OOM-killed; `LLAMA_KV_REGION=0` disables the provider; `LLAMA_KV_REGION_QUARANTINE=0` and `LLAMA_KV_REGION_DEBUG/TRACE/CANARY/DUMP` are the diagnosis switches. PURITY (the window). A spilled KV is numerically transparent: prefill-logit **KLD -0.000000 / 100.000 %** on a spilling 27B arm and -0.000000 / 99.994 % on a spilling Flash-Next (two KV caches: the attention KV and the QSA indexer), text byte-identical on 27B (f16 and q8_0), 4B, 35B-A3B and Flash-Next, and the state paths, the context-checkpoint path and the MTP verify widths all green on arms that provably spill. Two driver hazards are held: a kind flip zeroes a neighbouring live host mapping unless the released physical is held across the create (`LLAMA_KV_REGION_QUARANTINE`, default on -- `=0` reproduces the corruption), and every tensor in a windowed region is placed on the driver's map granularity so a slide step coincides with a mapping. An idle-slot park is REFUSED on a region-backed cache (the server then saves the slot to the prompt cache and clears it, which is byte-identical to the parking gate's reference) because a park moves cells above the region's mapped watermark through the copy engine, which faults the GPU. FIT. `--fit` sizes and reports the window (`auto`), or honours and reports a numeric `W`: the resident/spill split, the VRAM saved, and the per-token read cost at the model's full context from the backend's calibrated link rate. The fit identifies the KV's bytes by the region buffer TYPE, and its measurement context is a `no_alloc` probe that declines a window -- so the probe takes the region buffer explicitly (`llama_kv_region_set_probe`); without that the fit cannot see the KV, reports an over-budget config and aborts instead of sizing the window (the r178 regression). GATES (1 GPU, gfx1201): default path byte-identical (`5ba44647188f`) and still OOMs; VMM selftest PASS and FAIL with the hold disabled; windowed arms 305 `e2cea6fa6670` = plain at W=1024/2048/4096 (spilling at 1024: 128 MiB host), `QUARANTINE=0` -> 325 `fb65430049e9` (the hazard); `--fit` sizes `auto` (96680 of 262144 cells, 3210 MiB resident) and reports a numeric W; `gate-ckpt-reuse.sh` / `gate-state-pipe.sh` / MTP verify widths on spilling arms; `test-backend-ops -o FLASH_ATTN_QSA` 26/26; `check-gpu-faults.sh` clean. Not in this block: the campaign's Goal B (a sparse attended set) and Goal C (the MTP drafter ring, `LLAMA_SPEC_DRAFT_WINDOW`) -- both remain campaign work -- and A1 (the superseded two-base FA read). Records: `wip/kv-residency/A2-MIXED-BACKING.md` (§3.7.9, §3.7.11), `HANDOVER.md`. MULTI-DEVICE `--fit` (r181; the window itself reaches a tensor split in r204, at the end of this message): the KV-region glue is now safe on a Meta (tensor-split) device, and `auto`'s decision reaches the cache as a decision. r178 made default `--fit` abort on ANY `-sm tensor` run with more than one device: the fit's KV probes and the cache's own region lookups call `ggml_backend_dev_backend_reg(dev)` and hand it to `ggml_backend_reg_get_proc_address`, and a Meta device has no backend reg (`device->reg == NULL`), so `GGML_ASSERT(reg)` fired at model load. Three paths asserted: the fit probe (any run), the runtime buft lookup (a numeric W), and the spill budget/link lookups (a numeric W below `-c`). r181 makes a null reg read as "not provided" and declines the window with one message naming the tensor split (fit and cache), keeping the KV fully resident -- which is the r181 state; r204, below, is what makes the backend answer there. Three wiring defects in the same code, all visible on ONE device: - `auto`'s "no window needed" decision (0) was indistinguishable from "nobody decided", so the cache warned "--fit did not run" immediately after the fit had decided exactly that. `llama_kv_region_set_resident_cells` now records that a decision was made (`llama_kv_region_resident_cells_decided`), and a decided 0 is silent. - every run without the knob logged "the windowed KV is unavailable for this cache (no spilled cells)". That message now only fires when a window was actually requested and declined for a real reason. - the pinned-RAM ceiling clamp could raise W past the VRAM budget and then be reported as "does not make this fit either". It is now only taken while the wider window still meets the VRAM target; otherwise the fit says the ceiling cannot be served at this `-c` and drops the window (which the fit then fits by reducing the context). That ordering is not cosmetic: an intermediate form of this fix accepted a 235 GiB pinned spill plan for a 4B at `-c 8388608`, and creating it OOM-killed the test box. GATES (the window, gfx1201): `--fit on` (default) at 2 and 3 devices, `-sm tensor`, with no knob / a numeric W / `auto`, fit on and off: no assert, tokens produced, exactly one message per requested window. `-sm layer` 2 devices and 1 GPU still take the window per device (numeric W), and `auto` still sizes the 27B Q8_0 `-c 262144` q8_0 arm identically (123265 of 262144 cells, 4092.8 MiB resident / 4611.2 MiB spilling). One device, no knob: no KV message at all. Purity unchanged: plain vs a SPILLING windowed arm prefill-logit KLD 0.000000 / 99.990 % (q8_0 KV), greedy text byte-identical on that arm; 35B-A3B (1 GPU and 2-GPU `-sm tensor`), dense 27B and the canonical 27B Q8_0 prefill-logit gate (0.000000 / 100.000 %) byte-identical to r180; MTP Protocol A unchanged (tensor acceptance 0.60816 = 1937/3185, plain == draft-mtp); no GPU faults. ========================================================================== PART 2 -- the ATTENDANCE POOL (Goal B, promoted in r190) ========================================================================== The attention KV lives twice: its AUTHORITATIVE copy in a pinned host MIRROR (cell-indexed, so the writers, state_write/state_read, the K-shift, defrag and seq_park all work on it unchanged -- the writer rule) and a compact DEVICE POOL of pages of one indexer block (compress_ratio cells) with a page table block -> slot and its inverse. A decode step resolves its top-k selection through the table and fills the pages it missed from the mirror; the QSA reader gathers K/V at the pool slots while the mask stays cell-indexed. LLAMA_KV_REGION_POOL=<cells>, unset/0 = off = byte-identical. Contents. - ggml/src/ggml-cuda/kv-pool.{cu,cuh}: GGML_OP_KV_POOL. MARK sets use[slot] = epoch for every page this launch reads AND every page the batch just wrote (the graph's k_idxs), and queues the written ones for re-fill; CLAIM takes a slot for each DISTINCT missing block (the table CAS is the dedupe) and never takes a slot MARK protected; MAP+FILL writes each selected cell's pool position into the reader's K/V id list and copies the claimed and dirty pages from the mirror, K and V sharing slots. The epoch is a device counter incremented once per launch: the graph bakes pointers, never counters, and nothing is allocated per launch. - ggml-cuda.cu: the pool's pinned host mirror buffer type -- a DEVICE buffer type whose allocation is pinned host memory (`ROCm_Host` reports is_host, which would send the KV's writers and the FA read to the CPU on a discrete device), and its proc-address entry. - llama-kv-cache: the eligibility, the per-layer pool tensors (pool_k/pool_v, tbl, inv, use, one shared counter block), the resolve wiring into the QSA id list, kv_pool_serves() (a batch too wide for the pool takes the cell-indexed path), the teardown accounting (LLAMA_KV_POOL_STATS takes a PATH: a line on stderr sits inside the generated text), and memory_breakdown() charging the mirror to the host bucket so `--fit` does not reserve it as VRAM. - llama-memory-hybrid-idx / llama-memory-hybrid / llama-memory: the second id list (the K/V gather follows the page table while the mask stays cell-indexed), the flag threading, and the pool's byte accounting for `--fit` (llama_get_kv_pool_bytes()). - models/qwen4exp.cpp: a pooled cache reports is_streaming() and the sparse arm uses the pool's id list; the MTP draft's own cache is never pooled (its attention is dense). - llama-context / the async state copies: the mirror's buffer type is accepted by the batched save and restore (its bytes are host memory, staged through the pinned state_stage). - common/fit.cpp + src/llama-ext.h: the pool's split in --fit's arithmetic and report (the mirror is pinned host RAM, the pool is VRAM), and no context-reduction interpolation while the pool is active -- the pool's VRAM is fixed, so reducing -c frees nothing and the interpolation would divide by a near-zero bytes-per-context delta. Invariants, each one caught by the greedy text. 1. MARK then CLAIM: a claim must never evict a page the same launch reads. Without MARK the round-robin victim could be a page another row still needs (the text diverged ~400 chars in, and a pool larger than the whole cache hid it completely). 2. Claim ATTEMPTS are not distinct blocks: a slot per id attempt wrapped the cursor within one 4-row batch, so two blocks shared a slot and a just-resolved block went unresident. The table CAS dedupes first, so only distinct blocks consume a slot and kv_pool_serves() bounds the distinct count. 3. No transient scratch in a captured graph: the fill list lived in a ggml_cuda_pool_alloc that is freed at the end of the op, and a captured graph bakes the pointer, so a replay wrote into whatever op had been handed that block ("values verify clean, text differs run to run"). It lives in the counters tensor. 4. The mirror is AUTHORITATIVE: the writers land in it and a declared page is re-filled from it before the attention reads it, so an eviction costs nothing and nothing has to be invalidated -- except by a path that rewrites cells in place without going through the writers (the K-shift, a state restore), which calls kv_pool_invalidate(). 5. Eligibility is narrow on purpose: one stream, non-MLA, K and V both present, !v_trans, a uniform compress_ratio and cell geometry, no window active, a device-offloaded cache, and only the trunk context of a qwen4exp model. Anything else declines with one message and the KV is unchanged. 6. The pool is floored at one decode band's worth of blocks (8 x ceil(width/page) pages) so a verify batch cannot exhaust the slot budget, and the mirror is bounded at creation by LLAMA_KV_SPILL_RAM_PCT (it is pinned, non-swappable RAM) -- over the ceiling the pool is declined loudly instead of being OOM-killed. Measured (Flash-Next GSQ-IQ3_XXS, 1 GPU, -ncmoe 48, q8_0, the PLE flags, arms interleaved in one batch, -n 512, MTP depth 4; t/s and tokens/step): depth (ctx) dense sparse pool (204 MiB) text (-n 64) 5 298 (16 384) 72.09 71.58 71.27 pool == sparse: 332 chars dd1981213373 102 899 (131 072) 59.10 54.70 54.65 (5.3k / 51 475 references; dense differs) 180 035 (196 608) 48.94 43.16 43.41 pool == sparse: 861 chars 263c7f2be4d9 The pool lands ON the sparse ceiling at every depth (+0.5 / +0.6 / +0.58 %), so its placement is free and what remains against a resident KV (-7 % / -11 %) is the sparse decode arm's own indexer cost (block 11), not the KV's storage. A 204 MiB pool replaces the resident attention KV's 1 632 MiB at 103k / 2 448 MiB at 180k, and the freed VRAM goes to the expert arena: 103k plain decode, -n 2000, 23 579.8 -> 25 018.6 MiB (+1 438.8 MiB, +18 slots/table), expert hit 96.26 -> 97.02 %, cold reads 42.0 -> 31.6 GiB. The pool's own cost is 0.10-0.11 ms/token (mark/claim/map+fill) with fills 0.03-0.05 ms/step at 92-99 % hits, which is why a better page policy (LRU / F-LRU / a heat prior) is measured dead at this shape. Full numbers and the three-depth table: ../wip/kv-residency/BA-POOL-DESIGN.md §7-§8. PURITY (the pool). Greedy text pool == the resident sparse arm at 5.3k (332 dd1981213373), 51 475 depth (854 43b30de151b9) and 180k (861 263c7f2be4d9), with the dense arm differing as documented (GREEDY-PURITY §45/§63); LLAMA_KV_POOL_VERIFY=1 0 mismatches on every arm; gate-prefill-logits --ab "LLAMA_KV_REGION_POOL=..." 0.000000 / 100.000 % on the pool arm (base PPL 2.9225, bit-identical to the campaign's own base); gate-park-idle-slots, gate-ckpt-reuse and gate-state-pipe PASS on a pooled cache (the mirror is authoritative, which is what makes them trivial); test-backend-ops -o FLASH_ATTN_QSA pass; no GPU faults; and `--fit` accepts the arms that only fit with the pool (-ncmoe 21/22 at -c 262144: refused without it, accepted with it; -fitp moves 3 264 MiB from the device row to Host). ========================================================================== PART 3 -- a STREAMED cache takes the sparse decode arm (B2) ========================================================================== A cache that is streaming at the depth it reads -- a window the used extent has passed, or a pool -- takes the sparse QSA decode arm; a resident cache keeps the dense one. llama_kv_cache::is_streaming() plus the qwen4exp arm policy, LLAMA_QSA_DENSE_DECODE_STREAM=0 to restore the old behaviour. Measured on a spilled KV (Flash-Next IQ3_XXS, -ncmoe 48, q8_0, 1 GPU, -n 400, 2 reps): +34.3 % at 102 899 depth (23.42 -> 31.43 t/s) and +47.3 % at 180 035 (16.51 -> 24.31); a resident cache byte-identical (853 77a40bf40be1). This is a decode-ARM choice, i.e. a different attention regime (like GREEDY-PURITY §45/§63), so a streamed arm's text differs from the old dense-arm text by construction and a resident arm is the oracle. ========================================================================== DEFAULT OFF, for both placements ========================================================================== Neither knob is a speed feature on a config whose KV fits: the window costs the depth below W (11-26 %) and the pool costs the sparse-vs-dense gap (-7 % at 103k, -11 % at 180k). They are FITTABILITY features -- they turn an OOM into a run and they hand the freed VRAM to the expert arena -- so both are opt-in and both stay byte-identical, including the OOM, with their knobs unset. Do not "fix" the defaults. Goal C (the MTP drafter ring, TODO ggml-org#121) joins the same block -- it is the same claim applied to the draft context, and its default follows the delivery's own rule because it measures positive. `LLAMA_SPEC_DRAFT_WINDOW` gives the MTP draft context a sliding window instead of a `-c`-sized KV: unset or `auto` is the adaptive policy (a quarter of the context, clamped to [32768, 65536] cells), `0` is off (byte-identical to a build without it) and `N` is a cell count. The drafter reads its last few thousand tokens, so a window at or above that is free and one far below it costs 7-9 % of decode; the clamps keep it above that band, and the target verifies every token it proposes, so a truncated draft can only be slower. The ring is the shipped reclaim in `llama_kv_cache::find_slot` (`n_swa`), not a new allocator, and the derived kq mask stays valid -- its predicate compares each cell's POSITION, so a recycled cell reports its new one. The VRAM win needed one more piece: an embedded MTP head has no GGUF of its own, so the slab's draft reserve was the flat 3584 MiB and the freed VRAM never reached the expert arena. For an embedded MTP head with an active window the reserve is now derived from the model's own metadata with the weights zeroed (they are the target's) and the KV sized by the window: aux 3.50 -> 0.76 GiB, i.e. the arena gains ~2.8 GiB. A separate MTP draft GGUF (qwen4exp/Flash-Next) and an un-windowed run keep the flat constant exactly as before, and a declined arena preflight now re-evaluates when the smaller real value arrives instead of latching on the load-time estimate. Measured (1 GPU; one R9700; `-n 2000`/`-n 3000`; static depth 3; interleaved): * 35B-A3B Q8_0 `-ncmoe 48 -c 262144` q8_0 KV, 51 433-token prompt: arena 20 910 -> 23 715 MiB (residency 64.1 -> 72.7 %), decode 111.2 -> 113.7 t/s at `-n 3000` (+2.2 %; +2.8-4.9 % at `-n 2000`), prefill +3.4 %, drafts byte-for-byte the same count (1995/3011) -- the window truncates nothing the drafter used. * dense 27B UD-Q4_K_XL `-c 102400`, MTP Protocol A `-n 3000`, reasoning-pinned: layer 71.9 -> 72.1, tensor 72.6 -> 72.5 (neutral), acceptance 2083/2747 identical in all four arms. * target greedy text byte-identical across off/auto/4096, and plain == draft-mtp == draft-mtp(W=512) at `-c 16384` with a 5256-token prompt and 3000 generated tokens (10 158 chars, sha 99b267e8dc3e), i.e. no wrong answer under constant cell reuse. * gates on a windowed draft: `gate-park-idle-slots.sh` (35B, -ncmoe 48, `-c 65536`: 3 park moves, park == lazyoff), `gate-ckpt-reuse.sh` (4B, `-c 131072`: draft cache 33280 of 131072), `gate-state-pipe.sh` (35B, `-c 65536`: all five arms) -- all PASS with `MTP draft KV window = 32768 cells` in their logs. r194 corner fixes (found by a configuration battery against Flash-Next after r193): * LLAMA_KV_REGION_POOL is capped at the cache's own cell count. =1000000 on a 262144-cell context used to take a 12451 MiB device pool of 250000 pages where only 65536 blocks exist (never claimed, arena -4 GiB); it is now 3264 MiB / 65536 pages, and a small context clamps the same way. * the draft KV window sizes only the reserve of the cache it actually windows. A separate -md MTP head (Flash-Next) keeps its full -c cache, but the reserve was derived with the window: 921 MiB where the honest number is 1566 (kv 217 vs 862) at -c 262144, the under-charge direction. Embedded heads (qwen3.5/3.6/3.8) are unchanged (776 MiB on the 35B). The VRAM cliff at -c 262144 is documented (not code): the 768 MiB default headroom is one hipBLASLt workspace short for the first prefill, GGML_CUDA_SLAB_HEADROOM_MIB=1536 is 3/3 requests clean. Amendment (TODO ggml-org#129's sibling): `-nkvo` declines the window, and the streamed arm keys on the placement. The window is a DEVICE region plus a pinned host tail, but its guard did not test `offload`: with `-nkvo` the per-layer buffer is chosen inside `if (offload)` and stays plain pageable host memory, while the plan block still logged "WINDOWED KV ENABLED", reserved pinned-RAM spill budget and left `kv_resident_cells` set. `is_streaming()` then keyed the streamed (sparse) decode arm on that plan -- qwen4exp consumes it -- for a KV with no region at all. Measured: `-nkvo LLAMA_KV_RESIDENT_CELLS=64` built a plain `CPU KV buffer` of the whole context while announcing a 64-cell VRAM window. The window now declines once, with the reason (the pool already declines on `!offload`), so `-nkvo` means "no streamed placement"; `is_streaming()` tests `kv_region`, the placement actually taken, which also covers a device cache whose region buft the backend refused. Text is unchanged in every arm (the decline is a no-op: `-nkvo` + window already read as `-nkvo` alone). Amendment (issue ggml-org#264): the draft window is PER SEQUENCE, and under `--kv-unified` its cell count is `(win + one batch) x n_seq_max`. A unified cache holds every sequence in ONE stream, so the r193 sizing (`win + n_ubatch` cells) was shared by all of them: once the first sequence had filled its window the tail was all the room left, the tail is where that sequence's own ring writes, and a second sequence's first batch had no contiguous run to be placed in -- `find_slot` refused, and every request on that slot answered `decode() failed: failed to process speculative batch` (HTTP 500) while the drafter ran. Reported on `--kv-unified -np 2` with a 65 536-cell window at `-c 262144` after slot 0 held ~100k tokens; reproduced here with a forced 8192-cell window. A per-stream cache (no `--kv-unified`) already sized each stream separately and is unchanged. `llama_spec_draft_kv_cells()` is now the one geometry function -- the cache (`create_memory`), the slab's draft reserve estimate and the "is a window active" test in `common` all call it, so the reserve can never under-charge an allocation. It grants `win` per sequence plus one placeable batch (`(win + n_ubatch) * n_seq_max`, capped at the context), and DECLINES the window when that does not fit the context per sequence rather than lowering it to `per_seq - n_ubatch`: a window that small saves one batch of cells per sequence and masks the drafter's newest cells to do it. `llama_spec_draft_window_cells()` stays the policy (it is the per-sequence window). n_seq_max == 1 -- every `llama-cli`/`llama-bench` run -- measures exactly what it did (cells 1536 for a 1024-cell window at `-c 8192`), so no single-sequence arm changes at all. Measured (dense 27B, 1 GPU, `-np 2 --kv-unified`): the issue's scenario now answers both slots, and `scripts/gate-spec-draft-window.sh` (new) drives 6 requests over 2 slots with a 1024-cell window -- both rings wrapping, prompts full re-prefilled by swapping them between slots -- with output byte-identical to `LLAMA_SPEC_DRAFT_WINDOW=0` on every step and draft acceptance identical (17/36, 23/23). Greedy text `plain == draft-mtp == draft-mtp(W=1024) == draft-mtp(W=0)` (876 chars, sha 8c8fd395402f) at `-c 16384`. And the reserve now charges a per-STREAM (no `--kv-unified`) draft cache for every stream it allocates: `n_seq_max x` the per-stream cell count. Before, a multi-slot windowed MTP server without `--kv-unified` (35B-A3B `-ncmoe 40 -np 2 -c 8192`, window 1024: 2 x 1536 = 3072 cells allocated, 1536 charged) under-charged the slab's aux reserve by one stream's window -- the direction the reserve header calls dangerous. Measured: 3072 cells reported on both the unified and the per-stream arm now. ========================================================================== PART 4 -- `-sm tensor`: the window across a split (r204, `TODO` ggml-org#124) ========================================================================== A Meta (tensor-split) device carries no backend reg, so the r181 answer was "not provided" and the window was declined on every split. `TODO` ggml-org#124 designed the fix on a one-GPU box (`archive/work/kv-residency/ A6-TENSOR-SPLIT-WINDOW.md`, changes C1-C5); it is implemented and measured here, on a 3x R9700 host, and the decline is gone. * `ggml_backend_meta_kv_region_buft / _is_kv_buft / _grow` (new, `ggml-backend.h`): the Meta buffer type over the per-child region buffer types (ALL children or nothing), the is-a-region predicate `--fit` needs (the CUDA predicate is an identity on the child's `alloc_buffer` and cannot answer for a Meta buffer type), and a grow that fans out to every child. A child that cannot be reached is a REFUSAL (-1), never the 0 the CUDA hook returns for "not a region buffer": for a Meta buffer that 0 was a silent success on unmapped VA, i.e. a batch that page-faults the GPU. * `llama_kv_cache` resolves capability, the buffer type, the spill ceiling and the link through the Meta side; a MIRRORED cache (dsv4 / HRM, `llama_model::kv_cache_split_mirrored()`) declines the window with its own message, because every device holds the whole cache there (`n_devices x W x cell_bytes`) and the pinned-spill plan is per logical cache. * `common/fit.cpp` decides the window inside the tensor-split branch: charged at its PHYSICAL `W x cell_bytes` (what all devices commit together) against `min_i(target_i / ratio_i)`, which makes the aggregate check imply every device's (the loader shards the KV along the KV-head axis by the same ratio it shards the weights), and the Meta entry's margin is now the SUM of the children's `--fit-target`s (it was child 0's, so `(n_devices - 1) x target` silently vanished from the budget). The corrected KV term applies ONLY where a window is asked for: a run without `LLAMA_KV_RESIDENT_CELLS` keeps this branch's old arithmetic exactly, so the split's pre-existing `n_devices x` KV over-count is untouched outside the window arm. Four defects the arms found, fixed in the same block: 1. the init-time window commit was rounded up to a whole map unit past the tensor's own extent, and on a split each child is its own VA reservation -- the last tensor's inflated window was refused (`the KV window (4.00 MiB) could not be committed in VRAM on device 1`). Clamped to the region's END, in whole units (clamping to the tensor's own extent was tried first and is wrong: it leaves a short mapping off the unit grid and the next slide refuses to flip). 2. `ensure_span` refused a request that covered several WHOLE mappings; one batch can advance the boundary by more than one unit, and a 1 MiB unit is floored to the driver's 2 MiB granularity, so the request covered two mappings and aborted the batch. Whole mappings now flip one at a time; a request that covers a mapping only in PART is still refused (that loses bytes on this driver). 3. the batched state save issued a 2-D D2H per device and `hipMemcpy2DAsync` fails (`invalid argument`) when the range begins in a spilled region's pinned host mapping (the tensor-split checkpoint save aborted: `cache_k_l64 (view)`, 1024 B x 4782 rows). The region-backed directions of `get/set_tensor_2d_async` now go through the region buffer's own copy, ordered behind the compute stream like the pool mirror (a blocking default-stream copy does not wait for it, and the state saved mid-batch is torn). 4. that fallback's "contiguous rows = one copy" shortcut ignored the caller's destination pitch, which for a split splice is the FULL row, wider than one device's slice: the state-pipe gate failed on every cycle of all four async arms until a tight block required BOTH pitches to equal the width. Verified (gfx1201, `ROCBLAS_USE_HIPBLASLT=0` for every fresh-process pair): text byte-identical on `win3 == ref3` (3 devices, 4B, `057ea27b1009`) and `win2 == ref2 == win2mtp == ref2mtp` (2 devices, 27B, a 5246-token prompt, `7a7430617465`; draft acceptance 0.46154 in both MTP arms), also at a 1 MiB map unit; the spill is real on EVERY device (32 mapping flips each at 4 MiB, 128 at 1 MiB); a `-c 1048576` 2-device split (64 GiB of f16 KV) runs only because of the window; the single-device and `-nkvo` arms are unchanged; `--fit` on the split reports a WINDOWED cache and keeps the pinned `-c 524288` (plus the pinned-RAM ceiling's widen and drop arms, and `LLAMA_KV_REGION=0` silent); coherence identical to the r203 build on four no-window arms (3-GPU 4B, 2-GPU and 1-GPU 27B, 2-GPU host-expert 35B-A3B); prefill-logit 0.000000 / 100.000 %; Protocol A four-axis R/P/C/K 1.91x / 2.43x / 2.58x / 2.74x (acceptance 0.5869 / 0.8391 / 0.9112 / 0.9920, the r90 shape); `gate-spec-draft-window.sh` 6/6; `gate-state-pipe.sh` 2-GPU `-sm tensor` PASS with and without the window (the windowed arm failed before (3) and (4)); `GGML_CUDA_VMM_REGION_SELFTEST=1` PASS with a new multi-mapping arm; per-block build 1/1; `validate-set.sh` strict 16/16. Gate: `scripts/gate-kv-window-split.sh`. Record: `benchmarks/2026-11-01-kv-window-tensor-split-124.md`.
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Nov 5, 2026
…W (Goal A) and an attendance POOL (Goal B), both opt-in Goals A and B of TODO ggml-org#118, promoted from the `wip/kv-residency` campaign. This block is the delivery's "the KV does not have to be O(-c) of VRAM" work: TWO opt-in placements of the same cache, and each one is byte-identical to a build without it when its knob is unset. * the WINDOW (`LLAMA_KV_RESIDENT_CELLS=<cells>|auto`): the newest W cells stay in VRAM, everything older spills to pinned system RAM in the SAME VA reservation -- a positional window, no kernel or op change; * the POOL (`LLAMA_KV_REGION_POOL=<cells>`): the authoritative copy of the WHOLE context in a pinned host mirror, and a compact device pool of the pages a decode step actually attends to, which the QSA sparse read resolves through a page table (`GGML_OP_KV_POOL`). They are mutually exclusive by construction (the pool declines while a window is active) and they answer the same question from opposite ends: the window keeps the *newest* cells hot, the pool keeps the *attended* cells hot. Both report `is_streaming()`, so a streamed cache takes the sparse QSA decode arm (B2, below). ========================================================================== PART 1 -- the WINDOW (Goal A, promoted in r178) ========================================================================== Goal A of TODO ggml-org#118, promoted from the `wip/kv-residency` campaign. WHAT IT DOES. The KV cache's VRAM cost becomes a WINDOW of the newest `W` cells instead of `-c` cells: one VA reservation (a CUDA/HIP VMM region) holds the whole cache, the window's cells are backed by VRAM and everything below them by pinned system RAM. `set_rows`, the in-place rope shift, `state_write/read`, the kq mask and the FA kernels keep addressing one contiguous range, so no kernel and no op changes. The window slides with the watermark in whole map units, so a remap happens once per few thousand tokens and the apparatus itself is free (a zero-spill arm measures the same as plain). WHY. (a) A context that OOMs today runs: 27B Q8_0 `-c 262144` (8704 MiB of KV) now runs on one 32 GiB card at 128 MiB VRAM + 8576 MiB pinned host for the KV. (b) With host-resident MoE experts, the VRAM the KV does not need *yet* goes to the expert-cache arena: measured at `-c 262144`, `-n 2000`, `-ncmoe` = the model's full layer count, 51 433-token prompt, W at or above the run's depth = **+2.2 to +2.9 GiB of arena** (+3.9 to +6.7 points of residency) for free -- 122B-A10B Q4_K_XL +3.8 % decode and +4.7 % prefill, 35B-A3B Q8_0 -0.9 % decode and +3 % prefill; a `W` 35 k cells BELOW the run depth costs 11-26 % (the spill is read every token). OPT-IN, AND ONLY WHEN ASKED FOR. `LLAMA_KV_RESIDENT_CELLS=<cells>` (a number) or `=auto` (`--fit` sizes it, and only spills a context the user pinned with `-c`); unset/0 = no window. With no window the KV takes the PLAIN device buffer, so a run without the knob is byte-identical to a build without this block -- including its OOM (verified). `LLAMA_KV_SPILL_RAM_PCT` (85 % of MemAvailable) caps the pinned spill and widens the window rather than being OOM-killed; `LLAMA_KV_REGION=0` disables the provider; `LLAMA_KV_REGION_QUARANTINE=0` and `LLAMA_KV_REGION_DEBUG/TRACE/CANARY/DUMP` are the diagnosis switches. PURITY (the window). A spilled KV is numerically transparent: prefill-logit **KLD -0.000000 / 100.000 %** on a spilling 27B arm and -0.000000 / 99.994 % on a spilling Flash-Next (two KV caches: the attention KV and the QSA indexer), text byte-identical on 27B (f16 and q8_0), 4B, 35B-A3B and Flash-Next, and the state paths, the context-checkpoint path and the MTP verify widths all green on arms that provably spill. Two driver hazards are held: a kind flip zeroes a neighbouring live host mapping unless the released physical is held across the create (`LLAMA_KV_REGION_QUARANTINE`, default on -- `=0` reproduces the corruption), and every tensor in a windowed region is placed on the driver's map granularity so a slide step coincides with a mapping. An idle-slot park is REFUSED on a region-backed cache (the server then saves the slot to the prompt cache and clears it, which is byte-identical to the parking gate's reference) because a park moves cells above the region's mapped watermark through the copy engine, which faults the GPU. FIT. `--fit` sizes and reports the window (`auto`), or honours and reports a numeric `W`: the resident/spill split, the VRAM saved, and the per-token read cost at the model's full context from the backend's calibrated link rate. The fit identifies the KV's bytes by the region buffer TYPE, and its measurement context is a `no_alloc` probe that declines a window -- so the probe takes the region buffer explicitly (`llama_kv_region_set_probe`); without that the fit cannot see the KV, reports an over-budget config and aborts instead of sizing the window (the r178 regression). GATES (1 GPU, gfx1201): default path byte-identical (`5ba44647188f`) and still OOMs; VMM selftest PASS and FAIL with the hold disabled; windowed arms 305 `e2cea6fa6670` = plain at W=1024/2048/4096 (spilling at 1024: 128 MiB host), `QUARANTINE=0` -> 325 `fb65430049e9` (the hazard); `--fit` sizes `auto` (96680 of 262144 cells, 3210 MiB resident) and reports a numeric W; `gate-ckpt-reuse.sh` / `gate-state-pipe.sh` / MTP verify widths on spilling arms; `test-backend-ops -o FLASH_ATTN_QSA` 26/26; `check-gpu-faults.sh` clean. Not in this block: the campaign's Goal B (a sparse attended set) and Goal C (the MTP drafter ring, `LLAMA_SPEC_DRAFT_WINDOW`) -- both remain campaign work -- and A1 (the superseded two-base FA read). Records: `wip/kv-residency/A2-MIXED-BACKING.md` (§3.7.9, §3.7.11), `HANDOVER.md`. MULTI-DEVICE `--fit` (r181; the window itself reaches a tensor split in r204, at the end of this message): the KV-region glue is now safe on a Meta (tensor-split) device, and `auto`'s decision reaches the cache as a decision. r178 made default `--fit` abort on ANY `-sm tensor` run with more than one device: the fit's KV probes and the cache's own region lookups call `ggml_backend_dev_backend_reg(dev)` and hand it to `ggml_backend_reg_get_proc_address`, and a Meta device has no backend reg (`device->reg == NULL`), so `GGML_ASSERT(reg)` fired at model load. Three paths asserted: the fit probe (any run), the runtime buft lookup (a numeric W), and the spill budget/link lookups (a numeric W below `-c`). r181 makes a null reg read as "not provided" and declines the window with one message naming the tensor split (fit and cache), keeping the KV fully resident -- which is the r181 state; r204, below, is what makes the backend answer there. Three wiring defects in the same code, all visible on ONE device: - `auto`'s "no window needed" decision (0) was indistinguishable from "nobody decided", so the cache warned "--fit did not run" immediately after the fit had decided exactly that. `llama_kv_region_set_resident_cells` now records that a decision was made (`llama_kv_region_resident_cells_decided`), and a decided 0 is silent. - every run without the knob logged "the windowed KV is unavailable for this cache (no spilled cells)". That message now only fires when a window was actually requested and declined for a real reason. - the pinned-RAM ceiling clamp could raise W past the VRAM budget and then be reported as "does not make this fit either". It is now only taken while the wider window still meets the VRAM target; otherwise the fit says the ceiling cannot be served at this `-c` and drops the window (which the fit then fits by reducing the context). That ordering is not cosmetic: an intermediate form of this fix accepted a 235 GiB pinned spill plan for a 4B at `-c 8388608`, and creating it OOM-killed the test box. GATES (the window, gfx1201): `--fit on` (default) at 2 and 3 devices, `-sm tensor`, with no knob / a numeric W / `auto`, fit on and off: no assert, tokens produced, exactly one message per requested window. `-sm layer` 2 devices and 1 GPU still take the window per device (numeric W), and `auto` still sizes the 27B Q8_0 `-c 262144` q8_0 arm identically (123265 of 262144 cells, 4092.8 MiB resident / 4611.2 MiB spilling). One device, no knob: no KV message at all. Purity unchanged: plain vs a SPILLING windowed arm prefill-logit KLD 0.000000 / 99.990 % (q8_0 KV), greedy text byte-identical on that arm; 35B-A3B (1 GPU and 2-GPU `-sm tensor`), dense 27B and the canonical 27B Q8_0 prefill-logit gate (0.000000 / 100.000 %) byte-identical to r180; MTP Protocol A unchanged (tensor acceptance 0.60816 = 1937/3185, plain == draft-mtp); no GPU faults. ========================================================================== PART 2 -- the ATTENDANCE POOL (Goal B, promoted in r190) ========================================================================== The attention KV lives twice: its AUTHORITATIVE copy in a pinned host MIRROR (cell-indexed, so the writers, state_write/state_read, the K-shift, defrag and seq_park all work on it unchanged -- the writer rule) and a compact DEVICE POOL of pages of one indexer block (compress_ratio cells) with a page table block -> slot and its inverse. A decode step resolves its top-k selection through the table and fills the pages it missed from the mirror; the QSA reader gathers K/V at the pool slots while the mask stays cell-indexed. LLAMA_KV_REGION_POOL=<cells>, unset/0 = off = byte-identical. Contents. - ggml/src/ggml-cuda/kv-pool.{cu,cuh}: GGML_OP_KV_POOL. MARK sets use[slot] = epoch for every page this launch reads AND every page the batch just wrote (the graph's k_idxs), and queues the written ones for re-fill; CLAIM takes a slot for each DISTINCT missing block (the table CAS is the dedupe) and never takes a slot MARK protected; MAP+FILL writes each selected cell's pool position into the reader's K/V id list and copies the claimed and dirty pages from the mirror, K and V sharing slots. The epoch is a device counter incremented once per launch: the graph bakes pointers, never counters, and nothing is allocated per launch. - ggml-cuda.cu: the pool's pinned host mirror buffer type -- a DEVICE buffer type whose allocation is pinned host memory (`ROCm_Host` reports is_host, which would send the KV's writers and the FA read to the CPU on a discrete device), and its proc-address entry. - llama-kv-cache: the eligibility, the per-layer pool tensors (pool_k/pool_v, tbl, inv, use, one shared counter block), the resolve wiring into the QSA id list, kv_pool_serves() (a batch too wide for the pool takes the cell-indexed path), the teardown accounting (LLAMA_KV_POOL_STATS takes a PATH: a line on stderr sits inside the generated text), and memory_breakdown() charging the mirror to the host bucket so `--fit` does not reserve it as VRAM. - llama-memory-hybrid-idx / llama-memory-hybrid / llama-memory: the second id list (the K/V gather follows the page table while the mask stays cell-indexed), the flag threading, and the pool's byte accounting for `--fit` (llama_get_kv_pool_bytes()). - models/qwen4exp.cpp: a pooled cache reports is_streaming() and the sparse arm uses the pool's id list; the MTP draft's own cache is never pooled (its attention is dense). - llama-context / the async state copies: the mirror's buffer type is accepted by the batched save and restore (its bytes are host memory, staged through the pinned state_stage). - common/fit.cpp + src/llama-ext.h: the pool's split in --fit's arithmetic and report (the mirror is pinned host RAM, the pool is VRAM), and no context-reduction interpolation while the pool is active -- the pool's VRAM is fixed, so reducing -c frees nothing and the interpolation would divide by a near-zero bytes-per-context delta. Invariants, each one caught by the greedy text. 1. MARK then CLAIM: a claim must never evict a page the same launch reads. Without MARK the round-robin victim could be a page another row still needs (the text diverged ~400 chars in, and a pool larger than the whole cache hid it completely). 2. Claim ATTEMPTS are not distinct blocks: a slot per id attempt wrapped the cursor within one 4-row batch, so two blocks shared a slot and a just-resolved block went unresident. The table CAS dedupes first, so only distinct blocks consume a slot and kv_pool_serves() bounds the distinct count. 3. No transient scratch in a captured graph: the fill list lived in a ggml_cuda_pool_alloc that is freed at the end of the op, and a captured graph bakes the pointer, so a replay wrote into whatever op had been handed that block ("values verify clean, text differs run to run"). It lives in the counters tensor. 4. The mirror is AUTHORITATIVE: the writers land in it and a declared page is re-filled from it before the attention reads it, so an eviction costs nothing and nothing has to be invalidated -- except by a path that rewrites cells in place without going through the writers (the K-shift, a state restore), which calls kv_pool_invalidate(). 5. Eligibility is narrow on purpose: one stream, non-MLA, K and V both present, !v_trans, a uniform compress_ratio and cell geometry, no window active, a device-offloaded cache, and only the trunk context of a qwen4exp model. Anything else declines with one message and the KV is unchanged. 6. The pool is floored at one decode band's worth of blocks (8 x ceil(width/page) pages) so a verify batch cannot exhaust the slot budget, and the mirror is bounded at creation by LLAMA_KV_SPILL_RAM_PCT (it is pinned, non-swappable RAM) -- over the ceiling the pool is declined loudly instead of being OOM-killed. Measured (Flash-Next GSQ-IQ3_XXS, 1 GPU, -ncmoe 48, q8_0, the PLE flags, arms interleaved in one batch, -n 512, MTP depth 4; t/s and tokens/step): depth (ctx) dense sparse pool (204 MiB) text (-n 64) 5 298 (16 384) 72.09 71.58 71.27 pool == sparse: 332 chars dd1981213373 102 899 (131 072) 59.10 54.70 54.65 (5.3k / 51 475 references; dense differs) 180 035 (196 608) 48.94 43.16 43.41 pool == sparse: 861 chars 263c7f2be4d9 The pool lands ON the sparse ceiling at every depth (+0.5 / +0.6 / +0.58 %), so its placement is free and what remains against a resident KV (-7 % / -11 %) is the sparse decode arm's own indexer cost (block 11), not the KV's storage. A 204 MiB pool replaces the resident attention KV's 1 632 MiB at 103k / 2 448 MiB at 180k, and the freed VRAM goes to the expert arena: 103k plain decode, -n 2000, 23 579.8 -> 25 018.6 MiB (+1 438.8 MiB, +18 slots/table), expert hit 96.26 -> 97.02 %, cold reads 42.0 -> 31.6 GiB. The pool's own cost is 0.10-0.11 ms/token (mark/claim/map+fill) with fills 0.03-0.05 ms/step at 92-99 % hits, which is why a better page policy (LRU / F-LRU / a heat prior) is measured dead at this shape. Full numbers and the three-depth table: ../wip/kv-residency/BA-POOL-DESIGN.md §7-§8. PURITY (the pool). Greedy text pool == the resident sparse arm at 5.3k (332 dd1981213373), 51 475 depth (854 43b30de151b9) and 180k (861 263c7f2be4d9), with the dense arm differing as documented (GREEDY-PURITY §45/§63); LLAMA_KV_POOL_VERIFY=1 0 mismatches on every arm; gate-prefill-logits --ab "LLAMA_KV_REGION_POOL=..." 0.000000 / 100.000 % on the pool arm (base PPL 2.9225, bit-identical to the campaign's own base); gate-park-idle-slots, gate-ckpt-reuse and gate-state-pipe PASS on a pooled cache (the mirror is authoritative, which is what makes them trivial); test-backend-ops -o FLASH_ATTN_QSA pass; no GPU faults; and `--fit` accepts the arms that only fit with the pool (-ncmoe 21/22 at -c 262144: refused without it, accepted with it; -fitp moves 3 264 MiB from the device row to Host). ========================================================================== PART 3 -- a STREAMED cache takes the sparse decode arm (B2) ========================================================================== A cache that is streaming at the depth it reads -- a window the used extent has passed, or a pool -- takes the sparse QSA decode arm; a resident cache keeps the dense one. llama_kv_cache::is_streaming() plus the qwen4exp arm policy, LLAMA_QSA_DENSE_DECODE_STREAM=0 to restore the old behaviour. Measured on a spilled KV (Flash-Next IQ3_XXS, -ncmoe 48, q8_0, 1 GPU, -n 400, 2 reps): +34.3 % at 102 899 depth (23.42 -> 31.43 t/s) and +47.3 % at 180 035 (16.51 -> 24.31); a resident cache byte-identical (853 77a40bf40be1). This is a decode-ARM choice, i.e. a different attention regime (like GREEDY-PURITY §45/§63), so a streamed arm's text differs from the old dense-arm text by construction and a resident arm is the oracle. ========================================================================== DEFAULT OFF, for both placements ========================================================================== Neither knob is a speed feature on a config whose KV fits: the window costs the depth below W (11-26 %) and the pool costs the sparse-vs-dense gap (-7 % at 103k, -11 % at 180k). They are FITTABILITY features -- they turn an OOM into a run and they hand the freed VRAM to the expert arena -- so both are opt-in and both stay byte-identical, including the OOM, with their knobs unset. Do not "fix" the defaults. Goal C (the MTP drafter ring, TODO ggml-org#121) joins the same block -- it is the same claim applied to the draft context, and its default follows the delivery's own rule because it measures positive. `LLAMA_SPEC_DRAFT_WINDOW` gives the MTP draft context a sliding window instead of a `-c`-sized KV: unset or `auto` is the adaptive policy (a quarter of the context, clamped to [32768, 65536] cells), `0` is off (byte-identical to a build without it) and `N` is a cell count. The drafter reads its last few thousand tokens, so a window at or above that is free and one far below it costs 7-9 % of decode; the clamps keep it above that band, and the target verifies every token it proposes, so a truncated draft can only be slower. The ring is the shipped reclaim in `llama_kv_cache::find_slot` (`n_swa`), not a new allocator, and the derived kq mask stays valid -- its predicate compares each cell's POSITION, so a recycled cell reports its new one. The VRAM win needed one more piece: an embedded MTP head has no GGUF of its own, so the slab's draft reserve was the flat 3584 MiB and the freed VRAM never reached the expert arena. For an embedded MTP head with an active window the reserve is now derived from the model's own metadata with the weights zeroed (they are the target's) and the KV sized by the window: aux 3.50 -> 0.76 GiB, i.e. the arena gains ~2.8 GiB. A separate MTP draft GGUF (qwen4exp/Flash-Next) and an un-windowed run keep the flat constant exactly as before, and a declined arena preflight now re-evaluates when the smaller real value arrives instead of latching on the load-time estimate. Measured (1 GPU; one R9700; `-n 2000`/`-n 3000`; static depth 3; interleaved): * 35B-A3B Q8_0 `-ncmoe 48 -c 262144` q8_0 KV, 51 433-token prompt: arena 20 910 -> 23 715 MiB (residency 64.1 -> 72.7 %), decode 111.2 -> 113.7 t/s at `-n 3000` (+2.2 %; +2.8-4.9 % at `-n 2000`), prefill +3.4 %, drafts byte-for-byte the same count (1995/3011) -- the window truncates nothing the drafter used. * dense 27B UD-Q4_K_XL `-c 102400`, MTP Protocol A `-n 3000`, reasoning-pinned: layer 71.9 -> 72.1, tensor 72.6 -> 72.5 (neutral), acceptance 2083/2747 identical in all four arms. * target greedy text byte-identical across off/auto/4096, and plain == draft-mtp == draft-mtp(W=512) at `-c 16384` with a 5256-token prompt and 3000 generated tokens (10 158 chars, sha 99b267e8dc3e), i.e. no wrong answer under constant cell reuse. * gates on a windowed draft: `gate-park-idle-slots.sh` (35B, -ncmoe 48, `-c 65536`: 3 park moves, park == lazyoff), `gate-ckpt-reuse.sh` (4B, `-c 131072`: draft cache 33280 of 131072), `gate-state-pipe.sh` (35B, `-c 65536`: all five arms) -- all PASS with `MTP draft KV window = 32768 cells` in their logs. r194 corner fixes (found by a configuration battery against Flash-Next after r193): * LLAMA_KV_REGION_POOL is capped at the cache's own cell count. =1000000 on a 262144-cell context used to take a 12451 MiB device pool of 250000 pages where only 65536 blocks exist (never claimed, arena -4 GiB); it is now 3264 MiB / 65536 pages, and a small context clamps the same way. * the draft KV window sizes only the reserve of the cache it actually windows. A separate -md MTP head (Flash-Next) keeps its full -c cache, but the reserve was derived with the window: 921 MiB where the honest number is 1566 (kv 217 vs 862) at -c 262144, the under-charge direction. Embedded heads (qwen3.5/3.6/3.8) are unchanged (776 MiB on the 35B). The VRAM cliff at -c 262144 is documented (not code): the 768 MiB default headroom is one hipBLASLt workspace short for the first prefill, GGML_CUDA_SLAB_HEADROOM_MIB=1536 is 3/3 requests clean. Amendment (TODO ggml-org#129's sibling): `-nkvo` declines the window, and the streamed arm keys on the placement. The window is a DEVICE region plus a pinned host tail, but its guard did not test `offload`: with `-nkvo` the per-layer buffer is chosen inside `if (offload)` and stays plain pageable host memory, while the plan block still logged "WINDOWED KV ENABLED", reserved pinned-RAM spill budget and left `kv_resident_cells` set. `is_streaming()` then keyed the streamed (sparse) decode arm on that plan -- qwen4exp consumes it -- for a KV with no region at all. Measured: `-nkvo LLAMA_KV_RESIDENT_CELLS=64` built a plain `CPU KV buffer` of the whole context while announcing a 64-cell VRAM window. The window now declines once, with the reason (the pool already declines on `!offload`), so `-nkvo` means "no streamed placement"; `is_streaming()` tests `kv_region`, the placement actually taken, which also covers a device cache whose region buft the backend refused. Text is unchanged in every arm (the decline is a no-op: `-nkvo` + window already read as `-nkvo` alone). Amendment (issue ggml-org#264): the draft window is PER SEQUENCE, and under `--kv-unified` its cell count is `(win + one batch) x n_seq_max`. A unified cache holds every sequence in ONE stream, so the r193 sizing (`win + n_ubatch` cells) was shared by all of them: once the first sequence had filled its window the tail was all the room left, the tail is where that sequence's own ring writes, and a second sequence's first batch had no contiguous run to be placed in -- `find_slot` refused, and every request on that slot answered `decode() failed: failed to process speculative batch` (HTTP 500) while the drafter ran. Reported on `--kv-unified -np 2` with a 65 536-cell window at `-c 262144` after slot 0 held ~100k tokens; reproduced here with a forced 8192-cell window. A per-stream cache (no `--kv-unified`) already sized each stream separately and is unchanged. `llama_spec_draft_kv_cells()` is now the one geometry function -- the cache (`create_memory`), the slab's draft reserve estimate and the "is a window active" test in `common` all call it, so the reserve can never under-charge an allocation. It grants `win` per sequence plus one placeable batch (`(win + n_ubatch) * n_seq_max`, capped at the context), and DECLINES the window when that does not fit the context per sequence rather than lowering it to `per_seq - n_ubatch`: a window that small saves one batch of cells per sequence and masks the drafter's newest cells to do it. `llama_spec_draft_window_cells()` stays the policy (it is the per-sequence window). n_seq_max == 1 -- every `llama-cli`/`llama-bench` run -- measures exactly what it did (cells 1536 for a 1024-cell window at `-c 8192`), so no single-sequence arm changes at all. Measured (dense 27B, 1 GPU, `-np 2 --kv-unified`): the issue's scenario now answers both slots, and `scripts/gate-spec-draft-window.sh` (new) drives 6 requests over 2 slots with a 1024-cell window -- both rings wrapping, prompts full re-prefilled by swapping them between slots -- with output byte-identical to `LLAMA_SPEC_DRAFT_WINDOW=0` on every step and draft acceptance identical (17/36, 23/23). Greedy text `plain == draft-mtp == draft-mtp(W=1024) == draft-mtp(W=0)` (876 chars, sha 8c8fd395402f) at `-c 16384`. And the reserve now charges a per-STREAM (no `--kv-unified`) draft cache for every stream it allocates: `n_seq_max x` the per-stream cell count. Before, a multi-slot windowed MTP server without `--kv-unified` (35B-A3B `-ncmoe 40 -np 2 -c 8192`, window 1024: 2 x 1536 = 3072 cells allocated, 1536 charged) under-charged the slab's aux reserve by one stream's window -- the direction the reserve header calls dangerous. Measured: 3072 cells reported on both the unified and the per-stream arm now. ========================================================================== PART 4 -- `-sm tensor`: the window across a split (r204, `TODO` ggml-org#124) ========================================================================== A Meta (tensor-split) device carries no backend reg, so the r181 answer was "not provided" and the window was declined on every split. `TODO` ggml-org#124 designed the fix on a one-GPU box (`archive/work/kv-residency/ A6-TENSOR-SPLIT-WINDOW.md`, changes C1-C5); it is implemented and measured here, on a 3x R9700 host, and the decline is gone. * `ggml_backend_meta_kv_region_buft / _is_kv_buft / _grow` (new, `ggml-backend.h`): the Meta buffer type over the per-child region buffer types (ALL children or nothing), the is-a-region predicate `--fit` needs (the CUDA predicate is an identity on the child's `alloc_buffer` and cannot answer for a Meta buffer type), and a grow that fans out to every child. A child that cannot be reached is a REFUSAL (-1), never the 0 the CUDA hook returns for "not a region buffer": for a Meta buffer that 0 was a silent success on unmapped VA, i.e. a batch that page-faults the GPU. * `llama_kv_cache` resolves capability, the buffer type, the spill ceiling and the link through the Meta side; a MIRRORED cache (dsv4 / HRM, `llama_model::kv_cache_split_mirrored()`) declines the window with its own message, because every device holds the whole cache there (`n_devices x W x cell_bytes`) and the pinned-spill plan is per logical cache. * `common/fit.cpp` decides the window inside the tensor-split branch: charged at its PHYSICAL `W x cell_bytes` (what all devices commit together) against `min_i(target_i / ratio_i)`, which makes the aggregate check imply every device's (the loader shards the KV along the KV-head axis by the same ratio it shards the weights), and the Meta entry's margin is now the SUM of the children's `--fit-target`s (it was child 0's, so `(n_devices - 1) x target` silently vanished from the budget). The corrected KV term applies ONLY where a window is asked for: a run without `LLAMA_KV_RESIDENT_CELLS` keeps this branch's old arithmetic exactly, so the split's pre-existing `n_devices x` KV over-count is untouched outside the window arm. Four defects the arms found, fixed in the same block: 1. the init-time window commit was rounded up to a whole map unit past the tensor's own extent, and on a split each child is its own VA reservation -- the last tensor's inflated window was refused (`the KV window (4.00 MiB) could not be committed in VRAM on device 1`). Clamped to the region's END, in whole units (clamping to the tensor's own extent was tried first and is wrong: it leaves a short mapping off the unit grid and the next slide refuses to flip). 2. `ensure_span` refused a request that covered several WHOLE mappings; one batch can advance the boundary by more than one unit, and a 1 MiB unit is floored to the driver's 2 MiB granularity, so the request covered two mappings and aborted the batch. Whole mappings now flip one at a time; a request that covers a mapping only in PART is still refused (that loses bytes on this driver). 3. the batched state save issued a 2-D D2H per device and `hipMemcpy2DAsync` fails (`invalid argument`) when the range begins in a spilled region's pinned host mapping (the tensor-split checkpoint save aborted: `cache_k_l64 (view)`, 1024 B x 4782 rows). The region-backed directions of `get/set_tensor_2d_async` now go through the region buffer's own copy, ordered behind the compute stream like the pool mirror (a blocking default-stream copy does not wait for it, and the state saved mid-batch is torn). 4. that fallback's "contiguous rows = one copy" shortcut ignored the caller's destination pitch, which for a split splice is the FULL row, wider than one device's slice: the state-pipe gate failed on every cycle of all four async arms until a tight block required BOTH pitches to equal the width. Verified (gfx1201, `ROCBLAS_USE_HIPBLASLT=0` for every fresh-process pair): text byte-identical on `win3 == ref3` (3 devices, 4B, `057ea27b1009`) and `win2 == ref2 == win2mtp == ref2mtp` (2 devices, 27B, a 5246-token prompt, `7a7430617465`; draft acceptance 0.46154 in both MTP arms), also at a 1 MiB map unit; the spill is real on EVERY device (32 mapping flips each at 4 MiB, 128 at 1 MiB); a `-c 1048576` 2-device split (64 GiB of f16 KV) runs only because of the window; the single-device and `-nkvo` arms are unchanged; `--fit` on the split reports a WINDOWED cache and keeps the pinned `-c 524288` (plus the pinned-RAM ceiling's widen and drop arms, and `LLAMA_KV_REGION=0` silent); coherence identical to the r203 build on four no-window arms (3-GPU 4B, 2-GPU and 1-GPU 27B, 2-GPU host-expert 35B-A3B); prefill-logit 0.000000 / 100.000 %; Protocol A four-axis R/P/C/K 1.91x / 2.43x / 2.58x / 2.74x (acceptance 0.5869 / 0.8391 / 0.9112 / 0.9920, the r90 shape); `gate-spec-draft-window.sh` 6/6; `gate-state-pipe.sh` 2-GPU `-sm tensor` PASS with and without the window (the windowed arm failed before (3) and (4)); `GGML_CUDA_VMM_REGION_SELFTEST=1` PASS with a new multi-mapping arm; per-block build 1/1; `validate-set.sh` strict 16/16. Gate: `scripts/gate-kv-window-split.sh`. Record: `benchmarks/2026-11-01-kv-window-tensor-split-124.md`.
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Nov 5, 2026
…W (Goal A) and an attendance POOL (Goal B), both opt-in Goals A and B of TODO ggml-org#118, promoted from the `wip/kv-residency` campaign. This block is the delivery's "the KV does not have to be O(-c) of VRAM" work: TWO opt-in placements of the same cache, and each one is byte-identical to a build without it when its knob is unset. * the WINDOW (`LLAMA_KV_RESIDENT_CELLS=<cells>|auto`): the newest W cells stay in VRAM, everything older spills to pinned system RAM in the SAME VA reservation -- a positional window, no kernel or op change; * the POOL (`LLAMA_KV_REGION_POOL=<cells>`): the authoritative copy of the WHOLE context in a pinned host mirror, and a compact device pool of the pages a decode step actually attends to, which the QSA sparse read resolves through a page table (`GGML_OP_KV_POOL`). They are mutually exclusive by construction (the pool declines while a window is active) and they answer the same question from opposite ends: the window keeps the *newest* cells hot, the pool keeps the *attended* cells hot. Both report `is_streaming()`, so a streamed cache takes the sparse QSA decode arm (B2, below). ========================================================================== PART 1 -- the WINDOW (Goal A, promoted in r178) ========================================================================== Goal A of TODO ggml-org#118, promoted from the `wip/kv-residency` campaign. WHAT IT DOES. The KV cache's VRAM cost becomes a WINDOW of the newest `W` cells instead of `-c` cells: one VA reservation (a CUDA/HIP VMM region) holds the whole cache, the window's cells are backed by VRAM and everything below them by pinned system RAM. `set_rows`, the in-place rope shift, `state_write/read`, the kq mask and the FA kernels keep addressing one contiguous range, so no kernel and no op changes. The window slides with the watermark in whole map units, so a remap happens once per few thousand tokens and the apparatus itself is free (a zero-spill arm measures the same as plain). WHY. (a) A context that OOMs today runs: 27B Q8_0 `-c 262144` (8704 MiB of KV) now runs on one 32 GiB card at 128 MiB VRAM + 8576 MiB pinned host for the KV. (b) With host-resident MoE experts, the VRAM the KV does not need *yet* goes to the expert-cache arena: measured at `-c 262144`, `-n 2000`, `-ncmoe` = the model's full layer count, 51 433-token prompt, W at or above the run's depth = **+2.2 to +2.9 GiB of arena** (+3.9 to +6.7 points of residency) for free -- 122B-A10B Q4_K_XL +3.8 % decode and +4.7 % prefill, 35B-A3B Q8_0 -0.9 % decode and +3 % prefill; a `W` 35 k cells BELOW the run depth costs 11-26 % (the spill is read every token). OPT-IN, AND ONLY WHEN ASKED FOR. `LLAMA_KV_RESIDENT_CELLS=<cells>` (a number) or `=auto` (`--fit` sizes it, and only spills a context the user pinned with `-c`); unset/0 = no window. With no window the KV takes the PLAIN device buffer, so a run without the knob is byte-identical to a build without this block -- including its OOM (verified). `LLAMA_KV_SPILL_RAM_PCT` (85 % of MemAvailable) caps the pinned spill and widens the window rather than being OOM-killed; `LLAMA_KV_REGION=0` disables the provider; `LLAMA_KV_REGION_QUARANTINE=0` and `LLAMA_KV_REGION_DEBUG/TRACE/CANARY/DUMP` are the diagnosis switches. PURITY (the window). A spilled KV is numerically transparent: prefill-logit **KLD -0.000000 / 100.000 %** on a spilling 27B arm and -0.000000 / 99.994 % on a spilling Flash-Next (two KV caches: the attention KV and the QSA indexer), text byte-identical on 27B (f16 and q8_0), 4B, 35B-A3B and Flash-Next, and the state paths, the context-checkpoint path and the MTP verify widths all green on arms that provably spill. Two driver hazards are held: a kind flip zeroes a neighbouring live host mapping unless the released physical is held across the create (`LLAMA_KV_REGION_QUARANTINE`, default on -- `=0` reproduces the corruption), and every tensor in a windowed region is placed on the driver's map granularity so a slide step coincides with a mapping. An idle-slot park is REFUSED on a region-backed cache (the server then saves the slot to the prompt cache and clears it, which is byte-identical to the parking gate's reference) because a park moves cells above the region's mapped watermark through the copy engine, which faults the GPU. FIT. `--fit` sizes and reports the window (`auto`), or honours and reports a numeric `W`: the resident/spill split, the VRAM saved, and the per-token read cost at the model's full context from the backend's calibrated link rate. The fit identifies the KV's bytes by the region buffer TYPE, and its measurement context is a `no_alloc` probe that declines a window -- so the probe takes the region buffer explicitly (`llama_kv_region_set_probe`); without that the fit cannot see the KV, reports an over-budget config and aborts instead of sizing the window (the r178 regression). GATES (1 GPU, gfx1201): default path byte-identical (`5ba44647188f`) and still OOMs; VMM selftest PASS and FAIL with the hold disabled; windowed arms 305 `e2cea6fa6670` = plain at W=1024/2048/4096 (spilling at 1024: 128 MiB host), `QUARANTINE=0` -> 325 `fb65430049e9` (the hazard); `--fit` sizes `auto` (96680 of 262144 cells, 3210 MiB resident) and reports a numeric W; `gate-ckpt-reuse.sh` / `gate-state-pipe.sh` / MTP verify widths on spilling arms; `test-backend-ops -o FLASH_ATTN_QSA` 26/26; `check-gpu-faults.sh` clean. Not in this block: the campaign's Goal B (a sparse attended set) and Goal C (the MTP drafter ring, `LLAMA_SPEC_DRAFT_WINDOW`) -- both remain campaign work -- and A1 (the superseded two-base FA read). Records: `wip/kv-residency/A2-MIXED-BACKING.md` (§3.7.9, §3.7.11), `HANDOVER.md`. MULTI-DEVICE `--fit` (r181; the window itself reaches a tensor split in r204, at the end of this message): the KV-region glue is now safe on a Meta (tensor-split) device, and `auto`'s decision reaches the cache as a decision. r178 made default `--fit` abort on ANY `-sm tensor` run with more than one device: the fit's KV probes and the cache's own region lookups call `ggml_backend_dev_backend_reg(dev)` and hand it to `ggml_backend_reg_get_proc_address`, and a Meta device has no backend reg (`device->reg == NULL`), so `GGML_ASSERT(reg)` fired at model load. Three paths asserted: the fit probe (any run), the runtime buft lookup (a numeric W), and the spill budget/link lookups (a numeric W below `-c`). r181 makes a null reg read as "not provided" and declines the window with one message naming the tensor split (fit and cache), keeping the KV fully resident -- which is the r181 state; r204, below, is what makes the backend answer there. Three wiring defects in the same code, all visible on ONE device: - `auto`'s "no window needed" decision (0) was indistinguishable from "nobody decided", so the cache warned "--fit did not run" immediately after the fit had decided exactly that. `llama_kv_region_set_resident_cells` now records that a decision was made (`llama_kv_region_resident_cells_decided`), and a decided 0 is silent. - every run without the knob logged "the windowed KV is unavailable for this cache (no spilled cells)". That message now only fires when a window was actually requested and declined for a real reason. - the pinned-RAM ceiling clamp could raise W past the VRAM budget and then be reported as "does not make this fit either". It is now only taken while the wider window still meets the VRAM target; otherwise the fit says the ceiling cannot be served at this `-c` and drops the window (which the fit then fits by reducing the context). That ordering is not cosmetic: an intermediate form of this fix accepted a 235 GiB pinned spill plan for a 4B at `-c 8388608`, and creating it OOM-killed the test box. GATES (the window, gfx1201): `--fit on` (default) at 2 and 3 devices, `-sm tensor`, with no knob / a numeric W / `auto`, fit on and off: no assert, tokens produced, exactly one message per requested window. `-sm layer` 2 devices and 1 GPU still take the window per device (numeric W), and `auto` still sizes the 27B Q8_0 `-c 262144` q8_0 arm identically (123265 of 262144 cells, 4092.8 MiB resident / 4611.2 MiB spilling). One device, no knob: no KV message at all. Purity unchanged: plain vs a SPILLING windowed arm prefill-logit KLD 0.000000 / 99.990 % (q8_0 KV), greedy text byte-identical on that arm; 35B-A3B (1 GPU and 2-GPU `-sm tensor`), dense 27B and the canonical 27B Q8_0 prefill-logit gate (0.000000 / 100.000 %) byte-identical to r180; MTP Protocol A unchanged (tensor acceptance 0.60816 = 1937/3185, plain == draft-mtp); no GPU faults. ========================================================================== PART 2 -- the ATTENDANCE POOL (Goal B, promoted in r190) ========================================================================== The attention KV lives twice: its AUTHORITATIVE copy in a pinned host MIRROR (cell-indexed, so the writers, state_write/state_read, the K-shift, defrag and seq_park all work on it unchanged -- the writer rule) and a compact DEVICE POOL of pages of one indexer block (compress_ratio cells) with a page table block -> slot and its inverse. A decode step resolves its top-k selection through the table and fills the pages it missed from the mirror; the QSA reader gathers K/V at the pool slots while the mask stays cell-indexed. LLAMA_KV_REGION_POOL=<cells>, unset/0 = off = byte-identical. Contents. - ggml/src/ggml-cuda/kv-pool.{cu,cuh}: GGML_OP_KV_POOL. MARK sets use[slot] = epoch for every page this launch reads AND every page the batch just wrote (the graph's k_idxs), and queues the written ones for re-fill; CLAIM takes a slot for each DISTINCT missing block (the table CAS is the dedupe) and never takes a slot MARK protected; MAP+FILL writes each selected cell's pool position into the reader's K/V id list and copies the claimed and dirty pages from the mirror, K and V sharing slots. The epoch is a device counter incremented once per launch: the graph bakes pointers, never counters, and nothing is allocated per launch. - ggml-cuda.cu: the pool's pinned host mirror buffer type -- a DEVICE buffer type whose allocation is pinned host memory (`ROCm_Host` reports is_host, which would send the KV's writers and the FA read to the CPU on a discrete device), and its proc-address entry. - llama-kv-cache: the eligibility, the per-layer pool tensors (pool_k/pool_v, tbl, inv, use, one shared counter block), the resolve wiring into the QSA id list, kv_pool_serves() (a batch too wide for the pool takes the cell-indexed path), the teardown accounting (LLAMA_KV_POOL_STATS takes a PATH: a line on stderr sits inside the generated text), and memory_breakdown() charging the mirror to the host bucket so `--fit` does not reserve it as VRAM. - llama-memory-hybrid-idx / llama-memory-hybrid / llama-memory: the second id list (the K/V gather follows the page table while the mask stays cell-indexed), the flag threading, and the pool's byte accounting for `--fit` (llama_get_kv_pool_bytes()). - models/qwen4exp.cpp: a pooled cache reports is_streaming() and the sparse arm uses the pool's id list; the MTP draft's own cache is never pooled (its attention is dense). - llama-context / the async state copies: the mirror's buffer type is accepted by the batched save and restore (its bytes are host memory, staged through the pinned state_stage). - common/fit.cpp + src/llama-ext.h: the pool's split in --fit's arithmetic and report (the mirror is pinned host RAM, the pool is VRAM), and no context-reduction interpolation while the pool is active -- the pool's VRAM is fixed, so reducing -c frees nothing and the interpolation would divide by a near-zero bytes-per-context delta. Invariants, each one caught by the greedy text. 1. MARK then CLAIM: a claim must never evict a page the same launch reads. Without MARK the round-robin victim could be a page another row still needs (the text diverged ~400 chars in, and a pool larger than the whole cache hid it completely). 2. Claim ATTEMPTS are not distinct blocks: a slot per id attempt wrapped the cursor within one 4-row batch, so two blocks shared a slot and a just-resolved block went unresident. The table CAS dedupes first, so only distinct blocks consume a slot and kv_pool_serves() bounds the distinct count. 3. No transient scratch in a captured graph: the fill list lived in a ggml_cuda_pool_alloc that is freed at the end of the op, and a captured graph bakes the pointer, so a replay wrote into whatever op had been handed that block ("values verify clean, text differs run to run"). It lives in the counters tensor. 4. The mirror is AUTHORITATIVE: the writers land in it and a declared page is re-filled from it before the attention reads it, so an eviction costs nothing and nothing has to be invalidated -- except by a path that rewrites cells in place without going through the writers (the K-shift, a state restore), which calls kv_pool_invalidate(). 5. Eligibility is narrow on purpose: one stream, non-MLA, K and V both present, !v_trans, a uniform compress_ratio and cell geometry, no window active, a device-offloaded cache, and only the trunk context of a qwen4exp model. Anything else declines with one message and the KV is unchanged. 6. The pool is floored at one decode band's worth of blocks (8 x ceil(width/page) pages) so a verify batch cannot exhaust the slot budget, and the mirror is bounded at creation by LLAMA_KV_SPILL_RAM_PCT (it is pinned, non-swappable RAM) -- over the ceiling the pool is declined loudly instead of being OOM-killed. Measured (Flash-Next GSQ-IQ3_XXS, 1 GPU, -ncmoe 48, q8_0, the PLE flags, arms interleaved in one batch, -n 512, MTP depth 4; t/s and tokens/step): depth (ctx) dense sparse pool (204 MiB) text (-n 64) 5 298 (16 384) 72.09 71.58 71.27 pool == sparse: 332 chars dd1981213373 102 899 (131 072) 59.10 54.70 54.65 (5.3k / 51 475 references; dense differs) 180 035 (196 608) 48.94 43.16 43.41 pool == sparse: 861 chars 263c7f2be4d9 The pool lands ON the sparse ceiling at every depth (+0.5 / +0.6 / +0.58 %), so its placement is free and what remains against a resident KV (-7 % / -11 %) is the sparse decode arm's own indexer cost (block 11), not the KV's storage. A 204 MiB pool replaces the resident attention KV's 1 632 MiB at 103k / 2 448 MiB at 180k, and the freed VRAM goes to the expert arena: 103k plain decode, -n 2000, 23 579.8 -> 25 018.6 MiB (+1 438.8 MiB, +18 slots/table), expert hit 96.26 -> 97.02 %, cold reads 42.0 -> 31.6 GiB. The pool's own cost is 0.10-0.11 ms/token (mark/claim/map+fill) with fills 0.03-0.05 ms/step at 92-99 % hits, which is why a better page policy (LRU / F-LRU / a heat prior) is measured dead at this shape. Full numbers and the three-depth table: ../wip/kv-residency/BA-POOL-DESIGN.md §7-§8. PURITY (the pool). Greedy text pool == the resident sparse arm at 5.3k (332 dd1981213373), 51 475 depth (854 43b30de151b9) and 180k (861 263c7f2be4d9), with the dense arm differing as documented (GREEDY-PURITY §45/§63); LLAMA_KV_POOL_VERIFY=1 0 mismatches on every arm; gate-prefill-logits --ab "LLAMA_KV_REGION_POOL=..." 0.000000 / 100.000 % on the pool arm (base PPL 2.9225, bit-identical to the campaign's own base); gate-park-idle-slots, gate-ckpt-reuse and gate-state-pipe PASS on a pooled cache (the mirror is authoritative, which is what makes them trivial); test-backend-ops -o FLASH_ATTN_QSA pass; no GPU faults; and `--fit` accepts the arms that only fit with the pool (-ncmoe 21/22 at -c 262144: refused without it, accepted with it; -fitp moves 3 264 MiB from the device row to Host). ========================================================================== PART 3 -- a STREAMED cache takes the sparse decode arm (B2) ========================================================================== A cache that is streaming at the depth it reads -- a window the used extent has passed, or a pool -- takes the sparse QSA decode arm; a resident cache keeps the dense one. llama_kv_cache::is_streaming() plus the qwen4exp arm policy, LLAMA_QSA_DENSE_DECODE_STREAM=0 to restore the old behaviour. Measured on a spilled KV (Flash-Next IQ3_XXS, -ncmoe 48, q8_0, 1 GPU, -n 400, 2 reps): +34.3 % at 102 899 depth (23.42 -> 31.43 t/s) and +47.3 % at 180 035 (16.51 -> 24.31); a resident cache byte-identical (853 77a40bf40be1). This is a decode-ARM choice, i.e. a different attention regime (like GREEDY-PURITY §45/§63), so a streamed arm's text differs from the old dense-arm text by construction and a resident arm is the oracle. ========================================================================== DEFAULT OFF, for both placements ========================================================================== Neither knob is a speed feature on a config whose KV fits: the window costs the depth below W (11-26 %) and the pool costs the sparse-vs-dense gap (-7 % at 103k, -11 % at 180k). They are FITTABILITY features -- they turn an OOM into a run and they hand the freed VRAM to the expert arena -- so both are opt-in and both stay byte-identical, including the OOM, with their knobs unset. Do not "fix" the defaults. Goal C (the MTP drafter ring, TODO ggml-org#121) joins the same block -- it is the same claim applied to the draft context, and its default follows the delivery's own rule because it measures positive. `LLAMA_SPEC_DRAFT_WINDOW` gives the MTP draft context a sliding window instead of a `-c`-sized KV: unset or `auto` is the adaptive policy (a quarter of the context, clamped to [32768, 65536] cells), `0` is off (byte-identical to a build without it) and `N` is a cell count. The drafter reads its last few thousand tokens, so a window at or above that is free and one far below it costs 7-9 % of decode; the clamps keep it above that band, and the target verifies every token it proposes, so a truncated draft can only be slower. The ring is the shipped reclaim in `llama_kv_cache::find_slot` (`n_swa`), not a new allocator, and the derived kq mask stays valid -- its predicate compares each cell's POSITION, so a recycled cell reports its new one. The VRAM win needed one more piece: an embedded MTP head has no GGUF of its own, so the slab's draft reserve was the flat 3584 MiB and the freed VRAM never reached the expert arena. For an embedded MTP head with an active window the reserve is now derived from the model's own metadata with the weights zeroed (they are the target's) and the KV sized by the window: aux 3.50 -> 0.76 GiB, i.e. the arena gains ~2.8 GiB. A separate MTP draft GGUF (qwen4exp/Flash-Next) and an un-windowed run keep the flat constant exactly as before, and a declined arena preflight now re-evaluates when the smaller real value arrives instead of latching on the load-time estimate. Measured (1 GPU; one R9700; `-n 2000`/`-n 3000`; static depth 3; interleaved): * 35B-A3B Q8_0 `-ncmoe 48 -c 262144` q8_0 KV, 51 433-token prompt: arena 20 910 -> 23 715 MiB (residency 64.1 -> 72.7 %), decode 111.2 -> 113.7 t/s at `-n 3000` (+2.2 %; +2.8-4.9 % at `-n 2000`), prefill +3.4 %, drafts byte-for-byte the same count (1995/3011) -- the window truncates nothing the drafter used. * dense 27B UD-Q4_K_XL `-c 102400`, MTP Protocol A `-n 3000`, reasoning-pinned: layer 71.9 -> 72.1, tensor 72.6 -> 72.5 (neutral), acceptance 2083/2747 identical in all four arms. * target greedy text byte-identical across off/auto/4096, and plain == draft-mtp == draft-mtp(W=512) at `-c 16384` with a 5256-token prompt and 3000 generated tokens (10 158 chars, sha 99b267e8dc3e), i.e. no wrong answer under constant cell reuse. * gates on a windowed draft: `gate-park-idle-slots.sh` (35B, -ncmoe 48, `-c 65536`: 3 park moves, park == lazyoff), `gate-ckpt-reuse.sh` (4B, `-c 131072`: draft cache 33280 of 131072), `gate-state-pipe.sh` (35B, `-c 65536`: all five arms) -- all PASS with `MTP draft KV window = 32768 cells` in their logs. r194 corner fixes (found by a configuration battery against Flash-Next after r193): * LLAMA_KV_REGION_POOL is capped at the cache's own cell count. =1000000 on a 262144-cell context used to take a 12451 MiB device pool of 250000 pages where only 65536 blocks exist (never claimed, arena -4 GiB); it is now 3264 MiB / 65536 pages, and a small context clamps the same way. * the draft KV window sizes only the reserve of the cache it actually windows. A separate -md MTP head (Flash-Next) keeps its full -c cache, but the reserve was derived with the window: 921 MiB where the honest number is 1566 (kv 217 vs 862) at -c 262144, the under-charge direction. Embedded heads (qwen3.5/3.6/3.8) are unchanged (776 MiB on the 35B). The VRAM cliff at -c 262144 is documented (not code): the 768 MiB default headroom is one hipBLASLt workspace short for the first prefill, GGML_CUDA_SLAB_HEADROOM_MIB=1536 is 3/3 requests clean. Amendment (TODO ggml-org#129's sibling): `-nkvo` declines the window, and the streamed arm keys on the placement. The window is a DEVICE region plus a pinned host tail, but its guard did not test `offload`: with `-nkvo` the per-layer buffer is chosen inside `if (offload)` and stays plain pageable host memory, while the plan block still logged "WINDOWED KV ENABLED", reserved pinned-RAM spill budget and left `kv_resident_cells` set. `is_streaming()` then keyed the streamed (sparse) decode arm on that plan -- qwen4exp consumes it -- for a KV with no region at all. Measured: `-nkvo LLAMA_KV_RESIDENT_CELLS=64` built a plain `CPU KV buffer` of the whole context while announcing a 64-cell VRAM window. The window now declines once, with the reason (the pool already declines on `!offload`), so `-nkvo` means "no streamed placement"; `is_streaming()` tests `kv_region`, the placement actually taken, which also covers a device cache whose region buft the backend refused. Text is unchanged in every arm (the decline is a no-op: `-nkvo` + window already read as `-nkvo` alone). Amendment (issue ggml-org#264): the draft window is PER SEQUENCE, and under `--kv-unified` its cell count is `(win + one batch) x n_seq_max`. A unified cache holds every sequence in ONE stream, so the r193 sizing (`win + n_ubatch` cells) was shared by all of them: once the first sequence had filled its window the tail was all the room left, the tail is where that sequence's own ring writes, and a second sequence's first batch had no contiguous run to be placed in -- `find_slot` refused, and every request on that slot answered `decode() failed: failed to process speculative batch` (HTTP 500) while the drafter ran. Reported on `--kv-unified -np 2` with a 65 536-cell window at `-c 262144` after slot 0 held ~100k tokens; reproduced here with a forced 8192-cell window. A per-stream cache (no `--kv-unified`) already sized each stream separately and is unchanged. `llama_spec_draft_kv_cells()` is now the one geometry function -- the cache (`create_memory`), the slab's draft reserve estimate and the "is a window active" test in `common` all call it, so the reserve can never under-charge an allocation. It grants `win` per sequence plus one placeable batch (`(win + n_ubatch) * n_seq_max`, capped at the context), and DECLINES the window when that does not fit the context per sequence rather than lowering it to `per_seq - n_ubatch`: a window that small saves one batch of cells per sequence and masks the drafter's newest cells to do it. `llama_spec_draft_window_cells()` stays the policy (it is the per-sequence window). n_seq_max == 1 -- every `llama-cli`/`llama-bench` run -- measures exactly what it did (cells 1536 for a 1024-cell window at `-c 8192`), so no single-sequence arm changes at all. Measured (dense 27B, 1 GPU, `-np 2 --kv-unified`): the issue's scenario now answers both slots, and `scripts/gate-spec-draft-window.sh` (new) drives 6 requests over 2 slots with a 1024-cell window -- both rings wrapping, prompts full re-prefilled by swapping them between slots -- with output byte-identical to `LLAMA_SPEC_DRAFT_WINDOW=0` on every step and draft acceptance identical (17/36, 23/23). Greedy text `plain == draft-mtp == draft-mtp(W=1024) == draft-mtp(W=0)` (876 chars, sha 8c8fd395402f) at `-c 16384`. And the reserve now charges a per-STREAM (no `--kv-unified`) draft cache for every stream it allocates: `n_seq_max x` the per-stream cell count. Before, a multi-slot windowed MTP server without `--kv-unified` (35B-A3B `-ncmoe 40 -np 2 -c 8192`, window 1024: 2 x 1536 = 3072 cells allocated, 1536 charged) under-charged the slab's aux reserve by one stream's window -- the direction the reserve header calls dangerous. Measured: 3072 cells reported on both the unified and the per-stream arm now. ========================================================================== PART 4 -- `-sm tensor`: the window across a split (r204, `TODO` ggml-org#124) ========================================================================== A Meta (tensor-split) device carries no backend reg, so the r181 answer was "not provided" and the window was declined on every split. `TODO` ggml-org#124 designed the fix on a one-GPU box (`archive/work/kv-residency/ A6-TENSOR-SPLIT-WINDOW.md`, changes C1-C5); it is implemented and measured here, on a 3x R9700 host, and the decline is gone. * `ggml_backend_meta_kv_region_buft / _is_kv_buft / _grow` (new, `ggml-backend.h`): the Meta buffer type over the per-child region buffer types (ALL children or nothing), the is-a-region predicate `--fit` needs (the CUDA predicate is an identity on the child's `alloc_buffer` and cannot answer for a Meta buffer type), and a grow that fans out to every child. A child that cannot be reached is a REFUSAL (-1), never the 0 the CUDA hook returns for "not a region buffer": for a Meta buffer that 0 was a silent success on unmapped VA, i.e. a batch that page-faults the GPU. * `llama_kv_cache` resolves capability, the buffer type, the spill ceiling and the link through the Meta side; a MIRRORED cache (dsv4 / HRM, `llama_model::kv_cache_split_mirrored()`) declines the window with its own message, because every device holds the whole cache there (`n_devices x W x cell_bytes`) and the pinned-spill plan is per logical cache. * `common/fit.cpp` decides the window inside the tensor-split branch: charged at its PHYSICAL `W x cell_bytes` (what all devices commit together) against `min_i(target_i / ratio_i)`, which makes the aggregate check imply every device's (the loader shards the KV along the KV-head axis by the same ratio it shards the weights), and the Meta entry's margin is now the SUM of the children's `--fit-target`s (it was child 0's, so `(n_devices - 1) x target` silently vanished from the budget). The corrected KV term applies ONLY where a window is asked for: a run without `LLAMA_KV_RESIDENT_CELLS` keeps this branch's old arithmetic exactly, so the split's pre-existing `n_devices x` KV over-count is untouched outside the window arm. Four defects the arms found, fixed in the same block: 1. the init-time window commit was rounded up to a whole map unit past the tensor's own extent, and on a split each child is its own VA reservation -- the last tensor's inflated window was refused (`the KV window (4.00 MiB) could not be committed in VRAM on device 1`). Clamped to the region's END, in whole units (clamping to the tensor's own extent was tried first and is wrong: it leaves a short mapping off the unit grid and the next slide refuses to flip). 2. `ensure_span` refused a request that covered several WHOLE mappings; one batch can advance the boundary by more than one unit, and a 1 MiB unit is floored to the driver's 2 MiB granularity, so the request covered two mappings and aborted the batch. Whole mappings now flip one at a time; a request that covers a mapping only in PART is still refused (that loses bytes on this driver). 3. the batched state save issued a 2-D D2H per device and `hipMemcpy2DAsync` fails (`invalid argument`) when the range begins in a spilled region's pinned host mapping (the tensor-split checkpoint save aborted: `cache_k_l64 (view)`, 1024 B x 4782 rows). The region-backed directions of `get/set_tensor_2d_async` now go through the region buffer's own copy, ordered behind the compute stream like the pool mirror (a blocking default-stream copy does not wait for it, and the state saved mid-batch is torn). 4. that fallback's "contiguous rows = one copy" shortcut ignored the caller's destination pitch, which for a split splice is the FULL row, wider than one device's slice: the state-pipe gate failed on every cycle of all four async arms until a tight block required BOTH pitches to equal the width. Verified (gfx1201, `ROCBLAS_USE_HIPBLASLT=0` for every fresh-process pair): text byte-identical on `win3 == ref3` (3 devices, 4B, `057ea27b1009`) and `win2 == ref2 == win2mtp == ref2mtp` (2 devices, 27B, a 5246-token prompt, `7a7430617465`; draft acceptance 0.46154 in both MTP arms), also at a 1 MiB map unit; the spill is real on EVERY device (32 mapping flips each at 4 MiB, 128 at 1 MiB); a `-c 1048576` 2-device split (64 GiB of f16 KV) runs only because of the window; the single-device and `-nkvo` arms are unchanged; `--fit` on the split reports a WINDOWED cache and keeps the pinned `-c 524288` (plus the pinned-RAM ceiling's widen and drop arms, and `LLAMA_KV_REGION=0` silent); coherence identical to the r203 build on four no-window arms (3-GPU 4B, 2-GPU and 1-GPU 27B, 2-GPU host-expert 35B-A3B); prefill-logit 0.000000 / 100.000 %; Protocol A four-axis R/P/C/K 1.91x / 2.43x / 2.58x / 2.74x (acceptance 0.5869 / 0.8391 / 0.9112 / 0.9920, the r90 shape); `gate-spec-draft-window.sh` 6/6; `gate-state-pipe.sh` 2-GPU `-sm tensor` PASS with and without the window (the windowed arm failed before (3) and (4)); `GGML_CUDA_VMM_REGION_SELFTEST=1` PASS with a new multi-mapping arm; per-block build 1/1; `validate-set.sh` strict 16/16. Gate: `scripts/gate-kv-window-split.sh`. Record: `benchmarks/2026-11-01-kv-window-tensor-split-124.md`.
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Nov 5, 2026
…W (Goal A) and an attendance POOL (Goal B), both opt-in Goals A and B of TODO ggml-org#118, promoted from the `wip/kv-residency` campaign. This block is the delivery's "the KV does not have to be O(-c) of VRAM" work: TWO opt-in placements of the same cache, and each one is byte-identical to a build without it when its knob is unset. * the WINDOW (`LLAMA_KV_RESIDENT_CELLS=<cells>|auto`): the newest W cells stay in VRAM, everything older spills to pinned system RAM in the SAME VA reservation -- a positional window, no kernel or op change; * the POOL (`LLAMA_KV_REGION_POOL=<cells>`): the authoritative copy of the WHOLE context in a pinned host mirror, and a compact device pool of the pages a decode step actually attends to, which the QSA sparse read resolves through a page table (`GGML_OP_KV_POOL`). They are mutually exclusive by construction (the pool declines while a window is active) and they answer the same question from opposite ends: the window keeps the *newest* cells hot, the pool keeps the *attended* cells hot. Both report `is_streaming()`, so a streamed cache takes the sparse QSA decode arm (B2, below). ========================================================================== PART 1 -- the WINDOW (Goal A, promoted in r178) ========================================================================== Goal A of TODO ggml-org#118, promoted from the `wip/kv-residency` campaign. WHAT IT DOES. The KV cache's VRAM cost becomes a WINDOW of the newest `W` cells instead of `-c` cells: one VA reservation (a CUDA/HIP VMM region) holds the whole cache, the window's cells are backed by VRAM and everything below them by pinned system RAM. `set_rows`, the in-place rope shift, `state_write/read`, the kq mask and the FA kernels keep addressing one contiguous range, so no kernel and no op changes. The window slides with the watermark in whole map units, so a remap happens once per few thousand tokens and the apparatus itself is free (a zero-spill arm measures the same as plain). WHY. (a) A context that OOMs today runs: 27B Q8_0 `-c 262144` (8704 MiB of KV) now runs on one 32 GiB card at 128 MiB VRAM + 8576 MiB pinned host for the KV. (b) With host-resident MoE experts, the VRAM the KV does not need *yet* goes to the expert-cache arena: measured at `-c 262144`, `-n 2000`, `-ncmoe` = the model's full layer count, 51 433-token prompt, W at or above the run's depth = **+2.2 to +2.9 GiB of arena** (+3.9 to +6.7 points of residency) for free -- 122B-A10B Q4_K_XL +3.8 % decode and +4.7 % prefill, 35B-A3B Q8_0 -0.9 % decode and +3 % prefill; a `W` 35 k cells BELOW the run depth costs 11-26 % (the spill is read every token). OPT-IN, AND ONLY WHEN ASKED FOR. `LLAMA_KV_RESIDENT_CELLS=<cells>` (a number) or `=auto` (`--fit` sizes it, and only spills a context the user pinned with `-c`); unset/0 = no window. With no window the KV takes the PLAIN device buffer, so a run without the knob is byte-identical to a build without this block -- including its OOM (verified). `LLAMA_KV_SPILL_RAM_PCT` (85 % of MemAvailable) caps the pinned spill and widens the window rather than being OOM-killed; `LLAMA_KV_REGION=0` disables the provider; `LLAMA_KV_REGION_QUARANTINE=0` and `LLAMA_KV_REGION_DEBUG/TRACE/CANARY/DUMP` are the diagnosis switches. PURITY (the window). A spilled KV is numerically transparent: prefill-logit **KLD -0.000000 / 100.000 %** on a spilling 27B arm and -0.000000 / 99.994 % on a spilling Flash-Next (two KV caches: the attention KV and the QSA indexer), text byte-identical on 27B (f16 and q8_0), 4B, 35B-A3B and Flash-Next, and the state paths, the context-checkpoint path and the MTP verify widths all green on arms that provably spill. Two driver hazards are held: a kind flip zeroes a neighbouring live host mapping unless the released physical is held across the create (`LLAMA_KV_REGION_QUARANTINE`, default on -- `=0` reproduces the corruption), and every tensor in a windowed region is placed on the driver's map granularity so a slide step coincides with a mapping. An idle-slot park is REFUSED on a region-backed cache (the server then saves the slot to the prompt cache and clears it, which is byte-identical to the parking gate's reference) because a park moves cells above the region's mapped watermark through the copy engine, which faults the GPU. FIT. `--fit` sizes and reports the window (`auto`), or honours and reports a numeric `W`: the resident/spill split, the VRAM saved, and the per-token read cost at the model's full context from the backend's calibrated link rate. The fit identifies the KV's bytes by the region buffer TYPE, and its measurement context is a `no_alloc` probe that declines a window -- so the probe takes the region buffer explicitly (`llama_kv_region_set_probe`); without that the fit cannot see the KV, reports an over-budget config and aborts instead of sizing the window (the r178 regression). GATES (1 GPU, gfx1201): default path byte-identical (`5ba44647188f`) and still OOMs; VMM selftest PASS and FAIL with the hold disabled; windowed arms 305 `e2cea6fa6670` = plain at W=1024/2048/4096 (spilling at 1024: 128 MiB host), `QUARANTINE=0` -> 325 `fb65430049e9` (the hazard); `--fit` sizes `auto` (96680 of 262144 cells, 3210 MiB resident) and reports a numeric W; `gate-ckpt-reuse.sh` / `gate-state-pipe.sh` / MTP verify widths on spilling arms; `test-backend-ops -o FLASH_ATTN_QSA` 26/26; `check-gpu-faults.sh` clean. Not in this block: the campaign's Goal B (a sparse attended set) and Goal C (the MTP drafter ring, `LLAMA_SPEC_DRAFT_WINDOW`) -- both remain campaign work -- and A1 (the superseded two-base FA read). Records: `wip/kv-residency/A2-MIXED-BACKING.md` (§3.7.9, §3.7.11), `HANDOVER.md`. MULTI-DEVICE `--fit` (r181; the window itself reaches a tensor split in r204, at the end of this message): the KV-region glue is now safe on a Meta (tensor-split) device, and `auto`'s decision reaches the cache as a decision. r178 made default `--fit` abort on ANY `-sm tensor` run with more than one device: the fit's KV probes and the cache's own region lookups call `ggml_backend_dev_backend_reg(dev)` and hand it to `ggml_backend_reg_get_proc_address`, and a Meta device has no backend reg (`device->reg == NULL`), so `GGML_ASSERT(reg)` fired at model load. Three paths asserted: the fit probe (any run), the runtime buft lookup (a numeric W), and the spill budget/link lookups (a numeric W below `-c`). r181 makes a null reg read as "not provided" and declines the window with one message naming the tensor split (fit and cache), keeping the KV fully resident -- which is the r181 state; r204, below, is what makes the backend answer there. Three wiring defects in the same code, all visible on ONE device: - `auto`'s "no window needed" decision (0) was indistinguishable from "nobody decided", so the cache warned "--fit did not run" immediately after the fit had decided exactly that. `llama_kv_region_set_resident_cells` now records that a decision was made (`llama_kv_region_resident_cells_decided`), and a decided 0 is silent. - every run without the knob logged "the windowed KV is unavailable for this cache (no spilled cells)". That message now only fires when a window was actually requested and declined for a real reason. - the pinned-RAM ceiling clamp could raise W past the VRAM budget and then be reported as "does not make this fit either". It is now only taken while the wider window still meets the VRAM target; otherwise the fit says the ceiling cannot be served at this `-c` and drops the window (which the fit then fits by reducing the context). That ordering is not cosmetic: an intermediate form of this fix accepted a 235 GiB pinned spill plan for a 4B at `-c 8388608`, and creating it OOM-killed the test box. GATES (the window, gfx1201): `--fit on` (default) at 2 and 3 devices, `-sm tensor`, with no knob / a numeric W / `auto`, fit on and off: no assert, tokens produced, exactly one message per requested window. `-sm layer` 2 devices and 1 GPU still take the window per device (numeric W), and `auto` still sizes the 27B Q8_0 `-c 262144` q8_0 arm identically (123265 of 262144 cells, 4092.8 MiB resident / 4611.2 MiB spilling). One device, no knob: no KV message at all. Purity unchanged: plain vs a SPILLING windowed arm prefill-logit KLD 0.000000 / 99.990 % (q8_0 KV), greedy text byte-identical on that arm; 35B-A3B (1 GPU and 2-GPU `-sm tensor`), dense 27B and the canonical 27B Q8_0 prefill-logit gate (0.000000 / 100.000 %) byte-identical to r180; MTP Protocol A unchanged (tensor acceptance 0.60816 = 1937/3185, plain == draft-mtp); no GPU faults. ========================================================================== PART 2 -- the ATTENDANCE POOL (Goal B, promoted in r190) ========================================================================== The attention KV lives twice: its AUTHORITATIVE copy in a pinned host MIRROR (cell-indexed, so the writers, state_write/state_read, the K-shift, defrag and seq_park all work on it unchanged -- the writer rule) and a compact DEVICE POOL of pages of one indexer block (compress_ratio cells) with a page table block -> slot and its inverse. A decode step resolves its top-k selection through the table and fills the pages it missed from the mirror; the QSA reader gathers K/V at the pool slots while the mask stays cell-indexed. LLAMA_KV_REGION_POOL=<cells>, unset/0 = off = byte-identical. Contents. - ggml/src/ggml-cuda/kv-pool.{cu,cuh}: GGML_OP_KV_POOL. MARK sets use[slot] = epoch for every page this launch reads AND every page the batch just wrote (the graph's k_idxs), and queues the written ones for re-fill; CLAIM takes a slot for each DISTINCT missing block (the table CAS is the dedupe) and never takes a slot MARK protected; MAP+FILL writes each selected cell's pool position into the reader's K/V id list and copies the claimed and dirty pages from the mirror, K and V sharing slots. The epoch is a device counter incremented once per launch: the graph bakes pointers, never counters, and nothing is allocated per launch. - ggml-cuda.cu: the pool's pinned host mirror buffer type -- a DEVICE buffer type whose allocation is pinned host memory (`ROCm_Host` reports is_host, which would send the KV's writers and the FA read to the CPU on a discrete device), and its proc-address entry. - llama-kv-cache: the eligibility, the per-layer pool tensors (pool_k/pool_v, tbl, inv, use, one shared counter block), the resolve wiring into the QSA id list, kv_pool_serves() (a batch too wide for the pool takes the cell-indexed path), the teardown accounting (LLAMA_KV_POOL_STATS takes a PATH: a line on stderr sits inside the generated text), and memory_breakdown() charging the mirror to the host bucket so `--fit` does not reserve it as VRAM. - llama-memory-hybrid-idx / llama-memory-hybrid / llama-memory: the second id list (the K/V gather follows the page table while the mask stays cell-indexed), the flag threading, and the pool's byte accounting for `--fit` (llama_get_kv_pool_bytes()). - models/qwen4exp.cpp: a pooled cache reports is_streaming() and the sparse arm uses the pool's id list; the MTP draft's own cache is never pooled (its attention is dense). - llama-context / the async state copies: the mirror's buffer type is accepted by the batched save and restore (its bytes are host memory, staged through the pinned state_stage). - common/fit.cpp + src/llama-ext.h: the pool's split in --fit's arithmetic and report (the mirror is pinned host RAM, the pool is VRAM), and no context-reduction interpolation while the pool is active -- the pool's VRAM is fixed, so reducing -c frees nothing and the interpolation would divide by a near-zero bytes-per-context delta. Invariants, each one caught by the greedy text. 1. MARK then CLAIM: a claim must never evict a page the same launch reads. Without MARK the round-robin victim could be a page another row still needs (the text diverged ~400 chars in, and a pool larger than the whole cache hid it completely). 2. Claim ATTEMPTS are not distinct blocks: a slot per id attempt wrapped the cursor within one 4-row batch, so two blocks shared a slot and a just-resolved block went unresident. The table CAS dedupes first, so only distinct blocks consume a slot and kv_pool_serves() bounds the distinct count. 3. No transient scratch in a captured graph: the fill list lived in a ggml_cuda_pool_alloc that is freed at the end of the op, and a captured graph bakes the pointer, so a replay wrote into whatever op had been handed that block ("values verify clean, text differs run to run"). It lives in the counters tensor. 4. The mirror is AUTHORITATIVE: the writers land in it and a declared page is re-filled from it before the attention reads it, so an eviction costs nothing and nothing has to be invalidated -- except by a path that rewrites cells in place without going through the writers (the K-shift, a state restore), which calls kv_pool_invalidate(). 5. Eligibility is narrow on purpose: one stream, non-MLA, K and V both present, !v_trans, a uniform compress_ratio and cell geometry, no window active, a device-offloaded cache, and only the trunk context of a qwen4exp model. Anything else declines with one message and the KV is unchanged. 6. The pool is floored at one decode band's worth of blocks (8 x ceil(width/page) pages) so a verify batch cannot exhaust the slot budget, and the mirror is bounded at creation by LLAMA_KV_SPILL_RAM_PCT (it is pinned, non-swappable RAM) -- over the ceiling the pool is declined loudly instead of being OOM-killed. Measured (Flash-Next GSQ-IQ3_XXS, 1 GPU, -ncmoe 48, q8_0, the PLE flags, arms interleaved in one batch, -n 512, MTP depth 4; t/s and tokens/step): depth (ctx) dense sparse pool (204 MiB) text (-n 64) 5 298 (16 384) 72.09 71.58 71.27 pool == sparse: 332 chars dd1981213373 102 899 (131 072) 59.10 54.70 54.65 (5.3k / 51 475 references; dense differs) 180 035 (196 608) 48.94 43.16 43.41 pool == sparse: 861 chars 263c7f2be4d9 The pool lands ON the sparse ceiling at every depth (+0.5 / +0.6 / +0.58 %), so its placement is free and what remains against a resident KV (-7 % / -11 %) is the sparse decode arm's own indexer cost (block 11), not the KV's storage. A 204 MiB pool replaces the resident attention KV's 1 632 MiB at 103k / 2 448 MiB at 180k, and the freed VRAM goes to the expert arena: 103k plain decode, -n 2000, 23 579.8 -> 25 018.6 MiB (+1 438.8 MiB, +18 slots/table), expert hit 96.26 -> 97.02 %, cold reads 42.0 -> 31.6 GiB. The pool's own cost is 0.10-0.11 ms/token (mark/claim/map+fill) with fills 0.03-0.05 ms/step at 92-99 % hits, which is why a better page policy (LRU / F-LRU / a heat prior) is measured dead at this shape. Full numbers and the three-depth table: ../wip/kv-residency/BA-POOL-DESIGN.md §7-§8. PURITY (the pool). Greedy text pool == the resident sparse arm at 5.3k (332 dd1981213373), 51 475 depth (854 43b30de151b9) and 180k (861 263c7f2be4d9), with the dense arm differing as documented (GREEDY-PURITY §45/§63); LLAMA_KV_POOL_VERIFY=1 0 mismatches on every arm; gate-prefill-logits --ab "LLAMA_KV_REGION_POOL=..." 0.000000 / 100.000 % on the pool arm (base PPL 2.9225, bit-identical to the campaign's own base); gate-park-idle-slots, gate-ckpt-reuse and gate-state-pipe PASS on a pooled cache (the mirror is authoritative, which is what makes them trivial); test-backend-ops -o FLASH_ATTN_QSA pass; no GPU faults; and `--fit` accepts the arms that only fit with the pool (-ncmoe 21/22 at -c 262144: refused without it, accepted with it; -fitp moves 3 264 MiB from the device row to Host). ========================================================================== PART 3 -- a STREAMED cache takes the sparse decode arm (B2) ========================================================================== A cache that is streaming at the depth it reads -- a window the used extent has passed, or a pool -- takes the sparse QSA decode arm; a resident cache keeps the dense one. llama_kv_cache::is_streaming() plus the qwen4exp arm policy, LLAMA_QSA_DENSE_DECODE_STREAM=0 to restore the old behaviour. Measured on a spilled KV (Flash-Next IQ3_XXS, -ncmoe 48, q8_0, 1 GPU, -n 400, 2 reps): +34.3 % at 102 899 depth (23.42 -> 31.43 t/s) and +47.3 % at 180 035 (16.51 -> 24.31); a resident cache byte-identical (853 77a40bf40be1). This is a decode-ARM choice, i.e. a different attention regime (like GREEDY-PURITY §45/§63), so a streamed arm's text differs from the old dense-arm text by construction and a resident arm is the oracle. ========================================================================== DEFAULT OFF, for both placements ========================================================================== Neither knob is a speed feature on a config whose KV fits: the window costs the depth below W (11-26 %) and the pool costs the sparse-vs-dense gap (-7 % at 103k, -11 % at 180k). They are FITTABILITY features -- they turn an OOM into a run and they hand the freed VRAM to the expert arena -- so both are opt-in and both stay byte-identical, including the OOM, with their knobs unset. Do not "fix" the defaults. Goal C (the MTP drafter ring, TODO ggml-org#121) joins the same block -- it is the same claim applied to the draft context, and its default follows the delivery's own rule because it measures positive. `LLAMA_SPEC_DRAFT_WINDOW` gives the MTP draft context a sliding window instead of a `-c`-sized KV: unset or `auto` is the adaptive policy (a quarter of the context, clamped to [32768, 65536] cells), `0` is off (byte-identical to a build without it) and `N` is a cell count. The drafter reads its last few thousand tokens, so a window at or above that is free and one far below it costs 7-9 % of decode; the clamps keep it above that band, and the target verifies every token it proposes, so a truncated draft can only be slower. The ring is the shipped reclaim in `llama_kv_cache::find_slot` (`n_swa`), not a new allocator, and the derived kq mask stays valid -- its predicate compares each cell's POSITION, so a recycled cell reports its new one. The VRAM win needed one more piece: an embedded MTP head has no GGUF of its own, so the slab's draft reserve was the flat 3584 MiB and the freed VRAM never reached the expert arena. For an embedded MTP head with an active window the reserve is now derived from the model's own metadata with the weights zeroed (they are the target's) and the KV sized by the window: aux 3.50 -> 0.76 GiB, i.e. the arena gains ~2.8 GiB. A separate MTP draft GGUF (qwen4exp/Flash-Next) and an un-windowed run keep the flat constant exactly as before, and a declined arena preflight now re-evaluates when the smaller real value arrives instead of latching on the load-time estimate. Measured (1 GPU; one R9700; `-n 2000`/`-n 3000`; static depth 3; interleaved): * 35B-A3B Q8_0 `-ncmoe 48 -c 262144` q8_0 KV, 51 433-token prompt: arena 20 910 -> 23 715 MiB (residency 64.1 -> 72.7 %), decode 111.2 -> 113.7 t/s at `-n 3000` (+2.2 %; +2.8-4.9 % at `-n 2000`), prefill +3.4 %, drafts byte-for-byte the same count (1995/3011) -- the window truncates nothing the drafter used. * dense 27B UD-Q4_K_XL `-c 102400`, MTP Protocol A `-n 3000`, reasoning-pinned: layer 71.9 -> 72.1, tensor 72.6 -> 72.5 (neutral), acceptance 2083/2747 identical in all four arms. * target greedy text byte-identical across off/auto/4096, and plain == draft-mtp == draft-mtp(W=512) at `-c 16384` with a 5256-token prompt and 3000 generated tokens (10 158 chars, sha 99b267e8dc3e), i.e. no wrong answer under constant cell reuse. * gates on a windowed draft: `gate-park-idle-slots.sh` (35B, -ncmoe 48, `-c 65536`: 3 park moves, park == lazyoff), `gate-ckpt-reuse.sh` (4B, `-c 131072`: draft cache 33280 of 131072), `gate-state-pipe.sh` (35B, `-c 65536`: all five arms) -- all PASS with `MTP draft KV window = 32768 cells` in their logs. r194 corner fixes (found by a configuration battery against Flash-Next after r193): * LLAMA_KV_REGION_POOL is capped at the cache's own cell count. =1000000 on a 262144-cell context used to take a 12451 MiB device pool of 250000 pages where only 65536 blocks exist (never claimed, arena -4 GiB); it is now 3264 MiB / 65536 pages, and a small context clamps the same way. * the draft KV window sizes only the reserve of the cache it actually windows. A separate -md MTP head (Flash-Next) keeps its full -c cache, but the reserve was derived with the window: 921 MiB where the honest number is 1566 (kv 217 vs 862) at -c 262144, the under-charge direction. Embedded heads (qwen3.5/3.6/3.8) are unchanged (776 MiB on the 35B). The VRAM cliff at -c 262144 is documented (not code): the 768 MiB default headroom is one hipBLASLt workspace short for the first prefill, GGML_CUDA_SLAB_HEADROOM_MIB=1536 is 3/3 requests clean. Amendment (TODO ggml-org#129's sibling): `-nkvo` declines the window, and the streamed arm keys on the placement. The window is a DEVICE region plus a pinned host tail, but its guard did not test `offload`: with `-nkvo` the per-layer buffer is chosen inside `if (offload)` and stays plain pageable host memory, while the plan block still logged "WINDOWED KV ENABLED", reserved pinned-RAM spill budget and left `kv_resident_cells` set. `is_streaming()` then keyed the streamed (sparse) decode arm on that plan -- qwen4exp consumes it -- for a KV with no region at all. Measured: `-nkvo LLAMA_KV_RESIDENT_CELLS=64` built a plain `CPU KV buffer` of the whole context while announcing a 64-cell VRAM window. The window now declines once, with the reason (the pool already declines on `!offload`), so `-nkvo` means "no streamed placement"; `is_streaming()` tests `kv_region`, the placement actually taken, which also covers a device cache whose region buft the backend refused. Text is unchanged in every arm (the decline is a no-op: `-nkvo` + window already read as `-nkvo` alone). Amendment (issue ggml-org#264): the draft window is PER SEQUENCE, and under `--kv-unified` its cell count is `(win + one batch) x n_seq_max`. A unified cache holds every sequence in ONE stream, so the r193 sizing (`win + n_ubatch` cells) was shared by all of them: once the first sequence had filled its window the tail was all the room left, the tail is where that sequence's own ring writes, and a second sequence's first batch had no contiguous run to be placed in -- `find_slot` refused, and every request on that slot answered `decode() failed: failed to process speculative batch` (HTTP 500) while the drafter ran. Reported on `--kv-unified -np 2` with a 65 536-cell window at `-c 262144` after slot 0 held ~100k tokens; reproduced here with a forced 8192-cell window. A per-stream cache (no `--kv-unified`) already sized each stream separately and is unchanged. `llama_spec_draft_kv_cells()` is now the one geometry function -- the cache (`create_memory`), the slab's draft reserve estimate and the "is a window active" test in `common` all call it, so the reserve can never under-charge an allocation. It grants `win` per sequence plus one placeable batch (`(win + n_ubatch) * n_seq_max`, capped at the context), and DECLINES the window when that does not fit the context per sequence rather than lowering it to `per_seq - n_ubatch`: a window that small saves one batch of cells per sequence and masks the drafter's newest cells to do it. `llama_spec_draft_window_cells()` stays the policy (it is the per-sequence window). n_seq_max == 1 -- every `llama-cli`/`llama-bench` run -- measures exactly what it did (cells 1536 for a 1024-cell window at `-c 8192`), so no single-sequence arm changes at all. Measured (dense 27B, 1 GPU, `-np 2 --kv-unified`): the issue's scenario now answers both slots, and `scripts/gate-spec-draft-window.sh` (new) drives 6 requests over 2 slots with a 1024-cell window -- both rings wrapping, prompts full re-prefilled by swapping them between slots -- with output byte-identical to `LLAMA_SPEC_DRAFT_WINDOW=0` on every step and draft acceptance identical (17/36, 23/23). Greedy text `plain == draft-mtp == draft-mtp(W=1024) == draft-mtp(W=0)` (876 chars, sha 8c8fd395402f) at `-c 16384`. And the reserve now charges a per-STREAM (no `--kv-unified`) draft cache for every stream it allocates: `n_seq_max x` the per-stream cell count. Before, a multi-slot windowed MTP server without `--kv-unified` (35B-A3B `-ncmoe 40 -np 2 -c 8192`, window 1024: 2 x 1536 = 3072 cells allocated, 1536 charged) under-charged the slab's aux reserve by one stream's window -- the direction the reserve header calls dangerous. Measured: 3072 cells reported on both the unified and the per-stream arm now. ========================================================================== PART 4 -- `-sm tensor`: the window across a split (r204, `TODO` ggml-org#124) ========================================================================== A Meta (tensor-split) device carries no backend reg, so the r181 answer was "not provided" and the window was declined on every split. `TODO` ggml-org#124 designed the fix on a one-GPU box (`archive/work/kv-residency/ A6-TENSOR-SPLIT-WINDOW.md`, changes C1-C5); it is implemented and measured here, on a 3x R9700 host, and the decline is gone. * `ggml_backend_meta_kv_region_buft / _is_kv_buft / _grow` (new, `ggml-backend.h`): the Meta buffer type over the per-child region buffer types (ALL children or nothing), the is-a-region predicate `--fit` needs (the CUDA predicate is an identity on the child's `alloc_buffer` and cannot answer for a Meta buffer type), and a grow that fans out to every child. A child that cannot be reached is a REFUSAL (-1), never the 0 the CUDA hook returns for "not a region buffer": for a Meta buffer that 0 was a silent success on unmapped VA, i.e. a batch that page-faults the GPU. * `llama_kv_cache` resolves capability, the buffer type, the spill ceiling and the link through the Meta side; a MIRRORED cache (dsv4 / HRM, `llama_model::kv_cache_split_mirrored()`) declines the window with its own message, because every device holds the whole cache there (`n_devices x W x cell_bytes`) and the pinned-spill plan is per logical cache. * `common/fit.cpp` decides the window inside the tensor-split branch: charged at its PHYSICAL `W x cell_bytes` (what all devices commit together) against `min_i(target_i / ratio_i)`, which makes the aggregate check imply every device's (the loader shards the KV along the KV-head axis by the same ratio it shards the weights), and the Meta entry's margin is now the SUM of the children's `--fit-target`s (it was child 0's, so `(n_devices - 1) x target` silently vanished from the budget). The corrected KV term applies ONLY where a window is asked for: a run without `LLAMA_KV_RESIDENT_CELLS` keeps this branch's old arithmetic exactly, so the split's pre-existing `n_devices x` KV over-count is untouched outside the window arm. Four defects the arms found, fixed in the same block: 1. the init-time window commit was rounded up to a whole map unit past the tensor's own extent, and on a split each child is its own VA reservation -- the last tensor's inflated window was refused (`the KV window (4.00 MiB) could not be committed in VRAM on device 1`). Clamped to the region's END, in whole units (clamping to the tensor's own extent was tried first and is wrong: it leaves a short mapping off the unit grid and the next slide refuses to flip). 2. `ensure_span` refused a request that covered several WHOLE mappings; one batch can advance the boundary by more than one unit, and a 1 MiB unit is floored to the driver's 2 MiB granularity, so the request covered two mappings and aborted the batch. Whole mappings now flip one at a time; a request that covers a mapping only in PART is still refused (that loses bytes on this driver). 3. the batched state save issued a 2-D D2H per device and `hipMemcpy2DAsync` fails (`invalid argument`) when the range begins in a spilled region's pinned host mapping (the tensor-split checkpoint save aborted: `cache_k_l64 (view)`, 1024 B x 4782 rows). The region-backed directions of `get/set_tensor_2d_async` now go through the region buffer's own copy, ordered behind the compute stream like the pool mirror (a blocking default-stream copy does not wait for it, and the state saved mid-batch is torn). 4. that fallback's "contiguous rows = one copy" shortcut ignored the caller's destination pitch, which for a split splice is the FULL row, wider than one device's slice: the state-pipe gate failed on every cycle of all four async arms until a tight block required BOTH pitches to equal the width. Verified (gfx1201, `ROCBLAS_USE_HIPBLASLT=0` for every fresh-process pair): text byte-identical on `win3 == ref3` (3 devices, 4B, `057ea27b1009`) and `win2 == ref2 == win2mtp == ref2mtp` (2 devices, 27B, a 5246-token prompt, `7a7430617465`; draft acceptance 0.46154 in both MTP arms), also at a 1 MiB map unit; the spill is real on EVERY device (32 mapping flips each at 4 MiB, 128 at 1 MiB); a `-c 1048576` 2-device split (64 GiB of f16 KV) runs only because of the window; the single-device and `-nkvo` arms are unchanged; `--fit` on the split reports a WINDOWED cache and keeps the pinned `-c 524288` (plus the pinned-RAM ceiling's widen and drop arms, and `LLAMA_KV_REGION=0` silent); coherence identical to the r203 build on four no-window arms (3-GPU 4B, 2-GPU and 1-GPU 27B, 2-GPU host-expert 35B-A3B); prefill-logit 0.000000 / 100.000 %; Protocol A four-axis R/P/C/K 1.91x / 2.43x / 2.58x / 2.74x (acceptance 0.5869 / 0.8391 / 0.9112 / 0.9920, the r90 shape); `gate-spec-draft-window.sh` 6/6; `gate-state-pipe.sh` 2-GPU `-sm tensor` PASS with and without the window (the windowed arm failed before (3) and (4)); `GGML_CUDA_VMM_REGION_SELFTEST=1` PASS with a new multi-mapping arm; per-block build 1/1; `validate-set.sh` strict 16/16. Gate: `scripts/gate-kv-window-split.sh`. Record: `benchmarks/2026-11-01-kv-window-tensor-split-124.md`.
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Nov 5, 2026
…W (Goal A) and an attendance POOL (Goal B), both opt-in Goals A and B of TODO ggml-org#118, promoted from the `wip/kv-residency` campaign. This block is the delivery's "the KV does not have to be O(-c) of VRAM" work: TWO opt-in placements of the same cache, and each one is byte-identical to a build without it when its knob is unset. * the WINDOW (`LLAMA_KV_RESIDENT_CELLS=<cells>|auto`): the newest W cells stay in VRAM, everything older spills to pinned system RAM in the SAME VA reservation -- a positional window, no kernel or op change; * the POOL (`LLAMA_KV_REGION_POOL=<cells>`): the authoritative copy of the WHOLE context in a pinned host mirror, and a compact device pool of the pages a decode step actually attends to, which the QSA sparse read resolves through a page table (`GGML_OP_KV_POOL`). They are mutually exclusive by construction (the pool declines while a window is active) and they answer the same question from opposite ends: the window keeps the *newest* cells hot, the pool keeps the *attended* cells hot. Both report `is_streaming()`, so a streamed cache takes the sparse QSA decode arm (B2, below). ========================================================================== PART 1 -- the WINDOW (Goal A, promoted in r178) ========================================================================== Goal A of TODO ggml-org#118, promoted from the `wip/kv-residency` campaign. WHAT IT DOES. The KV cache's VRAM cost becomes a WINDOW of the newest `W` cells instead of `-c` cells: one VA reservation (a CUDA/HIP VMM region) holds the whole cache, the window's cells are backed by VRAM and everything below them by pinned system RAM. `set_rows`, the in-place rope shift, `state_write/read`, the kq mask and the FA kernels keep addressing one contiguous range, so no kernel and no op changes. The window slides with the watermark in whole map units, so a remap happens once per few thousand tokens and the apparatus itself is free (a zero-spill arm measures the same as plain). WHY. (a) A context that OOMs today runs: 27B Q8_0 `-c 262144` (8704 MiB of KV) now runs on one 32 GiB card at 128 MiB VRAM + 8576 MiB pinned host for the KV. (b) With host-resident MoE experts, the VRAM the KV does not need *yet* goes to the expert-cache arena: measured at `-c 262144`, `-n 2000`, `-ncmoe` = the model's full layer count, 51 433-token prompt, W at or above the run's depth = **+2.2 to +2.9 GiB of arena** (+3.9 to +6.7 points of residency) for free -- 122B-A10B Q4_K_XL +3.8 % decode and +4.7 % prefill, 35B-A3B Q8_0 -0.9 % decode and +3 % prefill; a `W` 35 k cells BELOW the run depth costs 11-26 % (the spill is read every token). OPT-IN, AND ONLY WHEN ASKED FOR. `LLAMA_KV_RESIDENT_CELLS=<cells>` (a number) or `=auto` (`--fit` sizes it, and only spills a context the user pinned with `-c`); unset/0 = no window. With no window the KV takes the PLAIN device buffer, so a run without the knob is byte-identical to a build without this block -- including its OOM (verified). `LLAMA_KV_SPILL_RAM_PCT` (85 % of MemAvailable) caps the pinned spill and widens the window rather than being OOM-killed; `LLAMA_KV_REGION=0` disables the provider; `LLAMA_KV_REGION_QUARANTINE=0` and `LLAMA_KV_REGION_DEBUG/TRACE/CANARY/DUMP` are the diagnosis switches. PURITY (the window). A spilled KV is numerically transparent: prefill-logit **KLD -0.000000 / 100.000 %** on a spilling 27B arm and -0.000000 / 99.994 % on a spilling Flash-Next (two KV caches: the attention KV and the QSA indexer), text byte-identical on 27B (f16 and q8_0), 4B, 35B-A3B and Flash-Next, and the state paths, the context-checkpoint path and the MTP verify widths all green on arms that provably spill. Two driver hazards are held: a kind flip zeroes a neighbouring live host mapping unless the released physical is held across the create (`LLAMA_KV_REGION_QUARANTINE`, default on -- `=0` reproduces the corruption), and every tensor in a windowed region is placed on the driver's map granularity so a slide step coincides with a mapping. An idle-slot park is REFUSED on a region-backed cache (the server then saves the slot to the prompt cache and clears it, which is byte-identical to the parking gate's reference) because a park moves cells above the region's mapped watermark through the copy engine, which faults the GPU. FIT. `--fit` sizes and reports the window (`auto`), or honours and reports a numeric `W`: the resident/spill split, the VRAM saved, and the per-token read cost at the model's full context from the backend's calibrated link rate. The fit identifies the KV's bytes by the region buffer TYPE, and its measurement context is a `no_alloc` probe that declines a window -- so the probe takes the region buffer explicitly (`llama_kv_region_set_probe`); without that the fit cannot see the KV, reports an over-budget config and aborts instead of sizing the window (the r178 regression). GATES (1 GPU, gfx1201): default path byte-identical (`5ba44647188f`) and still OOMs; VMM selftest PASS and FAIL with the hold disabled; windowed arms 305 `e2cea6fa6670` = plain at W=1024/2048/4096 (spilling at 1024: 128 MiB host), `QUARANTINE=0` -> 325 `fb65430049e9` (the hazard); `--fit` sizes `auto` (96680 of 262144 cells, 3210 MiB resident) and reports a numeric W; `gate-ckpt-reuse.sh` / `gate-state-pipe.sh` / MTP verify widths on spilling arms; `test-backend-ops -o FLASH_ATTN_QSA` 26/26; `check-gpu-faults.sh` clean. Not in this block: the campaign's Goal B (a sparse attended set) and Goal C (the MTP drafter ring, `LLAMA_SPEC_DRAFT_WINDOW`) -- both remain campaign work -- and A1 (the superseded two-base FA read). Records: `wip/kv-residency/A2-MIXED-BACKING.md` (§3.7.9, §3.7.11), `HANDOVER.md`. MULTI-DEVICE `--fit` (r181; the window itself reaches a tensor split in r204, at the end of this message): the KV-region glue is now safe on a Meta (tensor-split) device, and `auto`'s decision reaches the cache as a decision. r178 made default `--fit` abort on ANY `-sm tensor` run with more than one device: the fit's KV probes and the cache's own region lookups call `ggml_backend_dev_backend_reg(dev)` and hand it to `ggml_backend_reg_get_proc_address`, and a Meta device has no backend reg (`device->reg == NULL`), so `GGML_ASSERT(reg)` fired at model load. Three paths asserted: the fit probe (any run), the runtime buft lookup (a numeric W), and the spill budget/link lookups (a numeric W below `-c`). r181 makes a null reg read as "not provided" and declines the window with one message naming the tensor split (fit and cache), keeping the KV fully resident -- which is the r181 state; r204, below, is what makes the backend answer there. Three wiring defects in the same code, all visible on ONE device: - `auto`'s "no window needed" decision (0) was indistinguishable from "nobody decided", so the cache warned "--fit did not run" immediately after the fit had decided exactly that. `llama_kv_region_set_resident_cells` now records that a decision was made (`llama_kv_region_resident_cells_decided`), and a decided 0 is silent. - every run without the knob logged "the windowed KV is unavailable for this cache (no spilled cells)". That message now only fires when a window was actually requested and declined for a real reason. - the pinned-RAM ceiling clamp could raise W past the VRAM budget and then be reported as "does not make this fit either". It is now only taken while the wider window still meets the VRAM target; otherwise the fit says the ceiling cannot be served at this `-c` and drops the window (which the fit then fits by reducing the context). That ordering is not cosmetic: an intermediate form of this fix accepted a 235 GiB pinned spill plan for a 4B at `-c 8388608`, and creating it OOM-killed the test box. GATES (the window, gfx1201): `--fit on` (default) at 2 and 3 devices, `-sm tensor`, with no knob / a numeric W / `auto`, fit on and off: no assert, tokens produced, exactly one message per requested window. `-sm layer` 2 devices and 1 GPU still take the window per device (numeric W), and `auto` still sizes the 27B Q8_0 `-c 262144` q8_0 arm identically (123265 of 262144 cells, 4092.8 MiB resident / 4611.2 MiB spilling). One device, no knob: no KV message at all. Purity unchanged: plain vs a SPILLING windowed arm prefill-logit KLD 0.000000 / 99.990 % (q8_0 KV), greedy text byte-identical on that arm; 35B-A3B (1 GPU and 2-GPU `-sm tensor`), dense 27B and the canonical 27B Q8_0 prefill-logit gate (0.000000 / 100.000 %) byte-identical to r180; MTP Protocol A unchanged (tensor acceptance 0.60816 = 1937/3185, plain == draft-mtp); no GPU faults. ========================================================================== PART 2 -- the ATTENDANCE POOL (Goal B, promoted in r190) ========================================================================== The attention KV lives twice: its AUTHORITATIVE copy in a pinned host MIRROR (cell-indexed, so the writers, state_write/state_read, the K-shift, defrag and seq_park all work on it unchanged -- the writer rule) and a compact DEVICE POOL of pages of one indexer block (compress_ratio cells) with a page table block -> slot and its inverse. A decode step resolves its top-k selection through the table and fills the pages it missed from the mirror; the QSA reader gathers K/V at the pool slots while the mask stays cell-indexed. LLAMA_KV_REGION_POOL=<cells>, unset/0 = off = byte-identical. Contents. - ggml/src/ggml-cuda/kv-pool.{cu,cuh}: GGML_OP_KV_POOL. MARK sets use[slot] = epoch for every page this launch reads AND every page the batch just wrote (the graph's k_idxs), and queues the written ones for re-fill; CLAIM takes a slot for each DISTINCT missing block (the table CAS is the dedupe) and never takes a slot MARK protected; MAP+FILL writes each selected cell's pool position into the reader's K/V id list and copies the claimed and dirty pages from the mirror, K and V sharing slots. The epoch is a device counter incremented once per launch: the graph bakes pointers, never counters, and nothing is allocated per launch. - ggml-cuda.cu: the pool's pinned host mirror buffer type -- a DEVICE buffer type whose allocation is pinned host memory (`ROCm_Host` reports is_host, which would send the KV's writers and the FA read to the CPU on a discrete device), and its proc-address entry. - llama-kv-cache: the eligibility, the per-layer pool tensors (pool_k/pool_v, tbl, inv, use, one shared counter block), the resolve wiring into the QSA id list, kv_pool_serves() (a batch too wide for the pool takes the cell-indexed path), the teardown accounting (LLAMA_KV_POOL_STATS takes a PATH: a line on stderr sits inside the generated text), and memory_breakdown() charging the mirror to the host bucket so `--fit` does not reserve it as VRAM. - llama-memory-hybrid-idx / llama-memory-hybrid / llama-memory: the second id list (the K/V gather follows the page table while the mask stays cell-indexed), the flag threading, and the pool's byte accounting for `--fit` (llama_get_kv_pool_bytes()). - models/qwen4exp.cpp: a pooled cache reports is_streaming() and the sparse arm uses the pool's id list; the MTP draft's own cache is never pooled (its attention is dense). - llama-context / the async state copies: the mirror's buffer type is accepted by the batched save and restore (its bytes are host memory, staged through the pinned state_stage). - common/fit.cpp + src/llama-ext.h: the pool's split in --fit's arithmetic and report (the mirror is pinned host RAM, the pool is VRAM), and no context-reduction interpolation while the pool is active -- the pool's VRAM is fixed, so reducing -c frees nothing and the interpolation would divide by a near-zero bytes-per-context delta. Invariants, each one caught by the greedy text. 1. MARK then CLAIM: a claim must never evict a page the same launch reads. Without MARK the round-robin victim could be a page another row still needs (the text diverged ~400 chars in, and a pool larger than the whole cache hid it completely). 2. Claim ATTEMPTS are not distinct blocks: a slot per id attempt wrapped the cursor within one 4-row batch, so two blocks shared a slot and a just-resolved block went unresident. The table CAS dedupes first, so only distinct blocks consume a slot and kv_pool_serves() bounds the distinct count. 3. No transient scratch in a captured graph: the fill list lived in a ggml_cuda_pool_alloc that is freed at the end of the op, and a captured graph bakes the pointer, so a replay wrote into whatever op had been handed that block ("values verify clean, text differs run to run"). It lives in the counters tensor. 4. The mirror is AUTHORITATIVE: the writers land in it and a declared page is re-filled from it before the attention reads it, so an eviction costs nothing and nothing has to be invalidated -- except by a path that rewrites cells in place without going through the writers (the K-shift, a state restore), which calls kv_pool_invalidate(). 5. Eligibility is narrow on purpose: one stream, non-MLA, K and V both present, !v_trans, a uniform compress_ratio and cell geometry, no window active, a device-offloaded cache, and only the trunk context of a qwen4exp model. Anything else declines with one message and the KV is unchanged. 6. The pool is floored at one decode band's worth of blocks (8 x ceil(width/page) pages) so a verify batch cannot exhaust the slot budget, and the mirror is bounded at creation by LLAMA_KV_SPILL_RAM_PCT (it is pinned, non-swappable RAM) -- over the ceiling the pool is declined loudly instead of being OOM-killed. Measured (Flash-Next GSQ-IQ3_XXS, 1 GPU, -ncmoe 48, q8_0, the PLE flags, arms interleaved in one batch, -n 512, MTP depth 4; t/s and tokens/step): depth (ctx) dense sparse pool (204 MiB) text (-n 64) 5 298 (16 384) 72.09 71.58 71.27 pool == sparse: 332 chars dd1981213373 102 899 (131 072) 59.10 54.70 54.65 (5.3k / 51 475 references; dense differs) 180 035 (196 608) 48.94 43.16 43.41 pool == sparse: 861 chars 263c7f2be4d9 The pool lands ON the sparse ceiling at every depth (+0.5 / +0.6 / +0.58 %), so its placement is free and what remains against a resident KV (-7 % / -11 %) is the sparse decode arm's own indexer cost (block 11), not the KV's storage. A 204 MiB pool replaces the resident attention KV's 1 632 MiB at 103k / 2 448 MiB at 180k, and the freed VRAM goes to the expert arena: 103k plain decode, -n 2000, 23 579.8 -> 25 018.6 MiB (+1 438.8 MiB, +18 slots/table), expert hit 96.26 -> 97.02 %, cold reads 42.0 -> 31.6 GiB. The pool's own cost is 0.10-0.11 ms/token (mark/claim/map+fill) with fills 0.03-0.05 ms/step at 92-99 % hits, which is why a better page policy (LRU / F-LRU / a heat prior) is measured dead at this shape. Full numbers and the three-depth table: ../wip/kv-residency/BA-POOL-DESIGN.md §7-§8. PURITY (the pool). Greedy text pool == the resident sparse arm at 5.3k (332 dd1981213373), 51 475 depth (854 43b30de151b9) and 180k (861 263c7f2be4d9), with the dense arm differing as documented (GREEDY-PURITY §45/§63); LLAMA_KV_POOL_VERIFY=1 0 mismatches on every arm; gate-prefill-logits --ab "LLAMA_KV_REGION_POOL=..." 0.000000 / 100.000 % on the pool arm (base PPL 2.9225, bit-identical to the campaign's own base); gate-park-idle-slots, gate-ckpt-reuse and gate-state-pipe PASS on a pooled cache (the mirror is authoritative, which is what makes them trivial); test-backend-ops -o FLASH_ATTN_QSA pass; no GPU faults; and `--fit` accepts the arms that only fit with the pool (-ncmoe 21/22 at -c 262144: refused without it, accepted with it; -fitp moves 3 264 MiB from the device row to Host). ========================================================================== PART 3 -- a STREAMED cache takes the sparse decode arm (B2) ========================================================================== A cache that is streaming at the depth it reads -- a window the used extent has passed, or a pool -- takes the sparse QSA decode arm; a resident cache keeps the dense one. llama_kv_cache::is_streaming() plus the qwen4exp arm policy, LLAMA_QSA_DENSE_DECODE_STREAM=0 to restore the old behaviour. Measured on a spilled KV (Flash-Next IQ3_XXS, -ncmoe 48, q8_0, 1 GPU, -n 400, 2 reps): +34.3 % at 102 899 depth (23.42 -> 31.43 t/s) and +47.3 % at 180 035 (16.51 -> 24.31); a resident cache byte-identical (853 77a40bf40be1). This is a decode-ARM choice, i.e. a different attention regime (like GREEDY-PURITY §45/§63), so a streamed arm's text differs from the old dense-arm text by construction and a resident arm is the oracle. ========================================================================== DEFAULT OFF, for both placements ========================================================================== Neither knob is a speed feature on a config whose KV fits: the window costs the depth below W (11-26 %) and the pool costs the sparse-vs-dense gap (-7 % at 103k, -11 % at 180k). They are FITTABILITY features -- they turn an OOM into a run and they hand the freed VRAM to the expert arena -- so both are opt-in and both stay byte-identical, including the OOM, with their knobs unset. Do not "fix" the defaults. Goal C (the MTP drafter ring, TODO ggml-org#121) joins the same block -- it is the same claim applied to the draft context, and its default follows the delivery's own rule because it measures positive. `LLAMA_SPEC_DRAFT_WINDOW` gives the MTP draft context a sliding window instead of a `-c`-sized KV: unset or `auto` is the adaptive policy (a quarter of the context, clamped to [32768, 65536] cells), `0` is off (byte-identical to a build without it) and `N` is a cell count. The drafter reads its last few thousand tokens, so a window at or above that is free and one far below it costs 7-9 % of decode; the clamps keep it above that band, and the target verifies every token it proposes, so a truncated draft can only be slower. The ring is the shipped reclaim in `llama_kv_cache::find_slot` (`n_swa`), not a new allocator, and the derived kq mask stays valid -- its predicate compares each cell's POSITION, so a recycled cell reports its new one. The VRAM win needed one more piece: an embedded MTP head has no GGUF of its own, so the slab's draft reserve was the flat 3584 MiB and the freed VRAM never reached the expert arena. For an embedded MTP head with an active window the reserve is now derived from the model's own metadata with the weights zeroed (they are the target's) and the KV sized by the window: aux 3.50 -> 0.76 GiB, i.e. the arena gains ~2.8 GiB. A separate MTP draft GGUF (qwen4exp/Flash-Next) and an un-windowed run keep the flat constant exactly as before, and a declined arena preflight now re-evaluates when the smaller real value arrives instead of latching on the load-time estimate. Measured (1 GPU; one R9700; `-n 2000`/`-n 3000`; static depth 3; interleaved): * 35B-A3B Q8_0 `-ncmoe 48 -c 262144` q8_0 KV, 51 433-token prompt: arena 20 910 -> 23 715 MiB (residency 64.1 -> 72.7 %), decode 111.2 -> 113.7 t/s at `-n 3000` (+2.2 %; +2.8-4.9 % at `-n 2000`), prefill +3.4 %, drafts byte-for-byte the same count (1995/3011) -- the window truncates nothing the drafter used. * dense 27B UD-Q4_K_XL `-c 102400`, MTP Protocol A `-n 3000`, reasoning-pinned: layer 71.9 -> 72.1, tensor 72.6 -> 72.5 (neutral), acceptance 2083/2747 identical in all four arms. * target greedy text byte-identical across off/auto/4096, and plain == draft-mtp == draft-mtp(W=512) at `-c 16384` with a 5256-token prompt and 3000 generated tokens (10 158 chars, sha 99b267e8dc3e), i.e. no wrong answer under constant cell reuse. * gates on a windowed draft: `gate-park-idle-slots.sh` (35B, -ncmoe 48, `-c 65536`: 3 park moves, park == lazyoff), `gate-ckpt-reuse.sh` (4B, `-c 131072`: draft cache 33280 of 131072), `gate-state-pipe.sh` (35B, `-c 65536`: all five arms) -- all PASS with `MTP draft KV window = 32768 cells` in their logs. r194 corner fixes (found by a configuration battery against Flash-Next after r193): * LLAMA_KV_REGION_POOL is capped at the cache's own cell count. =1000000 on a 262144-cell context used to take a 12451 MiB device pool of 250000 pages where only 65536 blocks exist (never claimed, arena -4 GiB); it is now 3264 MiB / 65536 pages, and a small context clamps the same way. * the draft KV window sizes only the reserve of the cache it actually windows. A separate -md MTP head (Flash-Next) keeps its full -c cache, but the reserve was derived with the window: 921 MiB where the honest number is 1566 (kv 217 vs 862) at -c 262144, the under-charge direction. Embedded heads (qwen3.5/3.6/3.8) are unchanged (776 MiB on the 35B). The VRAM cliff at -c 262144 is documented (not code): the 768 MiB default headroom is one hipBLASLt workspace short for the first prefill, GGML_CUDA_SLAB_HEADROOM_MIB=1536 is 3/3 requests clean. Amendment (TODO ggml-org#129's sibling): `-nkvo` declines the window, and the streamed arm keys on the placement. The window is a DEVICE region plus a pinned host tail, but its guard did not test `offload`: with `-nkvo` the per-layer buffer is chosen inside `if (offload)` and stays plain pageable host memory, while the plan block still logged "WINDOWED KV ENABLED", reserved pinned-RAM spill budget and left `kv_resident_cells` set. `is_streaming()` then keyed the streamed (sparse) decode arm on that plan -- qwen4exp consumes it -- for a KV with no region at all. Measured: `-nkvo LLAMA_KV_RESIDENT_CELLS=64` built a plain `CPU KV buffer` of the whole context while announcing a 64-cell VRAM window. The window now declines once, with the reason (the pool already declines on `!offload`), so `-nkvo` means "no streamed placement"; `is_streaming()` tests `kv_region`, the placement actually taken, which also covers a device cache whose region buft the backend refused. Text is unchanged in every arm (the decline is a no-op: `-nkvo` + window already read as `-nkvo` alone). Amendment (issue ggml-org#264): the draft window is PER SEQUENCE, and under `--kv-unified` its cell count is `(win + one batch) x n_seq_max`. A unified cache holds every sequence in ONE stream, so the r193 sizing (`win + n_ubatch` cells) was shared by all of them: once the first sequence had filled its window the tail was all the room left, the tail is where that sequence's own ring writes, and a second sequence's first batch had no contiguous run to be placed in -- `find_slot` refused, and every request on that slot answered `decode() failed: failed to process speculative batch` (HTTP 500) while the drafter ran. Reported on `--kv-unified -np 2` with a 65 536-cell window at `-c 262144` after slot 0 held ~100k tokens; reproduced here with a forced 8192-cell window. A per-stream cache (no `--kv-unified`) already sized each stream separately and is unchanged. `llama_spec_draft_kv_cells()` is now the one geometry function -- the cache (`create_memory`), the slab's draft reserve estimate and the "is a window active" test in `common` all call it, so the reserve can never under-charge an allocation. It grants `win` per sequence plus one placeable batch (`(win + n_ubatch) * n_seq_max`, capped at the context), and DECLINES the window when that does not fit the context per sequence rather than lowering it to `per_seq - n_ubatch`: a window that small saves one batch of cells per sequence and masks the drafter's newest cells to do it. `llama_spec_draft_window_cells()` stays the policy (it is the per-sequence window). n_seq_max == 1 -- every `llama-cli`/`llama-bench` run -- measures exactly what it did (cells 1536 for a 1024-cell window at `-c 8192`), so no single-sequence arm changes at all. Measured (dense 27B, 1 GPU, `-np 2 --kv-unified`): the issue's scenario now answers both slots, and `scripts/gate-spec-draft-window.sh` (new) drives 6 requests over 2 slots with a 1024-cell window -- both rings wrapping, prompts full re-prefilled by swapping them between slots -- with output byte-identical to `LLAMA_SPEC_DRAFT_WINDOW=0` on every step and draft acceptance identical (17/36, 23/23). Greedy text `plain == draft-mtp == draft-mtp(W=1024) == draft-mtp(W=0)` (876 chars, sha 8c8fd395402f) at `-c 16384`. And the reserve now charges a per-STREAM (no `--kv-unified`) draft cache for every stream it allocates: `n_seq_max x` the per-stream cell count. Before, a multi-slot windowed MTP server without `--kv-unified` (35B-A3B `-ncmoe 40 -np 2 -c 8192`, window 1024: 2 x 1536 = 3072 cells allocated, 1536 charged) under-charged the slab's aux reserve by one stream's window -- the direction the reserve header calls dangerous. Measured: 3072 cells reported on both the unified and the per-stream arm now. ========================================================================== PART 4 -- `-sm tensor`: the window across a split (r204, `TODO` ggml-org#124) ========================================================================== A Meta (tensor-split) device carries no backend reg, so the r181 answer was "not provided" and the window was declined on every split. `TODO` ggml-org#124 designed the fix on a one-GPU box (`archive/work/kv-residency/ A6-TENSOR-SPLIT-WINDOW.md`, changes C1-C5); it is implemented and measured here, on a 3x R9700 host, and the decline is gone. * `ggml_backend_meta_kv_region_buft / _is_kv_buft / _grow` (new, `ggml-backend.h`): the Meta buffer type over the per-child region buffer types (ALL children or nothing), the is-a-region predicate `--fit` needs (the CUDA predicate is an identity on the child's `alloc_buffer` and cannot answer for a Meta buffer type), and a grow that fans out to every child. A child that cannot be reached is a REFUSAL (-1), never the 0 the CUDA hook returns for "not a region buffer": for a Meta buffer that 0 was a silent success on unmapped VA, i.e. a batch that page-faults the GPU. * `llama_kv_cache` resolves capability, the buffer type, the spill ceiling and the link through the Meta side; a MIRRORED cache (dsv4 / HRM, `llama_model::kv_cache_split_mirrored()`) declines the window with its own message, because every device holds the whole cache there (`n_devices x W x cell_bytes`) and the pinned-spill plan is per logical cache. * `common/fit.cpp` decides the window inside the tensor-split branch: charged at its PHYSICAL `W x cell_bytes` (what all devices commit together) against `min_i(target_i / ratio_i)`, which makes the aggregate check imply every device's (the loader shards the KV along the KV-head axis by the same ratio it shards the weights), and the Meta entry's margin is now the SUM of the children's `--fit-target`s (it was child 0's, so `(n_devices - 1) x target` silently vanished from the budget). The corrected KV term applies ONLY where a window is asked for: a run without `LLAMA_KV_RESIDENT_CELLS` keeps this branch's old arithmetic exactly, so the split's pre-existing `n_devices x` KV over-count is untouched outside the window arm. Four defects the arms found, fixed in the same block: 1. the init-time window commit was rounded up to a whole map unit past the tensor's own extent, and on a split each child is its own VA reservation -- the last tensor's inflated window was refused (`the KV window (4.00 MiB) could not be committed in VRAM on device 1`). Clamped to the region's END, in whole units (clamping to the tensor's own extent was tried first and is wrong: it leaves a short mapping off the unit grid and the next slide refuses to flip). 2. `ensure_span` refused a request that covered several WHOLE mappings; one batch can advance the boundary by more than one unit, and a 1 MiB unit is floored to the driver's 2 MiB granularity, so the request covered two mappings and aborted the batch. Whole mappings now flip one at a time; a request that covers a mapping only in PART is still refused (that loses bytes on this driver). 3. the batched state save issued a 2-D D2H per device and `hipMemcpy2DAsync` fails (`invalid argument`) when the range begins in a spilled region's pinned host mapping (the tensor-split checkpoint save aborted: `cache_k_l64 (view)`, 1024 B x 4782 rows). The region-backed directions of `get/set_tensor_2d_async` now go through the region buffer's own copy, ordered behind the compute stream like the pool mirror (a blocking default-stream copy does not wait for it, and the state saved mid-batch is torn). 4. that fallback's "contiguous rows = one copy" shortcut ignored the caller's destination pitch, which for a split splice is the FULL row, wider than one device's slice: the state-pipe gate failed on every cycle of all four async arms until a tight block required BOTH pitches to equal the width. Verified (gfx1201, `ROCBLAS_USE_HIPBLASLT=0` for every fresh-process pair): text byte-identical on `win3 == ref3` (3 devices, 4B, `057ea27b1009`) and `win2 == ref2 == win2mtp == ref2mtp` (2 devices, 27B, a 5246-token prompt, `7a7430617465`; draft acceptance 0.46154 in both MTP arms), also at a 1 MiB map unit; the spill is real on EVERY device (32 mapping flips each at 4 MiB, 128 at 1 MiB); a `-c 1048576` 2-device split (64 GiB of f16 KV) runs only because of the window; the single-device and `-nkvo` arms are unchanged; `--fit` on the split reports a WINDOWED cache and keeps the pinned `-c 524288` (plus the pinned-RAM ceiling's widen and drop arms, and `LLAMA_KV_REGION=0` silent); coherence identical to the r203 build on four no-window arms (3-GPU 4B, 2-GPU and 1-GPU 27B, 2-GPU host-expert 35B-A3B); prefill-logit 0.000000 / 100.000 %; Protocol A four-axis R/P/C/K 1.91x / 2.43x / 2.58x / 2.74x (acceptance 0.5869 / 0.8391 / 0.9112 / 0.9920, the r90 shape); `gate-spec-draft-window.sh` 6/6; `gate-state-pipe.sh` 2-GPU `-sm tensor` PASS with and without the window (the windowed arm failed before (3) and (4)); `GGML_CUDA_VMM_REGION_SELFTEST=1` PASS with a new multi-mapping arm; per-block build 1/1; `validate-set.sh` strict 16/16. Gate: `scripts/gate-kv-window-split.sh`. Record: `benchmarks/2026-11-01-kv-window-tensor-split-124.md`.
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Nov 5, 2026
…W (Goal A) and an attendance POOL (Goal B), both opt-in Goals A and B of TODO ggml-org#118, promoted from the `wip/kv-residency` campaign. This block is the delivery's "the KV does not have to be O(-c) of VRAM" work: TWO opt-in placements of the same cache, and each one is byte-identical to a build without it when its knob is unset. * the WINDOW (`LLAMA_KV_RESIDENT_CELLS=<cells>|auto`): the newest W cells stay in VRAM, everything older spills to pinned system RAM in the SAME VA reservation -- a positional window, no kernel or op change; * the POOL (`LLAMA_KV_REGION_POOL=<cells>`): the authoritative copy of the WHOLE context in a pinned host mirror, and a compact device pool of the pages a decode step actually attends to, which the QSA sparse read resolves through a page table (`GGML_OP_KV_POOL`). They are mutually exclusive by construction (the pool declines while a window is active) and they answer the same question from opposite ends: the window keeps the *newest* cells hot, the pool keeps the *attended* cells hot. Both report `is_streaming()`, so a streamed cache takes the sparse QSA decode arm (B2, below). ========================================================================== PART 1 -- the WINDOW (Goal A, promoted in r178) ========================================================================== Goal A of TODO ggml-org#118, promoted from the `wip/kv-residency` campaign. WHAT IT DOES. The KV cache's VRAM cost becomes a WINDOW of the newest `W` cells instead of `-c` cells: one VA reservation (a CUDA/HIP VMM region) holds the whole cache, the window's cells are backed by VRAM and everything below them by pinned system RAM. `set_rows`, the in-place rope shift, `state_write/read`, the kq mask and the FA kernels keep addressing one contiguous range, so no kernel and no op changes. The window slides with the watermark in whole map units, so a remap happens once per few thousand tokens and the apparatus itself is free (a zero-spill arm measures the same as plain). WHY. (a) A context that OOMs today runs: 27B Q8_0 `-c 262144` (8704 MiB of KV) now runs on one 32 GiB card at 128 MiB VRAM + 8576 MiB pinned host for the KV. (b) With host-resident MoE experts, the VRAM the KV does not need *yet* goes to the expert-cache arena: measured at `-c 262144`, `-n 2000`, `-ncmoe` = the model's full layer count, 51 433-token prompt, W at or above the run's depth = **+2.2 to +2.9 GiB of arena** (+3.9 to +6.7 points of residency) for free -- 122B-A10B Q4_K_XL +3.8 % decode and +4.7 % prefill, 35B-A3B Q8_0 -0.9 % decode and +3 % prefill; a `W` 35 k cells BELOW the run depth costs 11-26 % (the spill is read every token). OPT-IN, AND ONLY WHEN ASKED FOR. `LLAMA_KV_RESIDENT_CELLS=<cells>` (a number) or `=auto` (`--fit` sizes it, and only spills a context the user pinned with `-c`); unset/0 = no window. With no window the KV takes the PLAIN device buffer, so a run without the knob is byte-identical to a build without this block -- including its OOM (verified). `LLAMA_KV_SPILL_RAM_PCT` (85 % of MemAvailable) caps the pinned spill and widens the window rather than being OOM-killed; `LLAMA_KV_REGION=0` disables the provider; `LLAMA_KV_REGION_QUARANTINE=0` and `LLAMA_KV_REGION_DEBUG/TRACE/CANARY/DUMP` are the diagnosis switches. PURITY (the window). A spilled KV is numerically transparent: prefill-logit **KLD -0.000000 / 100.000 %** on a spilling 27B arm and -0.000000 / 99.994 % on a spilling Flash-Next (two KV caches: the attention KV and the QSA indexer), text byte-identical on 27B (f16 and q8_0), 4B, 35B-A3B and Flash-Next, and the state paths, the context-checkpoint path and the MTP verify widths all green on arms that provably spill. Two driver hazards are held: a kind flip zeroes a neighbouring live host mapping unless the released physical is held across the create (`LLAMA_KV_REGION_QUARANTINE`, default on -- `=0` reproduces the corruption), and every tensor in a windowed region is placed on the driver's map granularity so a slide step coincides with a mapping. An idle-slot park is REFUSED on a region-backed cache (the server then saves the slot to the prompt cache and clears it, which is byte-identical to the parking gate's reference) because a park moves cells above the region's mapped watermark through the copy engine, which faults the GPU. FIT. `--fit` sizes and reports the window (`auto`), or honours and reports a numeric `W`: the resident/spill split, the VRAM saved, and the per-token read cost at the model's full context from the backend's calibrated link rate. The fit identifies the KV's bytes by the region buffer TYPE, and its measurement context is a `no_alloc` probe that declines a window -- so the probe takes the region buffer explicitly (`llama_kv_region_set_probe`); without that the fit cannot see the KV, reports an over-budget config and aborts instead of sizing the window (the r178 regression). GATES (1 GPU, gfx1201): default path byte-identical (`5ba44647188f`) and still OOMs; VMM selftest PASS and FAIL with the hold disabled; windowed arms 305 `e2cea6fa6670` = plain at W=1024/2048/4096 (spilling at 1024: 128 MiB host), `QUARANTINE=0` -> 325 `fb65430049e9` (the hazard); `--fit` sizes `auto` (96680 of 262144 cells, 3210 MiB resident) and reports a numeric W; `gate-ckpt-reuse.sh` / `gate-state-pipe.sh` / MTP verify widths on spilling arms; `test-backend-ops -o FLASH_ATTN_QSA` 26/26; `check-gpu-faults.sh` clean. Not in this block: the campaign's Goal B (a sparse attended set) and Goal C (the MTP drafter ring, `LLAMA_SPEC_DRAFT_WINDOW`) -- both remain campaign work -- and A1 (the superseded two-base FA read). Records: `wip/kv-residency/A2-MIXED-BACKING.md` (§3.7.9, §3.7.11), `HANDOVER.md`. MULTI-DEVICE `--fit` (r181; the window itself reaches a tensor split in r204, at the end of this message): the KV-region glue is now safe on a Meta (tensor-split) device, and `auto`'s decision reaches the cache as a decision. r178 made default `--fit` abort on ANY `-sm tensor` run with more than one device: the fit's KV probes and the cache's own region lookups call `ggml_backend_dev_backend_reg(dev)` and hand it to `ggml_backend_reg_get_proc_address`, and a Meta device has no backend reg (`device->reg == NULL`), so `GGML_ASSERT(reg)` fired at model load. Three paths asserted: the fit probe (any run), the runtime buft lookup (a numeric W), and the spill budget/link lookups (a numeric W below `-c`). r181 makes a null reg read as "not provided" and declines the window with one message naming the tensor split (fit and cache), keeping the KV fully resident -- which is the r181 state; r204, below, is what makes the backend answer there. Three wiring defects in the same code, all visible on ONE device: - `auto`'s "no window needed" decision (0) was indistinguishable from "nobody decided", so the cache warned "--fit did not run" immediately after the fit had decided exactly that. `llama_kv_region_set_resident_cells` now records that a decision was made (`llama_kv_region_resident_cells_decided`), and a decided 0 is silent. - every run without the knob logged "the windowed KV is unavailable for this cache (no spilled cells)". That message now only fires when a window was actually requested and declined for a real reason. - the pinned-RAM ceiling clamp could raise W past the VRAM budget and then be reported as "does not make this fit either". It is now only taken while the wider window still meets the VRAM target; otherwise the fit says the ceiling cannot be served at this `-c` and drops the window (which the fit then fits by reducing the context). That ordering is not cosmetic: an intermediate form of this fix accepted a 235 GiB pinned spill plan for a 4B at `-c 8388608`, and creating it OOM-killed the test box. GATES (the window, gfx1201): `--fit on` (default) at 2 and 3 devices, `-sm tensor`, with no knob / a numeric W / `auto`, fit on and off: no assert, tokens produced, exactly one message per requested window. `-sm layer` 2 devices and 1 GPU still take the window per device (numeric W), and `auto` still sizes the 27B Q8_0 `-c 262144` q8_0 arm identically (123265 of 262144 cells, 4092.8 MiB resident / 4611.2 MiB spilling). One device, no knob: no KV message at all. Purity unchanged: plain vs a SPILLING windowed arm prefill-logit KLD 0.000000 / 99.990 % (q8_0 KV), greedy text byte-identical on that arm; 35B-A3B (1 GPU and 2-GPU `-sm tensor`), dense 27B and the canonical 27B Q8_0 prefill-logit gate (0.000000 / 100.000 %) byte-identical to r180; MTP Protocol A unchanged (tensor acceptance 0.60816 = 1937/3185, plain == draft-mtp); no GPU faults. ========================================================================== PART 2 -- the ATTENDANCE POOL (Goal B, promoted in r190) ========================================================================== The attention KV lives twice: its AUTHORITATIVE copy in a pinned host MIRROR (cell-indexed, so the writers, state_write/state_read, the K-shift, defrag and seq_park all work on it unchanged -- the writer rule) and a compact DEVICE POOL of pages of one indexer block (compress_ratio cells) with a page table block -> slot and its inverse. A decode step resolves its top-k selection through the table and fills the pages it missed from the mirror; the QSA reader gathers K/V at the pool slots while the mask stays cell-indexed. LLAMA_KV_REGION_POOL=<cells>, unset/0 = off = byte-identical. Contents. - ggml/src/ggml-cuda/kv-pool.{cu,cuh}: GGML_OP_KV_POOL. MARK sets use[slot] = epoch for every page this launch reads AND every page the batch just wrote (the graph's k_idxs), and queues the written ones for re-fill; CLAIM takes a slot for each DISTINCT missing block (the table CAS is the dedupe) and never takes a slot MARK protected; MAP+FILL writes each selected cell's pool position into the reader's K/V id list and copies the claimed and dirty pages from the mirror, K and V sharing slots. The epoch is a device counter incremented once per launch: the graph bakes pointers, never counters, and nothing is allocated per launch. - ggml-cuda.cu: the pool's pinned host mirror buffer type -- a DEVICE buffer type whose allocation is pinned host memory (`ROCm_Host` reports is_host, which would send the KV's writers and the FA read to the CPU on a discrete device), and its proc-address entry. - llama-kv-cache: the eligibility, the per-layer pool tensors (pool_k/pool_v, tbl, inv, use, one shared counter block), the resolve wiring into the QSA id list, kv_pool_serves() (a batch too wide for the pool takes the cell-indexed path), the teardown accounting (LLAMA_KV_POOL_STATS takes a PATH: a line on stderr sits inside the generated text), and memory_breakdown() charging the mirror to the host bucket so `--fit` does not reserve it as VRAM. - llama-memory-hybrid-idx / llama-memory-hybrid / llama-memory: the second id list (the K/V gather follows the page table while the mask stays cell-indexed), the flag threading, and the pool's byte accounting for `--fit` (llama_get_kv_pool_bytes()). - models/qwen4exp.cpp: a pooled cache reports is_streaming() and the sparse arm uses the pool's id list; the MTP draft's own cache is never pooled (its attention is dense). - llama-context / the async state copies: the mirror's buffer type is accepted by the batched save and restore (its bytes are host memory, staged through the pinned state_stage). - common/fit.cpp + src/llama-ext.h: the pool's split in --fit's arithmetic and report (the mirror is pinned host RAM, the pool is VRAM), and no context-reduction interpolation while the pool is active -- the pool's VRAM is fixed, so reducing -c frees nothing and the interpolation would divide by a near-zero bytes-per-context delta. Invariants, each one caught by the greedy text. 1. MARK then CLAIM: a claim must never evict a page the same launch reads. Without MARK the round-robin victim could be a page another row still needs (the text diverged ~400 chars in, and a pool larger than the whole cache hid it completely). 2. Claim ATTEMPTS are not distinct blocks: a slot per id attempt wrapped the cursor within one 4-row batch, so two blocks shared a slot and a just-resolved block went unresident. The table CAS dedupes first, so only distinct blocks consume a slot and kv_pool_serves() bounds the distinct count. 3. No transient scratch in a captured graph: the fill list lived in a ggml_cuda_pool_alloc that is freed at the end of the op, and a captured graph bakes the pointer, so a replay wrote into whatever op had been handed that block ("values verify clean, text differs run to run"). It lives in the counters tensor. 4. The mirror is AUTHORITATIVE: the writers land in it and a declared page is re-filled from it before the attention reads it, so an eviction costs nothing and nothing has to be invalidated -- except by a path that rewrites cells in place without going through the writers (the K-shift, a state restore), which calls kv_pool_invalidate(). 5. Eligibility is narrow on purpose: one stream, non-MLA, K and V both present, !v_trans, a uniform compress_ratio and cell geometry, no window active, a device-offloaded cache, and only the trunk context of a qwen4exp model. Anything else declines with one message and the KV is unchanged. 6. The pool is floored at one decode band's worth of blocks (8 x ceil(width/page) pages) so a verify batch cannot exhaust the slot budget, and the mirror is bounded at creation by LLAMA_KV_SPILL_RAM_PCT (it is pinned, non-swappable RAM) -- over the ceiling the pool is declined loudly instead of being OOM-killed. Measured (Flash-Next GSQ-IQ3_XXS, 1 GPU, -ncmoe 48, q8_0, the PLE flags, arms interleaved in one batch, -n 512, MTP depth 4; t/s and tokens/step): depth (ctx) dense sparse pool (204 MiB) text (-n 64) 5 298 (16 384) 72.09 71.58 71.27 pool == sparse: 332 chars dd1981213373 102 899 (131 072) 59.10 54.70 54.65 (5.3k / 51 475 references; dense differs) 180 035 (196 608) 48.94 43.16 43.41 pool == sparse: 861 chars 263c7f2be4d9 The pool lands ON the sparse ceiling at every depth (+0.5 / +0.6 / +0.58 %), so its placement is free and what remains against a resident KV (-7 % / -11 %) is the sparse decode arm's own indexer cost (block 11), not the KV's storage. A 204 MiB pool replaces the resident attention KV's 1 632 MiB at 103k / 2 448 MiB at 180k, and the freed VRAM goes to the expert arena: 103k plain decode, -n 2000, 23 579.8 -> 25 018.6 MiB (+1 438.8 MiB, +18 slots/table), expert hit 96.26 -> 97.02 %, cold reads 42.0 -> 31.6 GiB. The pool's own cost is 0.10-0.11 ms/token (mark/claim/map+fill) with fills 0.03-0.05 ms/step at 92-99 % hits, which is why a better page policy (LRU / F-LRU / a heat prior) is measured dead at this shape. Full numbers and the three-depth table: ../wip/kv-residency/BA-POOL-DESIGN.md §7-§8. PURITY (the pool). Greedy text pool == the resident sparse arm at 5.3k (332 dd1981213373), 51 475 depth (854 43b30de151b9) and 180k (861 263c7f2be4d9), with the dense arm differing as documented (GREEDY-PURITY §45/§63); LLAMA_KV_POOL_VERIFY=1 0 mismatches on every arm; gate-prefill-logits --ab "LLAMA_KV_REGION_POOL=..." 0.000000 / 100.000 % on the pool arm (base PPL 2.9225, bit-identical to the campaign's own base); gate-park-idle-slots, gate-ckpt-reuse and gate-state-pipe PASS on a pooled cache (the mirror is authoritative, which is what makes them trivial); test-backend-ops -o FLASH_ATTN_QSA pass; no GPU faults; and `--fit` accepts the arms that only fit with the pool (-ncmoe 21/22 at -c 262144: refused without it, accepted with it; -fitp moves 3 264 MiB from the device row to Host). ========================================================================== PART 3 -- a STREAMED cache takes the sparse decode arm (B2) ========================================================================== A cache that is streaming at the depth it reads -- a window the used extent has passed, or a pool -- takes the sparse QSA decode arm; a resident cache keeps the dense one. llama_kv_cache::is_streaming() plus the qwen4exp arm policy, LLAMA_QSA_DENSE_DECODE_STREAM=0 to restore the old behaviour. Measured on a spilled KV (Flash-Next IQ3_XXS, -ncmoe 48, q8_0, 1 GPU, -n 400, 2 reps): +34.3 % at 102 899 depth (23.42 -> 31.43 t/s) and +47.3 % at 180 035 (16.51 -> 24.31); a resident cache byte-identical (853 77a40bf40be1). This is a decode-ARM choice, i.e. a different attention regime (like GREEDY-PURITY §45/§63), so a streamed arm's text differs from the old dense-arm text by construction and a resident arm is the oracle. ========================================================================== DEFAULT OFF, for both placements ========================================================================== Neither knob is a speed feature on a config whose KV fits: the window costs the depth below W (11-26 %) and the pool costs the sparse-vs-dense gap (-7 % at 103k, -11 % at 180k). They are FITTABILITY features -- they turn an OOM into a run and they hand the freed VRAM to the expert arena -- so both are opt-in and both stay byte-identical, including the OOM, with their knobs unset. Do not "fix" the defaults. Goal C (the MTP drafter ring, TODO ggml-org#121) joins the same block -- it is the same claim applied to the draft context, and its default follows the delivery's own rule because it measures positive. `LLAMA_SPEC_DRAFT_WINDOW` gives the MTP draft context a sliding window instead of a `-c`-sized KV: unset or `auto` is the adaptive policy (a quarter of the context, clamped to [32768, 65536] cells), `0` is off (byte-identical to a build without it) and `N` is a cell count. The drafter reads its last few thousand tokens, so a window at or above that is free and one far below it costs 7-9 % of decode; the clamps keep it above that band, and the target verifies every token it proposes, so a truncated draft can only be slower. The ring is the shipped reclaim in `llama_kv_cache::find_slot` (`n_swa`), not a new allocator, and the derived kq mask stays valid -- its predicate compares each cell's POSITION, so a recycled cell reports its new one. The VRAM win needed one more piece: an embedded MTP head has no GGUF of its own, so the slab's draft reserve was the flat 3584 MiB and the freed VRAM never reached the expert arena. For an embedded MTP head with an active window the reserve is now derived from the model's own metadata with the weights zeroed (they are the target's) and the KV sized by the window: aux 3.50 -> 0.76 GiB, i.e. the arena gains ~2.8 GiB. A separate MTP draft GGUF (qwen4exp/Flash-Next) and an un-windowed run keep the flat constant exactly as before, and a declined arena preflight now re-evaluates when the smaller real value arrives instead of latching on the load-time estimate. Measured (1 GPU; one R9700; `-n 2000`/`-n 3000`; static depth 3; interleaved): * 35B-A3B Q8_0 `-ncmoe 48 -c 262144` q8_0 KV, 51 433-token prompt: arena 20 910 -> 23 715 MiB (residency 64.1 -> 72.7 %), decode 111.2 -> 113.7 t/s at `-n 3000` (+2.2 %; +2.8-4.9 % at `-n 2000`), prefill +3.4 %, drafts byte-for-byte the same count (1995/3011) -- the window truncates nothing the drafter used. * dense 27B UD-Q4_K_XL `-c 102400`, MTP Protocol A `-n 3000`, reasoning-pinned: layer 71.9 -> 72.1, tensor 72.6 -> 72.5 (neutral), acceptance 2083/2747 identical in all four arms. * target greedy text byte-identical across off/auto/4096, and plain == draft-mtp == draft-mtp(W=512) at `-c 16384` with a 5256-token prompt and 3000 generated tokens (10 158 chars, sha 99b267e8dc3e), i.e. no wrong answer under constant cell reuse. * gates on a windowed draft: `gate-park-idle-slots.sh` (35B, -ncmoe 48, `-c 65536`: 3 park moves, park == lazyoff), `gate-ckpt-reuse.sh` (4B, `-c 131072`: draft cache 33280 of 131072), `gate-state-pipe.sh` (35B, `-c 65536`: all five arms) -- all PASS with `MTP draft KV window = 32768 cells` in their logs. r194 corner fixes (found by a configuration battery against Flash-Next after r193): * LLAMA_KV_REGION_POOL is capped at the cache's own cell count. =1000000 on a 262144-cell context used to take a 12451 MiB device pool of 250000 pages where only 65536 blocks exist (never claimed, arena -4 GiB); it is now 3264 MiB / 65536 pages, and a small context clamps the same way. * the draft KV window sizes only the reserve of the cache it actually windows. A separate -md MTP head (Flash-Next) keeps its full -c cache, but the reserve was derived with the window: 921 MiB where the honest number is 1566 (kv 217 vs 862) at -c 262144, the under-charge direction. Embedded heads (qwen3.5/3.6/3.8) are unchanged (776 MiB on the 35B). The VRAM cliff at -c 262144 is documented (not code): the 768 MiB default headroom is one hipBLASLt workspace short for the first prefill, GGML_CUDA_SLAB_HEADROOM_MIB=1536 is 3/3 requests clean. Amendment (TODO ggml-org#129's sibling): `-nkvo` declines the window, and the streamed arm keys on the placement. The window is a DEVICE region plus a pinned host tail, but its guard did not test `offload`: with `-nkvo` the per-layer buffer is chosen inside `if (offload)` and stays plain pageable host memory, while the plan block still logged "WINDOWED KV ENABLED", reserved pinned-RAM spill budget and left `kv_resident_cells` set. `is_streaming()` then keyed the streamed (sparse) decode arm on that plan -- qwen4exp consumes it -- for a KV with no region at all. Measured: `-nkvo LLAMA_KV_RESIDENT_CELLS=64` built a plain `CPU KV buffer` of the whole context while announcing a 64-cell VRAM window. The window now declines once, with the reason (the pool already declines on `!offload`), so `-nkvo` means "no streamed placement"; `is_streaming()` tests `kv_region`, the placement actually taken, which also covers a device cache whose region buft the backend refused. Text is unchanged in every arm (the decline is a no-op: `-nkvo` + window already read as `-nkvo` alone). Amendment (issue ggml-org#264): the draft window is PER SEQUENCE, and under `--kv-unified` its cell count is `(win + one batch) x n_seq_max`. A unified cache holds every sequence in ONE stream, so the r193 sizing (`win + n_ubatch` cells) was shared by all of them: once the first sequence had filled its window the tail was all the room left, the tail is where that sequence's own ring writes, and a second sequence's first batch had no contiguous run to be placed in -- `find_slot` refused, and every request on that slot answered `decode() failed: failed to process speculative batch` (HTTP 500) while the drafter ran. Reported on `--kv-unified -np 2` with a 65 536-cell window at `-c 262144` after slot 0 held ~100k tokens; reproduced here with a forced 8192-cell window. A per-stream cache (no `--kv-unified`) already sized each stream separately and is unchanged. `llama_spec_draft_kv_cells()` is now the one geometry function -- the cache (`create_memory`), the slab's draft reserve estimate and the "is a window active" test in `common` all call it, so the reserve can never under-charge an allocation. It grants `win` per sequence plus one placeable batch (`(win + n_ubatch) * n_seq_max`, capped at the context), and DECLINES the window when that does not fit the context per sequence rather than lowering it to `per_seq - n_ubatch`: a window that small saves one batch of cells per sequence and masks the drafter's newest cells to do it. `llama_spec_draft_window_cells()` stays the policy (it is the per-sequence window). n_seq_max == 1 -- every `llama-cli`/`llama-bench` run -- measures exactly what it did (cells 1536 for a 1024-cell window at `-c 8192`), so no single-sequence arm changes at all. Measured (dense 27B, 1 GPU, `-np 2 --kv-unified`): the issue's scenario now answers both slots, and `scripts/gate-spec-draft-window.sh` (new) drives 6 requests over 2 slots with a 1024-cell window -- both rings wrapping, prompts full re-prefilled by swapping them between slots -- with output byte-identical to `LLAMA_SPEC_DRAFT_WINDOW=0` on every step and draft acceptance identical (17/36, 23/23). Greedy text `plain == draft-mtp == draft-mtp(W=1024) == draft-mtp(W=0)` (876 chars, sha 8c8fd395402f) at `-c 16384`. And the reserve now charges a per-STREAM (no `--kv-unified`) draft cache for every stream it allocates: `n_seq_max x` the per-stream cell count. Before, a multi-slot windowed MTP server without `--kv-unified` (35B-A3B `-ncmoe 40 -np 2 -c 8192`, window 1024: 2 x 1536 = 3072 cells allocated, 1536 charged) under-charged the slab's aux reserve by one stream's window -- the direction the reserve header calls dangerous. Measured: 3072 cells reported on both the unified and the per-stream arm now. ========================================================================== PART 4 -- `-sm tensor`: the window across a split (r204, `TODO` ggml-org#124) ========================================================================== A Meta (tensor-split) device carries no backend reg, so the r181 answer was "not provided" and the window was declined on every split. `TODO` ggml-org#124 designed the fix on a one-GPU box (`archive/work/kv-residency/ A6-TENSOR-SPLIT-WINDOW.md`, changes C1-C5); it is implemented and measured here, on a 3x R9700 host, and the decline is gone. * `ggml_backend_meta_kv_region_buft / _is_kv_buft / _grow` (new, `ggml-backend.h`): the Meta buffer type over the per-child region buffer types (ALL children or nothing), the is-a-region predicate `--fit` needs (the CUDA predicate is an identity on the child's `alloc_buffer` and cannot answer for a Meta buffer type), and a grow that fans out to every child. A child that cannot be reached is a REFUSAL (-1), never the 0 the CUDA hook returns for "not a region buffer": for a Meta buffer that 0 was a silent success on unmapped VA, i.e. a batch that page-faults the GPU. * `llama_kv_cache` resolves capability, the buffer type, the spill ceiling and the link through the Meta side; a MIRRORED cache (dsv4 / HRM, `llama_model::kv_cache_split_mirrored()`) declines the window with its own message, because every device holds the whole cache there (`n_devices x W x cell_bytes`) and the pinned-spill plan is per logical cache. * `common/fit.cpp` decides the window inside the tensor-split branch: charged at its PHYSICAL `W x cell_bytes` (what all devices commit together) against `min_i(target_i / ratio_i)`, which makes the aggregate check imply every device's (the loader shards the KV along the KV-head axis by the same ratio it shards the weights), and the Meta entry's margin is now the SUM of the children's `--fit-target`s (it was child 0's, so `(n_devices - 1) x target` silently vanished from the budget). The corrected KV term applies ONLY where a window is asked for: a run without `LLAMA_KV_RESIDENT_CELLS` keeps this branch's old arithmetic exactly, so the split's pre-existing `n_devices x` KV over-count is untouched outside the window arm. Four defects the arms found, fixed in the same block: 1. the init-time window commit was rounded up to a whole map unit past the tensor's own extent, and on a split each child is its own VA reservation -- the last tensor's inflated window was refused (`the KV window (4.00 MiB) could not be committed in VRAM on device 1`). Clamped to the region's END, in whole units (clamping to the tensor's own extent was tried first and is wrong: it leaves a short mapping off the unit grid and the next slide refuses to flip). 2. `ensure_span` refused a request that covered several WHOLE mappings; one batch can advance the boundary by more than one unit, and a 1 MiB unit is floored to the driver's 2 MiB granularity, so the request covered two mappings and aborted the batch. Whole mappings now flip one at a time; a request that covers a mapping only in PART is still refused (that loses bytes on this driver). 3. the batched state save issued a 2-D D2H per device and `hipMemcpy2DAsync` fails (`invalid argument`) when the range begins in a spilled region's pinned host mapping (the tensor-split checkpoint save aborted: `cache_k_l64 (view)`, 1024 B x 4782 rows). The region-backed directions of `get/set_tensor_2d_async` now go through the region buffer's own copy, ordered behind the compute stream like the pool mirror (a blocking default-stream copy does not wait for it, and the state saved mid-batch is torn). 4. that fallback's "contiguous rows = one copy" shortcut ignored the caller's destination pitch, which for a split splice is the FULL row, wider than one device's slice: the state-pipe gate failed on every cycle of all four async arms until a tight block required BOTH pitches to equal the width. Verified (gfx1201, `ROCBLAS_USE_HIPBLASLT=0` for every fresh-process pair): text byte-identical on `win3 == ref3` (3 devices, 4B, `057ea27b1009`) and `win2 == ref2 == win2mtp == ref2mtp` (2 devices, 27B, a 5246-token prompt, `7a7430617465`; draft acceptance 0.46154 in both MTP arms), also at a 1 MiB map unit; the spill is real on EVERY device (32 mapping flips each at 4 MiB, 128 at 1 MiB); a `-c 1048576` 2-device split (64 GiB of f16 KV) runs only because of the window; the single-device and `-nkvo` arms are unchanged; `--fit` on the split reports a WINDOWED cache and keeps the pinned `-c 524288` (plus the pinned-RAM ceiling's widen and drop arms, and `LLAMA_KV_REGION=0` silent); coherence identical to the r203 build on four no-window arms (3-GPU 4B, 2-GPU and 1-GPU 27B, 2-GPU host-expert 35B-A3B); prefill-logit 0.000000 / 100.000 %; Protocol A four-axis R/P/C/K 1.91x / 2.43x / 2.58x / 2.74x (acceptance 0.5869 / 0.8391 / 0.9112 / 0.9920, the r90 shape); `gate-spec-draft-window.sh` 6/6; `gate-state-pipe.sh` 2-GPU `-sm tensor` PASS with and without the window (the windowed arm failed before (3) and (4)); `GGML_CUDA_VMM_REGION_SELFTEST=1` PASS with a new multi-mapping arm; per-block build 1/1; `validate-set.sh` strict 16/16. Gate: `scripts/gate-kv-window-split.sh`. Record: `benchmarks/2026-11-01-kv-window-tensor-split-124.md`.
This PR makes the changes required to push the model to pypi, where it now resides
Edit: sorry for the pings lads this was supposed to go into my fork.