Skip to content

Add requirements to readme - #269

Merged
prusnak merged 2 commits into
masterfrom
readme-reqs
Mar 18, 2023
Merged

prusnak merged 2 commits into
masterfrom
readme-reqs

Conversation

@prusnak

@prusnak prusnak commented Mar 18, 2023

Copy link
Copy Markdown
Contributor

No description provided.

Comment thread README.md Resolved
@prusnak
prusnak merged commit 1e5a6d0 into master Mar 18, 2023
@prusnak
prusnak deleted the readme-reqs branch March 18, 2023 21:25
phuongncn pushed a commit to phuongncn/llama.cpp-gx10-dgx-sparks-deepseekv4 that referenced this pull request Apr 28, 2026
I broke it with PR ggml-org#265. I was testing with a model where
the wk_b and wk_v tensors were present, so didn't need to be computed,
so didn't notice that the change I made to ggml_compute_forward_dup_q
breaks that computation.

Co-authored-by: Iwan Kawrakow <[email protected]>
ckti pushed a commit to ckti/llama.cpp-consolidated that referenced this pull request Aug 22, 2026
tests: port 11 DSv4-shaped TQ MUL_MAT cases from the deleted sync/upstream-master
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Nov 5, 2026
…b and cache engine)

old-06 (generic MoE expert-cache iface, scheduler routed-expert rebalance, Meta
delegation, the movable-boundary slab + allocator fail-soft, the host-expert
pinned loader / --host-experts, the expert-cache engine, the h2d staging ring,
GGML_ENV_STR) + old-09b (slab headroom) + old-11 (graph handling for
expert-offload decode) + old-15's slab/cache extensions (narrow2, host pool,
stage_gather, the fattn_stage arena accounting, the cache-aware mmvq/mmq reads
and the try_fuse stand-down).

The qwen4exp/HC and cache-blocks (cpy_batch) try_fuse arms are still stripped
(they belong to 10 qwen4exp); the cache-aware arms present here are the
slab/engine ones.

Gates: build all OK; 35B-A3B -ncmoe 40 cache off == on (identical greedy text).

Env-read hygiene (no behaviour change): resolve the environment variables this block adds on hot
paths once into function-local statics instead of calling getenv() per alloc/reserve/ubatch --
GGML_SCHED_STAGE, LLAMA_DROP_COMPUTE_BUFFERS, GGML_CUDA_WORK_ALLOC_DEBUG,
GGML_CUDA_CACHE_GEOM_DEBUG, GGML_CUDA_POOL_MIN_FREE_MIB, MOE_EXPERT_CACHE_VALIDATE_LAYER.  Also
make GGML_ENV_STR cache the value (std::string) rather than the getenv() pointer: the MSVC CRT
returns a buffer that the next getenv() call overwrites, so a cached pointer is unsafe on Windows.

Prefill cache staging (r83): a whole-table staging copy of a host-resident expert table is now
filled from the cache arena for the experts already resident and from the pinned host master for
the rest, instead of re-uploading every expert over PCIe.  The source map is a per-table
"prefill residency snapshot": a small device copy of the authoritative host `expert_slot`, rebuilt
whenever the cache writes (`g_write_seq`), the arena moves or the slot count changes, never
mutated by decode, and not the removed device-remap policy.  The destination is the ordinary
staged table in expert order, so every consumer is unchanged and the bytes are identical.
DEFAULT ON; kill switch `GGML_MOE_CACHE_STAGE=0` restores the plain whole-table upload.  A table
the slab stands down mid-prefill, an unpinned host master or a geometry mismatch declines and
falls back to the plain upload.  `moe_cache_report` prints the staged arena/host split.

Measured (2x R9700 gfx1201, Qwen3.8-Flash-Next IQ4_NL 176.9B-A3B, `-sm tensor -ncmoe 48`, 32k
ctx): prefill 1092 -> 1436 t/s (16k-token prompt, `-ub 4096`), 583 -> 839 (`-ub 2048`), 1181 ->
1585 (31.6k); `-sm layer` 742 -> 1269.  Staged H2D falls to 27% of the table (arena 46.6 GiB,
71.9% residency).  Greedy text byte-identical to r82; prefill-logit mean KLD 0 / same-top-p 100%.

Slab drop reference (r85): the prefill -> decode drop recorded the work region it had just re-reserved as
its "settled narrow" reference, but that re-reserve is the `n_rs_batch` shape, narrower than the real MTP
decode/verify graph.  Every following decode pass therefore looked "materially wider" and dropped again:
measured one drop per decode step, 66 tables re-armed and ~3.65 GiB/device of arena evicted each time
(decode 17-25 t/s instead of 45).  The reference is now max(work region observed before the drop, shape the
drop re-reserved).

Fold (r86): beta 12, slab-transient-absorption (common half).  The draft reserve is derived
from the draft GGUF instead of assumed, the draft model is loaded before the
target context so the slab measures its per-device footprint, and the
common-layer and all-reduce transients are served by the slab.  Coherence
identical, prefill-logit KLD 0.000000 / same-top-p 100 %, adaptive-MTP 4 axes +
phase probe exactly equal on the development box.

Fold (r87): force the post-prefill drop on a wide -> narrow transition.  r85 recorded
`slab_narrow_boundary = max(re-reserved narrow, drop_observed)`, but at a prefill -> decode
drop `drop_observed` is the WIDE prefill region, so an equally-wide second prefill compared
equal and never dropped: the wide work buffer stayed allocated, the arena was not re-armed, and
every request after the first decoded at ~half speed (Flash-Next IQ4_NL field config,
2 GPUs -sm tensor -ncmoe 46 -ub 6144 + MTP n6: 68.5 -> 35.7 t/s; with the fix 68.1 -> 69.4).

Fold (r91): never auto-size the MoE expert arena on a shared host/device memory pool.
On an integrated GPU (gfx1151/Strix Halo) the device "VRAM" window is the same physical pool as
host RAM, so AUTO arena sizing and the movable-boundary slab (free - reserve) both map the
machine: measured 121 GiB resident + 13 GiB swap, and bounding the arena alone hands the same
overcommit to the slab.  `moe_cache_preflight` now declines the cache on `prop.integrated`,
keyed before any table registers, so the run is the documented host-expert path and the wrapper
disarms the slab; `common/fit.cpp` stops reserving slab headroom + arena for such a device.
Opt-in override `MOE_EXPERT_CACHE_UNIFIED=1` requires an explicit `MOE_EXPERT_CACHE_MIB` AND an
explicit `GGML_CUDA_SLAB_RESERVE_MIB` (bounded by construction).  A discrete GPU is untouched:
gfx1201 35B-A3B `-ncmoe 40` loads with identical preflight/SLAB_INIT/arena lines; coherence and
the prefill-logit gate are unchanged (guard == `MOE_EXPERT_CACHE_MIB=0`).
Record: archive/work/umem-arena-guard/.

Fold (r95): rdna3-verify-fusions (PR ggml-org#193, briansp2020): the batched f32 CPY run is admitted
on RDNA3_0 as well (GGML_CUDA_CC_IS_RDNA3_0 alongside GGML_CUDA_CC_IS_RDNA4; RDNA3_5 stays
out).  One launch for up to 16 same-layout copies, element copies in ggml_cpy's flat order:
bit-identical.  The fusion is inactive where a split's concurrent events are live, and
GGML_CUDA_FUSE_CPY_BATCH=0 still turns it off.

Fold (r96, PR ggml-org#186, briansp2020): in `ggml_backend_sched_split_graph`, a second `MUL_MAT_ID` consumer of
the expert weights the current split already stages starts a split of its own, so the re-registration
path stages them again for that consumer's own routing.  With both consumers in one split neither can be
served by the expert cache (the arena holds one routing's slots) and the scheduler's guarded fast paths
decline, so the whole table is copied for every such prompt chunk: qwen4exp's gathered logits tail next
to its full-row MTP export tail meant the last layer's 1062 MiB table per chunk (Flash-Next
`-sm tensor -ncmoe 10`: -30 % / -47 % TTFT on the follow-up turns, bit-identical text), and on
`-sm layer` the second consumer read the arena slots staged for the first consumer's routing, which
silently produced non-greedy-pure text with 0.00000 draft acceptance.  `GGML_SCHED_MOE_DUP_SPLIT=0`
restores the merged split (A/B and bisection).

Fold (r96, PR ggml-org#189, briansp2020): the meta backend's `get_tensor_async` shares the synchronous read's
split arithmetic instead of asserting `offset == 0` and one segment, so a caller can batch many
per-device reads behind one synchronize (a context checkpoint's per-sequence cells).  Calls that worked
before issue the same copies as before.

Fold (r99, TODO ggml-org#56): the scheduler must invoke the copy callback again, so the upstream
`llama_moe_cache` (`--moe-cache-mib`) works.  This block's rewrite of `ggml_backend_sched_copy_input` kept no
`sched->callback_copy` call, and that call is the only thing in the tree that drives
`llama_moe_cache::copy()`: the slot map stayed `0xff` (-1) while the graph had already swapped the routed op's
`src0` for the cache bank and its ids for `GET_ROWS(slot_map, ids)`, so `MUL_MAT_ID` indexed the bank with -1
(wrong values where the page below the bank is mapped, an HSA page fault where it is not).  The call is
restored at base's position (after the wait-before-overwrite) and in the branch with no `MUL_MAT_ID`
consumer, which is where the slot map lands (its consumer is a `GET_ROWS`); the delivery's own expert branch
(device gather, cache take-over, pruning) is byte-for-byte unchanged, so no host expert table can reach the
callback.  `llama_context::sched_copy_experts` now answers only for the upstream cache: its per-op
staging/pruning copy has been dead since this block's scheduler took that over, and would double-stage every
host expert table if it ever ran again.

Inert unless `--moe-cache-mib` is set (`moe_cache` is then null and the callback returns false).  Gates
(gfx1201, ROCm 10.1.0): `test-llama-archs -s 42` **375/375** (was 373/375; `deepseek2`'s `MoE cache` row
2.10e-10, the upstream base's own value, was 4.02e-03), also 375/375 with `GGML_CUDA_ASYNC_INPUT=0`;
host-expert greedy text byte-identical to r98 (35B-A3B `-ncmoe 40`); prefill-logit KLD 0.000000 / 100.000 %.
The upstream cache's large-batch `copy_experts()` arm stays unreached (this block's scheduler owns that
pruning); values are identical either way, so it is a missing upstream optimisation on a path the delivery
serves with its own cache, not a correctness gap.  `--moe-cache-mib` is now correct but slower than
`MOE_EXPERT_CACHE_MIB` on this box (decode 50.1 -> 37.8 t/s on 35B-A3B `-ncmoe 40`), so it stays documented
as "works, not recommended".

Split-state walk scratch (r100, issue ggml-org#184): the per-buffer-context split-state cache pre-warm walks
the not-yet-cached ancestors on an explicit stack, and its wstack/wseen containers allocated one heap
node per visited tensor (plus the rehash and the frees) on every graph re-allocation -- ~4.7k split
states and ~150k tensors per re-allocation in the reporter's 4-stream workload, where 94% of the
mallocs under ggml_gallocr_alloc_graph came from that set.  Both containers now use a reused
per-thread monotonic_buffer_resource (1 MiB, released per walk); only the outermost call walks, so the
resource is never re-entered, the walk visits the same tensors in the same order and computes the same
states, and an exhausted arena falls back to the upstream allocator.  GGML_META_SS_SCRATCH=0 restores
the heap containers (A/B only).

Second-scheduler slot for DFlash/DFlash2 drafts (issue ggml-org#208): the draft context's second scheduler
(LLAMA_DRAFT_SCHED2) was selected with `n_outputs > 0`.  That fits MTP (a no-output ingest graph and a
draft step with an output) but not a DFlash2 draft block, which has no outputs either: its lattice is
read from the nextn embeddings, not from logits (`output = !is_dflash2`).  The KV injection and the
noise-block draft step therefore shared one scheduler AND one `gf_res_prev` slot, so they overwrote
each other's graph every cycle and the draft context rebuilt and re-allocated both of them on every
verify step (measured 0 of 362 draft ubatches reused).

`sched_alt_for()` now selects the slot from the batch kind for LLM_ARCH_DFLASH -- the injection is the
batch that carries the target features (host embd rows, or the F1 device injection whose token ids are
target rows), the draft step is the token batch -- and keeps `n_outputs` for every other arch, where
the batch kind would merge MTP's ingest and step graphs instead of separating them.  `get_gf_res_prev()`
takes the same decision, so the scheduler and the graph-reuse slot cannot disagree.

Measured (gfx1201, 512 greedy tokens, `prompts/prose-rdna-boosts.txt`): draft graph reuse 0 -> 97.8 %
(dense 27B UD-Q4_K_XL 2 GPU tensor) and 97.9 % (35B-A3B Q4_K_M `-ncmoe 40`); decode +1.4 % (27B 2 GPU),
+1.8 % (27B 3 GPU), +4.0 % (35B-A3B host experts), +1.3 % (host injection, GGML_LF_DFLASH_DEV=0),
+0.5 % (27B `-sm layer`), +0.2 % (27B 1 GPU); a 2-slot unified server with two concurrent requests is
identical per slot (text, acceptance 0.66894 / 0.73801) at +1.0 / +1.9 %.  Generated text is
byte-identical in every arm, the dense 4B coherence hash is unchanged, and the adaptive-MTP four-axis
gate (27B, `-n 3000`, reasoning pinned per axis) is identical to the pre-fix build on all four axes
(t/s, acceptance and text).  `LLAMA_DRAFT_SCHED2=0` reproduces the old behaviour exactly.

Per-block build (blocks own their code): the identity-preference layer-drop ranking (r117) called
`heat_rank_vec()`, which block 12 introduces with the band-split heat prior (r114), so block 09 alone
did not compile (`use of undeclared identifier 'heat_rank_vec'`) since r117.  This block now ranks by
`t.heat`, which is byte-identical in this tree (there is no decode counter yet), and block 12 switches
this site over along with the two it already owns.  `gate-per-block-build.sh` selects block 09 again.

Verify-width band clamp (TODO ggml-org#59, ngram-mod x host experts): the expert cache serves a routed
`MUL_MAT_ID` from its arena only up to its decode/verify band (`moe_cache_max_tok_dev()`: 16 tokens on
RDNA4, 8 on RDNA3/NVIDIA).  A WIDER batch leaves the arena entirely -- `moe_cache_update_host()` returns
false above the band, so the routed experts are streamed from the pinned host master on every step.  A
speculative verify batch is `n_draft + 1` rows, and while the MTP/draft family is bounded to 15 (i.e. 16
rows) by `LLAMA_SPEC_DRAFT_N_MAX_CLAMP`, the DRAFTLESS n-gram speculators have no width bound at all:
`ngram_mod.n_max` defaults to 64 (`n_min` 48), the ngram-map family's `size_m` to 48.  On a host-expert
config the README's own `draft-mtp-adaptive,ngram-mod` recommendation therefore put every ngram step
outside the band, which is the "ngram-mod halves decode with host-resident experts" report (TODO ggml-org#59).

Measured (2x R9700 gfx1201, Flash-Next IQ4_NL + MTP head, `-sm tensor -ncmoe 36`, `-c 16384`,
`prompts/recall.txt`, `-n 2000 --temp 0 --seed 42`): sweeping `--spec-ngram-mod-n-max` gives 154.8 t/s at
12 (13-row verify), 159.2 t/s at 15 (16 rows, in band), **55.0 t/s at 16 (17 rows -- one extra row,
-65 %)**, 58.1-58.3 at 20/24, 48.1 at 32; the arena hit rate drops 0.978 -> 0.898 and the cache's counted
`reaches` collapse 1086540 -> 129660 (the wide steps never reach the arena).  The README combo measures
73.9 t/s uncapped against **168.3 t/s** at a 15-token draft.  Controls: fully device-resident (3 GPU,
`-ncmoe 0`) 144.7 (MTP n3) -> 378.7 (ngram default) vs 244.6 capped -- there the wide draft is the win;
the CPU expert path (`MOE_EXPERT_CACHE_MIB=0`) 38.5 -> 67.6 (wide) vs 52.2 capped -- upstream's shape and
the reason the reporter's config in issue ggml-org#214 was fine there.

The fix is a new `moe_cache_band` device query (appended to `ggml_backend_device_i`, zero-initialized for
backends that do not set it; CUDA answers `moe_cache_enabled() ? moe_cache_max_tok_dev(device) : 0`),
`llama_model_moe_cache_band()` (the smallest band across the model's host-expert devices), and
`common_speculative_clamp_ngram_n_max()`: `common_init_from_params` clamps an ENABLED n-gram
speculator's draft length to `band - 1` once the model (and therefore the preflight's decision) is known,
lowering `n_min` with it (ngram-mod discards a draft shorter than `n_min`, so a naked `n_max` clamp would
silently disable it), and refreshes `cparams.n_rs_batch` so the slab's narrow verify floor and the
chunked-GDN rollback bound see the capped depth (the uncapped default also cost ~5 GiB of arena:
32938 -> 27814 MiB).  `LLAMA_SPEC_NGRAM_MOD_BAND_CLAMP=0` restores the uncapped draft.  A model with no
active arena reports band 0 and is never clamped; a `draft.n_max` above the band is warned about, not
clamped (the 15 bound is a correctness one and matches RDNA4's band).

Gates: prefilled-text purity with `ROCBLAS_USE_HIPBLASLT=0` (per the delivery's fresh-process rule) --
`plain` / `draft-mtp n3` / `ngram-mod` hand-capped / `ngram-mod` auto-clamped all hash identically
(1793 chars, sha 9d914f47aebb) on the host-expert cell, the same hashes the pre-amend build produced;
`LLAMA_SPEC_NGRAM_MOD_BAND_CLAMP=0` reproduces 74.1 t/s exactly; the device-resident and CPU-expert
controls are unchanged (380.2 and 68.1 t/s, no clamp line).  The clamp never touches a non-ngram config
(the MTP-only arms log no clamp).  Record: `wip/ngram-mod-host-experts/EVIDENCE-2026-10-24.md`.

Windows HIP build (issue ggml-org#217): the three `std::min`/`std::max` calls on int64_t in
moe-expert-cache.cu (the sizing slack guard, the auto-arena floor and the heat-coverage bound) are
replaced with two local ternary helpers.  With HIP on Windows (clang + the MSVC STL) clang's
force-included `cuda_wrappers/algorithm` and the MSVC STL `<utility>` each define an inline
`std::min<long long>` (int64_t is `__int64` there, and the `enable_if` that makes clang's version win
overload resolution is not part of the mangled name), so a translation unit that instantiates both
fails to codegen with "definition with same mangled name".  Behaviour is unchanged: greedy text is
byte-identical on the dense 4B (`-sm tensor`, 3 GPU) and the host-expert arm (35B-A3B `-ncmoe 40`),
prefill-logit mean KLD 0.000000 / same-top-p 100.000 %, MTP acceptance 0.73881.

Amended r125 (issue ggml-org#216): the draft-reserve log line is now gated on the model actually having
host-resident experts (llama_model_moe_host_expert_dev_count() > 0).
llama_model_moe_cache_preflight() is a no-op without one, so a dense model used to print
"keeping the flat 3584 MiB draft reserve" for a reserve nothing consumed -- and in issue ggml-org#216 that
line was read as evidence that the slab or the expert-cache arena was involved in a dense model's
VRAM failure.  No behaviour change: the reserve, the derived value and the
MOE_EXPERT_CACHE_AUX_RESERVE_MIB override are identical wherever they are actually used.

Amended (r132): the split-state cache-hit path returns split_state_entry::get() directly instead of copying the
state out of a named local, so a compiler that does not elide NRVO out of this multi-return function builds it
once in the caller's object.  Same values, same assertions.  Contributed in PR ggml-org#213 (@briansp2020), where the
copy was ~half of this function's self time; on this tree it is measured neutral -- clang 24 and clang 23 at -O3
already build the entry directly in the return slot (identical function size and codegen; the function's sampled
self time is 1.6-1.9 % before and 1.6 % after, within run-to-run noise) and 12/12 same-seed configs are
byte-identical.  Taken as an explicit-intent change, not as a measured speedup.

Co-authored-by: Brian <[email protected]>

Meta: two halves of issue ggml-org#232 (the `ggml_new_object: not enough space in the context's memory
pool (needed 2261360, available 2260992)` abort, reported by @MrDrMcCoy).

(1) A simple-tensor container grows instead of aborting.  One generation (everything registered
between two graph rebuilds) can register more simple tensors than one context holds: a state
restore creates one view per KV cache chunk per layer (`llama_io_read_device`) and every graph
shape contributes its own.  A full context is now followed by another one, and a rebuild resets
and releases every context in the list, so the 128-views-per-static-tensor budget is a
first-context size rather than a cliff.  `GGML_META_COMPUTE_HEADROOM` overrides that size
(diagnostic/testing only: a smaller value only makes the container grow sooner and never changes
an output).  `ggml_new_object`'s overflow warning now also reports the context, its `mem_size`,
its object count and the bytes used, so a future report of this class is diagnosable.

(2) Views created *between* graph evals go to a scratch container (`ggml_backend_meta_set_scratch_views`
/ `ggml_backend_meta_reset_scratch_views`, caller-owned lifetime).  This is the reported trigger:
`llama_kv_cache::park_move` moves a run in chunks no larger than the gap to its destination and
creates 2 views per (layer, K/V) per chunk, so a nearly-full unified cache (two ~258k-token
prompts in 524288 cells) parks in dozens of tiny chunks -- hundreds of thousands of views in one
move -- and they all landed in the per-generation container, which nothing reclaims between
graphs.  The reporter's diagnosis and patch; the copies are synchronous (a meta buffer has no
`.cpy_tensor`, so `ggml_backend_tensor_copy` stages through the host), so no scratch view outlives
its reset.

Validation (3x R9700 gfx1201, ROCm 10.1.0, Flash-Next GSQ-RCO IQ3_XXS, `-sm tensor`).  The
trigger reproduces exactly at the default headroom (2 slots, `-c 32768`, two ~16.3k-token prompts,
so the park gap is ~100 cells): the r149 build aborts with `needed 2261360, available 2260992` in
`llama_kv_cache::seq_park` -> `llama_kv_cache::park_move`; with (1) alone the run completes and the
attention-KV container grows 6144 -> 12288 (the indexer's 3072 -> 6144); with (1)+(2) it completes
with **zero** growth events, i.e. parking no longer touches the per-generation container at all.
Byte-identical output across r149 / (1) / (1)+(2) on that flow; `llama-perplexity` wikitext-2
`PPL = 2.0901 +/- 0.05592` on all three builds; `GGML_META_COMPUTE_HEADROOM=1` aborts the r149
build at `sched_reserve` and completes here (105 growth events) with identical text; the 2-slot
524288-cell flow (two ~240k-token prompts, parking + checkpoint restores) is text-identical and
clean; `gate-park-idle-slots.sh` PASS (6 park / 2 unpark moves, park == lazyoff on all four
requests).

Also hardened while reading the same file: `get_node_aux()` now asserts against its pool
(`nodes_aux`, `3 * n_reduce_steps * max_subgraphs` tensors per device).  Its ALL_GATHER sibling already
asserted; an over-budget graph would have written past the pool instead of reporting (not reachable on any
recorded config, no behaviour change).

Amended r153 (issue ggml-org#234): the aligned verify-batch depth is bounded by this device's MoE expert-cache verify
band.  Block 02 aligns the drafts of the sequences that verify in the same step so the target batch stays one
ubatch, but on a host-expert config a batch wider than the band leaves the arena and streams the routed experts
from the pinned host master on every step (see common_speculative_clamp_ngram_n_max), and alignment turns a wide
batch from an occasional step into the steady state.  The aligned depth is therefore bounded by
`band / n_drafting - 1` rows per sequence, because the whole ubatch has to fit: a two-slot verify on RDNA4
(band 16) aligns to at most 7 each, not 15 each.  A sequence already deeper than that keeps its own cap -- the
band bound may only WIDEN a shallow draft, never shorten a deep one, which is what keeps every single-sequence
run bit-identical -- so it needs no new knob; LLAMA_SPEC_ALIGN=0 (block 02) disables the alignment with it.
The value is read once, after the target context exists, from llama_model_moe_cache_band(), so a config where
the slab declined (no arena) is unbounded.  Measured with the bound in place on 35B-A3B UD-Q4_K_M -ncmoe 40,
2 GPU, --parallel 2 --kv-unified: the diverging pair goes 116.2 -> 149.0 t/s (+28 %) and the split decode steps
58 -> 0, with the single-slot requests byte-identical on/off.  Issue ggml-org#234.

Amendment (TODO ggml-org#129): a routed host-weight op whose routing ids are computed by its own split.

`ggml_backend_sched_copy_input` prunes a host expert table's upload to the routed experts, and the
ids readback happens when the split's INPUTS are copied -- before that split computes.  The generalised
consumer search (this block) looks for ANY `MUL_MAT_ID` consumer of the input inside the split, and the
split pass only starts a new split for a host weight once the split already has an input to reuse
(`split->n_inputs > 0`).  With `-nkvo` the attention runs on the host, so the GPU split begins at its
output with no input yet: the split then swallows the router chain and the routed op, and the readback
returns the previous split's leftover memory -- `GGML_ASSERT(id >= 0 && id < n_expert)` in the readback
loop, or, when a stale word lands in `[0, n_expert)`, a silent wrong-expert selection.

Two parts:
 * `ggml_backend_sched_copy_input`: when the ids root (`view_src` chain of `node->src[2]`) is a node of
   the split being copied, stand every routing-dependent shortcut down (the pruned upload, the device
   gather and the expert cache's update) and take the general input path's whole-table copy -- the same
   fallback the existing two-consumer case uses, and what stock upstream does for this shape (its prune
   callback only fires when the routed op is the split's first node).
 * `ggml_backend_sched_split_graph`: start the split AT such a routed op, after the router chain, which
   is the shape every other config already has, so the pruning and the expert cache keep working
   (`next_moe_layer` keeps the routed ops of one layer in the split that starts here).

Measured on 1 x R9700: a 24-layer 128-expert MoE at `-ncmoe 24 -nkvo` aborts before this, runs at
24.6 t/s with the stand-down alone (whole-table upload per op) and 82.7 t/s with both parts (KV on GPU:
176, flat pre/post).  Text byte-identical between the `-nkvo` and default arms on bailingmoe3, 35B-A3B
(also with draft-mtp), gpt-oss-20b, Flash-Next/qwen4exp and a dense 4B, and identical to the pre-fix
default arms.

Fold (r202, PR ggml-org#266, briansp2020): the decode band no longer reads the routing back to the host.  The
eager hook synchronizes the backend once per routed op to read `ids` (the scheduler's `input_backend`
sync plus the ids readback's own sync), runs the residency policy and uploads the remap.  A new iface
member `moe_cache_remap` is offered the split input FIRST (last struct member; NULL in the meta, cpu
and rpc backends, so `-sm tensor` keeps the eager path): a kernel maps the device routing through a
per-table expert -> slot map (`slots + e` = cold, read in place from the pinned master) into that
table's `remap_dev`, and writes the routing into mapped pinned memory; the residency policy consumes
that routing at the NEXT call (one call late) and re-uploads the map only after a residency change
(`slot_dirty`).  One launch serves a layer's tables (gate / up / down) when they were served the same
routing tensor on the same stream.  Every expert is read from the same bytes it was read from before --
an arena slot, or the same pinned master the cold read already used -- so the output does not change:
byte-identical greedy text (35B-A3B `-ncmoe 40` and gpt-oss-20b at 128 and 1000 tokens, including a
2048 MiB arena under eviction pressure, pinned and `--host-experts pool`), identical MTP acceptance
(0.76089 / 1387-of-1836 both arms, n=3000), prefill KLD 0.000000 / 100.000 %.  Worth **+8.4 % TG**
(60.6 -> 65.7 t/s, 1 x R9700, `-ncmoe 40`) and +2.3 % on the MTP arm, and it is inert under `-sm
tensor` (98.0 vs 98.1 t/s, identical text).  `GGML_MOE_DEVREMAP=0` restores the eager path.

Scope, by construction: a pinned master (`table_cold_ok`), one unsplit table, no identity table, no
`-sm tensor`, the decode/verify band only (`ne[2] <= band`), and `g_sized` (the eager path primes,
sizes and re-primes).  The map is rebuilt from `slot_dirty` on EVERY slot mutation (fill, eviction,
stand-down, slab eviction, shrink, migration, re-arm), which is the one invariant to keep: a stale map
reads the wrong arena slot, and the cold encoding `slots + e` additionally depends on the slot COUNT,
so a slot-count change without a rebuild would read past the master.  `devremap_free_locked` bumps
`ggml_cuda_graph_mem_freed` (the map/lag buffers are kernel arguments of a captured graph).

Also `MOE_HOST_POOL_COLD` (default on): `--host-experts pool` has a pageable master, so the in-place
cold read stands down and every decode miss was an arena fill even when the expert was already in the
pinned pool.  Such a miss is now read cold from its pool slot through the pool's device alias (cold id
`n_res + pool slot`, `moe_cache_get_cold` returns the pool base), i.e. the same bytes the fill would
have copied.  Safe because the demand path never evicts a pool resident, a retiring slot (state 2) is
excluded, and the eager path it rides synchronizes the backend before the hook; single visible device,
single slice.  Measured (pool arm, 1 x R9700): fills 21747 -> 15270 and 8445 misses served in place,
+4.9 % TG (57.5 -> 60.4 t/s), identical text.  `MOE_HOST_POOL_COLD=0` restores the fill-every-miss arm.

TODO ggml-org#269 (r221): the decode remap reaches a TENSOR SPLIT and a covering host pool.  The Meta backend
now forwards `moe_cache_remap` to each simple device with that device's simple tensors, exactly as it
already forwards `moe_cache_update`/`take_over`/`gather` -- one `check_only` pass answering for all
devices, then one committing pass, so the scheduler's all-or-nothing skip-copy decision is unchanged.
That is not a formality: the remap is per (table, device) by construction (each device holds its own
arena, slot count, map and lag buffer), and the eager path it replaces synchronizes the WHOLE meta
backend once per routed op, which is why the win grows with the device count --
1 GPU 57.6 -> 63.3 t/s (+9.9 %), 2 GPUs `-sm tensor` 64.0 -> 74.3 (+16.1 %), 3 GPUs 59.4 -> 76.3
(+28.4 %), all 35B-A3B Q8_0 `-ncmoe 40` `MOE_EXPERT_CACHE_MIB=8000`, byte-identical greedy text
(300 and 1000 tokens), and +5.0..6.0 % on `llama-batched-bench` at `-npl 1/4/8`.  Under `-sm tensor`
the remap was previously inert by construction (the iface member was NULL).

The second half is the COLD SOURCE.  A `--host-experts pool` table has a pageable master
(`host_dev == nullptr`), so it had no cold encoding at all and took the eager path even when its pool
COVERED the tensor -- which is the default `-lme auto` layout on a mapped load ("a pinned per-EXPERT
pool of the whole host expert set (a MIRROR)").  Such a table now maps a cold expert to
`slots + pool slot` (the pool slot, a host-side fact at map-build time) instead of `slots + e`; the
consumer already resolved that id (`moe_cache_get_cold`'s pool branch).  Measured on that default
config, 1 GPU: 57.6 -> 63.3 t/s (+9.9 %), and +5.3 % under `--spec-type draft-mtp` with bit-identical
acceptance (0.75655 = 693/916, mean len 3.26) and text.  A sub-complement pool (any `-lme N` below the
set) still declines every offer (0 of 3840 served, exactly as before), because there a device-side map
would have a hole it cannot express; so does a covering pool with `MOE_HOST_POOL_COLD=0`.

The freshness invariant the maintainer conditioned ggml-org#269 on is now structural rather than incidental:
`dr_pool_ok` is latched once, at sizing (a graph capture needs a per-shape-constant take-over), and a
covering pool's expert -> slot map is WRITE-ONCE after sizing -- the demand path never evicts a
resident, and the one covering-pool re-rank is a no-op (`pool_rerank_from_heat_locked` returns before
any bookkeeping).  `devremap_prep_locked` re-counts the LIVE slots on every map rebuild and declines
rather than emit an id it cannot resolve.

Gates: prefill-logit KLD 0.000000 / same-top-p 100.000 % (data movement only), MTP acceptance
bit-identical, `test-backend-ops -o MUL_MAT_ID` 931/931, `scripts/gate-host-pool.sh` 18/18,
`check-gpu-faults.sh` clean.  Kill switch unchanged (`GGML_MOE_DEVREMAP=0`).
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`.

TODO ggml-org#269 (r221): a host pool whose capacity COVERS the tensor must never retire a slot for an expert it
just copied into the arena -- it is a MIRROR, and retiring there un-loads an expert that is still
resident (the comment above already says so for the surplus case).  One condition now covers both, and
it is what makes the decode remap's pool-slot cold map write-once after sizing.
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Nov 6, 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`.

TODO ggml-org#269 (r221): a host pool whose capacity COVERS the tensor must never retire a slot for an expert it
just copied into the arena -- it is a MIRROR, and retiring there un-loads an expert that is still
resident (the comment above already says so for the surplus case).  One condition now covers both, and
it is what makes the decode remap's pool-slot cold map write-once after sizing.
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Nov 6, 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,