[PR #2318] [CLOSED] KV cache: FP16 sliding window + attention sinks, and an optional 2-bit K / 4-bit V cache scheme (--kv q2k) [EXPERIMENTAL] #3978

Closed
opened 2026-11-07 15:32:11 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/Niko1221/Strata/pull/2318
Author: @bsorensen110
Created: 10/13/2026
Status: ❌ Closed

Base: main ← Head: feat/kv-q2k-window


📝 Commits (10+)

  • 1aee5c9 kv_window: FP16 sliding window + attention sinks over the quantized KV cache
  • 50bb59d kv_q2: 2-bit per-channel KV cache format, parity gate, and the measurement tooling
  • a8d8469 kv_q2k: K 2-bit per-channel + V 4-bit - the mixed-width point the real-cache gate found
  • 20ae0cb kv_q2: whole 32-cell groups wherever a q2/q2k pool is sized or moved
  • cd8e5fa kv_q2: a fresh partial group's scale is the RMS of the cells it has, not of 32
  • 2408c22 kv_q2_parity: pin the review fixes - fresh partial-group scale, whole-group staging
  • c0d8549 generate: repair the --dump-logits header on every path, not only the native one
  • 63726fe tools: review fixes - truncated dumps, zero-vocab headers, the no-e check, failure rows, pair scoring
  • 38ea09d kv_pr_report: ask each tail code in its own request, inside the window
  • 1f0b858 docs: footprint arithmetic, the tail-probe correction, the stale dump-logits gap, the AsymKV citation

📊 Changes

44 files changed (+8031 additions, -166 deletions)

View changed files

📝 CMakeLists.txt (+16 -0)
➕ ab-kv-window-probe.sh (+60 -0)
➕ ab-kv-window-stream.sh (+60 -0)
➕ ab-kv-window.sh (+60 -0)
➕ bench/results/2026-10-11-kv-window/README.md (+106 -0)
➕ bench/results/2026-10-12-kv-precision/README.md (+100 -0)
➕ docs/kv-q2.md (+540 -0)
➕ docs/kv-window.md (+100 -0)
➕ docs/research-kv-cache-compression.md (+101 -0)
➕ docs/research-kv-cache-proposals-3-4-5.md (+433 -0)
📝 include/strata/core/layer.hpp (+60 -1)
➕ include/strata/kernels/kv_q2.hpp (+212 -0)
📝 include/strata/kernels/kv_stream.hpp (+50 -6)
➕ include/strata/kernels/kv_window.hpp (+108 -0)
📝 include/strata/kernels/qsa_decode_attn.hpp (+12 -0)
📝 include/strata/prefill/prefill.hpp (+41 -1)
📝 include/strata/program/logits_selection.hpp (+20 -0)
➕ kv-ab-report.sh (+18 -0)
➕ logits-kv-window.sh (+42 -0)
➕ metal/src/engine/stubs_kv_q2.cpp (+77 -0)

...and 24 more files

📄 Description

KV cache: FP16 sliding window + attention sinks, and an optional 2-bit K / 4-bit V cache scheme (--kv q2k) [EXPERIMENTAL]

Status: experimental. Opt-in only (--kv q2k, --kv-window N, --kv-k-gain B); default behavior is unchanged when the flags are off. It needs more testing before it can be considered production-ready: the behavioral and long-context runs below are single-model, single-document measurements, and the window-1024 anomaly is unexplained.

Summary

Two composable KV-cache features behind opt-in flags, plus a correction that makes them work together:

  1. --kv-window N (--kv-sink S) — an FP16 overlay over the first S cells (attention sinks) and the most recent N cells of the quantized KV bulk. Those cells read exact; the rest stays quantized. Costs 304 KiB per layer at N=128, S=8 including 16 slack slots (3.56 MiB for 12 layers).
  2. --kv q2k — a cache format storing K at 2 bits with per-channel scales and V at 4 bits per token (q4_0): 448 B/cell vs q4_0's 576 B (−22%), 4.6× smaller than FP16 (2048 B).
  3. --kv-k-gain B (q2/q2k) — a K reconstruction gain: the stored K scale is B × the rule's, the codes are unchanged. It undoes the 2-bit codebook's score shrink, which is what made the window hurt q2k. Zero extra bytes.

Recommended with q2k: --kv-window 256 --kv-sink 8 --kv-k-gain 1.10 — decode-path KL −36.8% vs plain q2k (8 of 9 texts) for +6.6 MiB.

Correction to the previous revision (run-to-run variance). The last revision said greedy decode is not run-to-run reproducible "under QSA top-k tie-breaks and atomic partial-group KV writes" and reported decode-path numbers as 5-run means. That diagnosis was wrong, and the cause was our measurement setup: we did not have the prefill CPU share turned off. For prompt chunks under 1024 tokens the prefill hands part of the MoE expert work to the CPU, and that split changes from run to run — a 730-token prompt's logits differed by up to 6.8 between two identical runs. With STRATA_PREFILL_CPU_SHARE=0 two runs are bit-identical (129 teacher-forced decode rows, max |diff| 0; a second forced FP16 run scores KL 0.0000 against the first on all nine texts below). Every number in this revision was measured that way, and the 512-token logits table was re-measured (it moved by up to 2.5 points of top-1). The earlier decode-path comparison also used a greedy reference, which speculatively drafts multi-token windows and so does not produce rows comparable to the arms'; the decode numbers below use a teacher-forced FP16 reference instead.

Every directional claim below carries the number that pins it; the gate (kv_q2_parity) reproduces the attention-error tables from a real KV dump.

Why this shape

The bit-allocation rule came from the real cache, not the synthetic one

Measured with the gate's attention-output probe (relative RMS of attention output vs an FP16 cache) on a real stored KV cache dumped from a live serve (--dump-kv; 864 cells, 2 KV heads × 256 dims, rotated as stored), layer 3 unless stated:

arm B/cell/head attention error
q4_0 (reference) 288 0.888%
K 2-bit per-channel + V 4-bit (q2k) 224 1.911%
K 4-bit + V 2-bit per-channel 224 3.171%
K 2-bit + V 2-bit per-channel (symmetric q2) 160 3.508%
K per-channel + V per-token, both 2-bit (KIVI's placement) 160 5.188%

At equal bytes (224 B), the bits belong on V: K2c+V4 beats K4+V2c on every real layer measured (table below). On the synthetic gate cache the ranking is the reverse (K looks more sensitive) — synthetic data has no channel structure, which is why no ranking here is taken from it.

The mechanism: V's quantization error enters the output directly through softmax(qKᵀ)·V, while much of K's error is common-mode across cells and cancels in the softmax normalization (docs/kv-q2.md). Both published intuitions survive, scoped:

  • K's outliers are channel-aligned (KIVI's premise) — true on real layers (K channel RMS max/median 5.8× on L3 up to 74.9× on L47), and honored by the per-channel K scale, not by more bits.
  • V is the tensor the output feels — so V gets 4 bits while K takes 2.

Why per-channel K and per-token V

Per-channel K scales (block_q2c_0: one fp16 scale per dimension per 32-cell group, a 4-level Lloyd-Max codebook) absorb K's channel outliers. V reuses the existing q4_0 path (per-token blocks), so the format adds no new V quantizer. KIVI's 2-bit per-token V loses on this cache: the Hadamard rotation leaves V's channel structure in place (V channel RMS max/median 7.9–14.5×), so 2-bit V would want per-channel scales too — at 4 bits per token, V carries q4_0's own error.

Why the FP16 window — and why q2k needs the gain to use it

The window is a separate, format-agnostic device. It only acts at decode: prompt-mode (prefill) logits never read the overlay, which is why the previous revision measured "no logit precision" — that was a blind spot of the measurement, not a property of the window.

  • At decode it helps q4_0: −19.6% KL (7 of 9 texts).
  • With q2k alone it hurts: +10.3% (4 of 9 better). The 4-level Lloyd-Max K codebook is MSE-optimal, so its reconstruction is shrunk: on real queries q2k's attention scores come out at 0.92–0.97× the exact ones (q4_0: 0.997–0.998). Next to exact window cells that is a bias — the exact cells out-score the shrunk bulk, and the softmax over-weights the window by +1.7..+5.9% of its mass on 11 of 12 layers.
  • --kv-k-gain stores the K scale B × larger while choosing the codes against the un-gained scale, so no value moves to another level and only the reconstruction grows. With B = 1.10 the window turns into a gain: −29.3% at 128 cells, −36.8% at 256 (vs plain q2k).
  • Behaviorally the window recovers symmetric q2's short-answer loss (q2 2/3 → q2 + window 3/3); q2k matches the q4_0 reference on the recall probe without it (3/3).

Measurements

Gate (device kernels vs host reference)

  • kv_q2_parity: synthetic cache 40/40 checks (incl. the K-gain pin: stored scale = B × the rule, bit for bit, codes chosen against the un-gained scale); real cache layers 3/11/23/47 36/36 each. The q2k device arm (real append + gather kernels) lands on the host row: L3 1.910% device vs 1.911% host.
  • kv_window_parity: 10/10 — sink and window cells read bit-exactly equal to an FP16 pool; cells outside read the bulk pool bit-for-bit; kv_window_restore reproduces the bulk dequantization.
  • kv_q4_parity, kv_q8_parity, kv_stream_parity, kv_hybrid_parity: pass (existing formats untouched).

Attention error by layer (real cache)

layer K channel spread q4_0 q2k (K2c+V4) K4+V2c q2 (K2c+V2c)
L3 5.8× 0.888% 1.911% 3.171% 3.508%
L11 5.9× 0.740% 2.002% 2.589% 3.471%
L23 14.2× 0.941% 2.211% 2.768% 3.655%
L47 74.9× 1.040% 1.645% 2.663% 2.948%

The outlier layer (L47) is where q2k comes closest to q4_0.

Attention error under the engine's append patterns (real cache)

The row above appends every cell in one call — whole 32-cell groups — so it never runs the partial-group scale rule. The engine does, every request: speculative verify appends 2–5-cell windows that cross group boundaries, decode appends into the group the prompt ended in, and after a reused conversation prefix the 2048-cell prefill chunks fall mid-group. kv_q2_parity now replays those patterns on the same K/V and readers (attention output vs FP16). Three scale rules for a group first written by a partial batch: old = the pre-review kernel (sum / 32), /n = RMS of the n cells, shrink = shipped (full-group RMS, the previous group's mean square standing in for the cells not yet written):

layer q4_0 q2k one-shot spec verify (3-cell windows) old / /n / shrink chunked prefill (100-cell chunks, stress) old / /n / shrink prompt + decode
L3 0.888% 1.910% 1.978% / 1.912% / 1.892% 3.631% / 2.076% / 2.186% 1.910%
L11 0.740% 2.002% 2.030% / 2.011% / 2.012% 3.617% / 2.727% / 2.626% 2.002%
L23 0.941% 2.211% 2.895% / 2.667% / 2.245% 3.767% / 2.509% / 2.161% 2.211%
L47 1.040% 1.648% 1.457% / 1.799% / 1.720% 1.438% / 1.346% / 1.803% 1.648%
  • Speculative verify (what every decode does at each group boundary): the excess over one-shot, summed over the four layers, is +8.0% with /n and +1.3% with shrink.
  • Chunked prefill is a stress case (real chunks are 2048 cells, aligned from position 0): shrink is mixed by layer there (1.4% worse summed than /n) and 30% better than the pre-review kernel.
  • Prompt + decode lands exactly on the one-shot row (pinned). On the extreme-outlier layer 47 an undersized scale acts as clipping, which is why the pre-review kernel measures better there.

Logits (512-token prompts, prompt mode, vs FP16: top-1 agreement / mean KL) — re-measured with the CPU share off

text q4_0 q2 q2k
code 90.4% / 0.060 74.6% / 0.329 77.1% / 0.226
document 91.6% / 0.030 81.2% / 0.203 83.8% / 0.133
chat 92.4% / 0.027 81.2% / 0.177 83.4% / 0.144

q2k's KL is 3.8–5.3× q4_0's at the prompt level: it is a cheaper format, not a lossless one. (The previous revision's table, measured with the CPU share on, read 2.5–5×.)

Decode path (teacher-forced decode, 9 texts, vs FP16)

Every arm is fed the same 128-token continuation, one token per window, and each row is compared with a forced FP16 run's row at the same position. Nine texts: three built-in prompts (chat, document, code agent) and six repo files up to 6144 tokens. A second FP16 run scores KL 0.0000 against the reference on all nine. Change = geometric mean over the texts vs plain q2k, with the texts that improved.

arm mean KL top-1 vs q2k
q4_0 0.0198 96.6% −89.9% (9/9)
q4_0 + window 128 0.0174 96.9% −91.9% (9/9)
q2k 0.1825 88.5%
q2k + window 128 0.2060 87.3% +10.3% (4/9)
q2k + window 128 + gain 1.10 0.1338 89.8% −29.3% (7/9)
q2k + window 256 + gain 1.10 0.1203 90.3% −36.8% (8/9)

Gain sweep at window 128 (same texts, development build): 1.03 −9%, 1.05 −15%, 1.08 −26%, 1.10 −30%, 1.13 −29%; the gain alone, with no exact cells, −1%. Even the best q2k setting keeps ~6× q4_0's decode KL.

These rows were measured on this PR's build with a temporary copy of our teacher-forced decode tooling (--force-tokens + a per-window logits dump; not part of this PR). The PR build's prompt logits are byte-identical to our development build's under the same flags (--kv q2k, and --kv q2k --kv-window 256 --kv-sink 8 --kv-k-gain 1.10). The two builds sit on different upstream bases, and their decode rows differ slightly for every quantized format — plain q4_0 included — but never for FP16, so the development build's numbers are not quoted as this PR's.

Behavioral A/B (~5K-token buried-fact probe, tools/kv_recall_report.py)

Eight vault codes buried in a document: mid = the body; late = the last few paragraphs (~180–350 tokens before generation: outside a 128-cell window, inside a 512/1024 one). Scored by the instructed (vault, code) pair. Release q4_0 is the shipped binary; every other arm is this branch.

arm mid late short answers decode
release q4_0 (reference) 4/4 4/4 3/3 158.3 t/s
q4_0 (this branch) 4/4 4/4 3/3 159.0 t/s
q2 (symmetric) 4/4 4/4 2/3 134.6 t/s
q2k (no window) 4/4 4/4 3/3 137.5 t/s

q2k matches the q4_0 reference on every measure at 22% less KV memory and ~13% lower decode speed; symmetric q2 is the arm that loses a short answer. An earlier 5-arm run (substring-scored) agreed, with 0/3 repetition loops for release q4_0 and q2k.

Long-context recall at depth (smoke test)

~200K-token operations log (199,337 prompt tokens) served with --kv q2k --max-context 262144; three needles at 25% / 50% / 90% depth — all three recalled exactly (WALRUS-CANARY-2247, QUARTZ-DELTA-8813, TUNDRA-FALCON-6631). Cold prefill of the full prompt: 2574 tok/s. The verification pass rode the serve's conversation cache, which restores the same q2k-quantized state. Re-run on the final kernel (after the partial-group scale changes, fresh service, nothing cached): cold prefill of all 199,337 tokens at 2529 tok/s, 3/3 recalled. Re-run with the recommended --kv q2k --kv-window 256 --kv-sink 8 --kv-k-gain 1.10 (fresh service, nothing cached): 199,337 tokens, 3/3 recalled, 78.6 s wall including generation (~2537 tok/s). One model, one document.

A small multi-turn agent task (find and fix two planted bugs across two files, iterate pytest to green) also completed correctly against the served q2k/262144 endpoint.

Window sizing (symmetric q2 bulk + window)

arm mid late short answers decode
q2 + window 128 4/4 4/4 3/3 127.7 t/s
q2 + window 512 4/4 4/4 3/3 136.1 t/s
q2 + window 1024 3/4 0/4 3/3 129.0 t/s

128 and 512 are behaviorally identical (512 decodes faster: the FP16 overlay is a cheaper read than the q2 bulk). 1024 regresses — the late facts sit inside a 1024-cell window, so exact reads should help, not collapse; this points at a defect at that size, not a trade-off. Unexplained; do not use 1024.

Memory (262144 ctx, 12 QSA layers, 2 KV heads × 256 dims; the gain adds nothing)

format B/cell KV total
FP16 2048 6.00 GiB
q4_0 576 1.69 GiB
q2k 448 1.31 GiB
+ window 128 / sinks 8 — + 3.56 MiB
+ window 256 / sinks 8 — + 6.56 MiB

Reference papers

  • KIVI (arXiv 2402.02750) — K per-channel, V per-token, asymmetric 2-bit, 128 recent tokens in FP16. The K placement transfers (per-channel K wins on real layers); the V placement does not on this rotated cache (K2c+V2t 5.188% vs symmetric per-channel 3.508% at the same 160 B).
  • SKVQ (arXiv 2405.06219) — channel reordering, clipped dynamic quantization, an FP16 sliding window; K 2-bit / V 1.5-bit. Reordering is a no-op for per-channel-scaled K (a relabeling). During development (tooling not included in this PR) it helped per-token V on real layers, but SKVQ's byte budget still lost to plain per-channel 2-bit on every real layer. Clipping did not help (L3, in this PR's gate: clipped 4.731% vs unclipped 4.627%).
  • KVSink (arXiv 2508.04257) — attention-sink preservation under KV quantization; the reason the overlay keeps the first cells exact.
  • QuaRot (arXiv 2404.00456) — the Hadamard rotation the KV formats here (q4_0, q2, q2k) apply before quantizing.
  • KVQuant (arXiv 2401.18079) — per-channel (pre-RoPE) K and non-uniform codebooks; background for the per-channel K scale and the Lloyd-Max codebook.
  • "More for Keys, Less for Values" (arXiv 2502.15075) — argues K deserves more bits. At equal bytes on this rotated cache the measurement went the other way (above).
  • AsymKV (arXiv 2410.13212) — the 2-bit-K / 1-bit-V split; 1-bit V measured 9.7% (per-channel) to 14.4% (per-token) attention error on L3 here.

Review fixes (Copilot review of this PR)

All 15 findings were reproduced and fixed; the engine fixes are pinned by new gate checks, each shown to FAIL against the pre-fix code:

  • q2/q2k pools are sized and moved in whole 32-cell groups (high): fully resident pools, elastic VMM pools, the staging copy, the reverse DMA, and conversation snapshots (image size and reusable prefix). A page is not a byte range in the group-major layout.
  • Fresh partial-group scale: the RMS of the cells present (/n), not /32 — then, measured under the engine's append patterns (table above), shrunk toward the previous group's scale in the batch path too: s = sqrt((ss + (32 − n)·prev²)/32). prev is race-free: a previous group completed in the same launch is recomputed in-thread with its block's exact sum order; otherwise its stored scale is read. Pinned bit-exact (two-call and one-call appends must store the same scale).
  • --dump-logits header repair on every path, not only the native pack (CUDA and SYCL).
  • Tools: truncated KV dumps and zero-vocab logit headers fail cleanly instead of crashing; the no-e validator checks the letter anywhere; the engine-failure row prints; recall is scored by the (vault, code) pair (codes repeat between groups). Re-scoring the saved outputs left every arm above unchanged except q2 + window 1024 (late 1/4 → 0/4).
  • kv_pr_report.py: each tail code is now asked in its own request, inside the window. The 2026-10-11 README carries a correction: its earlier "tail" codes sat outside the window.
  • Docs: the overlay footprint (304 KiB/layer, 3.56 MiB total) and the q4_0 baseline (1.69 GiB at 262144) were ~2× off; a stale "dump-logits writes 0 bytes" note was removed.
  • Also fixed while re-measuring: two inverted gate labels (the K-vs-V check printed "K is the sensitive side" while proving V is), and the AsymKV citation (2410.13212, not 2411.17034).
  • No machine-specific paths: the harnesses and A/B scripts resolve everything from the repo's layout (tools/kv_bench_env.py: repo root, Strata-data next to it, strata-<model>.json, engines under engine/ and build/) with an environment override for each; the READMEs carry a generic CUDA 13.0 build recipe instead of local scripts.

Known limits

  • 2-bit K is the quality floor: q2k's prompt-level KL is 3.8–5.3× q4_0's, and even window 256 + gain 1.10 keeps ~6× q4_0's decode KL.
  • Reproducible measurements need STRATA_PREFILL_CPU_SHARE=0 (prompt chunks under 1024 tokens otherwise split MoE experts with the CPU, and the split varies run to run). Engine default unchanged.
  • The gain is calibrated on one model (uniform 1.10, from a 1.03–1.13 sweep on nine texts).
  • Window 1024 regresses recall (above); unexplained.
  • Behavioral and long-context results are single-model, single-document.

Commits

  1. kv_window — FP16 sliding window + attention sinks over the quantized KV cache
  2. kv_q2 — 2-bit per-channel KV format, parity gate, measurement tooling
  3. kv_q2k — K 2-bit per-channel + V 4-bit mixed-width format
  4. kv_q2 — whole 32-cell groups wherever a q2/q2k pool is sized or moved
  5. kv_q2 — a fresh partial group's scale is the RMS of the cells it has
  6. kv_q2_parity — pins for the review fixes, and the inverted K-vs-V labels
  7. generate — repair the --dump-logits header on every path
  8. tools — crash fixes and (vault, code) pair scoring
  9. kv_pr_report — tail probes inside the window
  10. docs — footprint arithmetic, the tail-probe correction, the stale dump-logits gap, the AsymKV citation
  11. tools + scripts — no machine-specific paths: repo-relative defaults, env overrides
  12. docs — a generic CUDA 13.0 build recipe instead of local paths and scripts
  13. kv_q2_parity — q2k under the engine's append patterns (spec verify, chunked prefill, prompt + decode)
  14. kv_q2 — a fresh partial group's scale shrinks toward the previous group's, in the batch path too
  15. kv_q2 — K reconstruction gain (--kv-k-gain): undo the 2-bit score shrink, codes unchanged, zero bytes

🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/Niko1221/Strata/pull/2318 **Author:** [@bsorensen110](https://github.com/bsorensen110) **Created:** 10/13/2026 **Status:** ❌ Closed **Base:** `main` ← **Head:** `feat/kv-q2k-window` --- ### 📝 Commits (10+) - [`1aee5c9`](https://github.com/Niko1221/Strata/commit/1aee5c90ffa6f0ddfb40c22db51ea3aacc1f66e8) kv_window: FP16 sliding window + attention sinks over the quantized KV cache - [`50bb59d`](https://github.com/Niko1221/Strata/commit/50bb59dd58f66f852bceecaf8f55d078cee397d4) kv_q2: 2-bit per-channel KV cache format, parity gate, and the measurement tooling - [`a8d8469`](https://github.com/Niko1221/Strata/commit/a8d8469303a515c64e1a2996ef041405af6a9fcc) kv_q2k: K 2-bit per-channel + V 4-bit - the mixed-width point the real-cache gate found - [`20ae0cb`](https://github.com/Niko1221/Strata/commit/20ae0cbaec820193aaa0815aab09577a1b69ea98) kv_q2: whole 32-cell groups wherever a q2/q2k pool is sized or moved - [`cd8e5fa`](https://github.com/Niko1221/Strata/commit/cd8e5fa475cc273263237fd51c1b77377182a7fa) kv_q2: a fresh partial group's scale is the RMS of the cells it has, not of 32 - [`2408c22`](https://github.com/Niko1221/Strata/commit/2408c22e67ac4753b2a49e7d7cd7d2bf0620bec2) kv_q2_parity: pin the review fixes - fresh partial-group scale, whole-group staging - [`c0d8549`](https://github.com/Niko1221/Strata/commit/c0d854918b9ec903176775994f7854dd76199cf6) generate: repair the --dump-logits header on every path, not only the native one - [`63726fe`](https://github.com/Niko1221/Strata/commit/63726feed4a92faf43cf2079ce85f0a84f3c5319) tools: review fixes - truncated dumps, zero-vocab headers, the no-e check, failure rows, pair scoring - [`38ea09d`](https://github.com/Niko1221/Strata/commit/38ea09d00a305cc45fd9d9d0838a2704b2384039) kv_pr_report: ask each tail code in its own request, inside the window - [`1f0b858`](https://github.com/Niko1221/Strata/commit/1f0b858faedc563a54e70c89a7b4d13f10577e70) docs: footprint arithmetic, the tail-probe correction, the stale dump-logits gap, the AsymKV citation ### 📊 Changes **44 files changed** (+8031 additions, -166 deletions) <details> <summary>View changed files</summary> 📝 `CMakeLists.txt` (+16 -0) ➕ `ab-kv-window-probe.sh` (+60 -0) ➕ `ab-kv-window-stream.sh` (+60 -0) ➕ `ab-kv-window.sh` (+60 -0) ➕ `bench/results/2026-10-11-kv-window/README.md` (+106 -0) ➕ `bench/results/2026-10-12-kv-precision/README.md` (+100 -0) ➕ `docs/kv-q2.md` (+540 -0) ➕ `docs/kv-window.md` (+100 -0) ➕ `docs/research-kv-cache-compression.md` (+101 -0) ➕ `docs/research-kv-cache-proposals-3-4-5.md` (+433 -0) 📝 `include/strata/core/layer.hpp` (+60 -1) ➕ `include/strata/kernels/kv_q2.hpp` (+212 -0) 📝 `include/strata/kernels/kv_stream.hpp` (+50 -6) ➕ `include/strata/kernels/kv_window.hpp` (+108 -0) 📝 `include/strata/kernels/qsa_decode_attn.hpp` (+12 -0) 📝 `include/strata/prefill/prefill.hpp` (+41 -1) 📝 `include/strata/program/logits_selection.hpp` (+20 -0) ➕ `kv-ab-report.sh` (+18 -0) ➕ `logits-kv-window.sh` (+42 -0) ➕ `metal/src/engine/stubs_kv_q2.cpp` (+77 -0) _...and 24 more files_ </details> ### 📄 Description # KV cache: FP16 sliding window + attention sinks, and an optional 2-bit K / 4-bit V cache scheme (`--kv q2k`) [EXPERIMENTAL] > **Status: experimental.** Opt-in only (`--kv q2k`, `--kv-window N`, `--kv-k-gain B`); default behavior is unchanged when the flags are off. It needs more testing before it can be considered production-ready: the behavioral and long-context runs below are single-model, single-document measurements, and the window-1024 anomaly is unexplained. ## Summary Two composable KV-cache features behind opt-in flags, plus a correction that makes them work together: 1. **`--kv-window N` (`--kv-sink S`)** — an FP16 overlay over the first `S` cells (attention sinks) and the most recent `N` cells of the quantized KV bulk. Those cells read exact; the rest stays quantized. Costs 304 KiB per layer at N=128, S=8 including 16 slack slots (3.56 MiB for 12 layers). 2. **`--kv q2k`** — a cache format storing **K at 2 bits with per-channel scales and V at 4 bits per token (q4_0)**: 448 B/cell vs q4_0's 576 B (−22%), 4.6× smaller than FP16 (2048 B). 3. **`--kv-k-gain B`** (q2/q2k) — a K reconstruction gain: the stored K scale is `B` × the rule's, the codes are unchanged. It undoes the 2-bit codebook's score shrink, which is what made the window *hurt* q2k. Zero extra bytes. **Recommended with q2k: `--kv-window 256 --kv-sink 8 --kv-k-gain 1.10`** — decode-path KL −36.8% vs plain q2k (8 of 9 texts) for +6.6 MiB. > **Correction to the previous revision (run-to-run variance).** The last revision said greedy decode is not run-to-run reproducible "under QSA top-k tie-breaks and atomic partial-group KV writes" and reported decode-path numbers as 5-run means. That diagnosis was wrong, and the cause was our measurement setup: **we did not have the prefill CPU share turned off.** For prompt chunks under 1024 tokens the prefill hands part of the MoE expert work to the CPU, and that split changes from run to run — a 730-token prompt's logits differed by up to 6.8 between two identical runs. With `STRATA_PREFILL_CPU_SHARE=0` two runs are bit-identical (129 teacher-forced decode rows, max |diff| 0; a second forced FP16 run scores KL 0.0000 against the first on all nine texts below). Every number in this revision was measured that way, and the 512-token logits table was re-measured (it moved by up to 2.5 points of top-1). The earlier decode-path comparison also used a greedy reference, which speculatively drafts multi-token windows and so does not produce rows comparable to the arms'; the decode numbers below use a teacher-forced FP16 reference instead. Every directional claim below carries the number that pins it; the gate (`kv_q2_parity`) reproduces the attention-error tables from a real KV dump. ## Why this shape ### The bit-allocation rule came from the real cache, not the synthetic one Measured with the gate's attention-output probe (relative RMS of attention output vs an FP16 cache) on a real stored KV cache dumped from a live serve (`--dump-kv`; 864 cells, 2 KV heads × 256 dims, rotated as stored), layer 3 unless stated: | arm | B/cell/head | attention error | |---|---:|---:| | q4_0 (reference) | 288 | 0.888% | | **K 2-bit per-channel + V 4-bit (`q2k`)** | **224** | **1.911%** | | K 4-bit + V 2-bit per-channel | 224 | 3.171% | | K 2-bit + V 2-bit per-channel (symmetric q2) | 160 | 3.508% | | K per-channel + V per-token, both 2-bit (KIVI's placement) | 160 | 5.188% | At equal bytes (224 B), **the bits belong on V**: K2c+V4 beats K4+V2c on every real layer measured (table below). On the synthetic gate cache the ranking is the reverse (K looks more sensitive) — synthetic data has no channel structure, which is why no ranking here is taken from it. The mechanism: V's quantization error enters the output directly through `softmax(qKᵀ)·V`, while much of K's error is common-mode across cells and cancels in the softmax normalization (`docs/kv-q2.md`). Both published intuitions survive, scoped: - **K's outliers are channel-aligned** (KIVI's premise) — true on real layers (K channel RMS max/median 5.8× on L3 up to 74.9× on L47), and honored by the per-channel K scale, not by more bits. - **V is the tensor the output feels** — so V gets 4 bits while K takes 2. ### Why per-channel K and per-token V Per-channel K scales (`block_q2c_0`: one fp16 scale per dimension per 32-cell group, a 4-level Lloyd-Max codebook) absorb K's channel outliers. V reuses the existing q4_0 path (per-token blocks), so the format adds no new V quantizer. KIVI's 2-bit per-token V loses on this cache: the Hadamard rotation leaves V's channel structure in place (V channel RMS max/median 7.9–14.5×), so 2-bit V would want per-channel scales too — at 4 bits per token, V carries q4_0's own error. ### Why the FP16 window — and why q2k needs the gain to use it The window is a separate, format-agnostic device. It only acts at decode: prompt-mode (prefill) logits never read the overlay, which is why the previous revision measured "no logit precision" — that was a blind spot of the measurement, not a property of the window. - At decode it helps q4_0: **−19.6%** KL (7 of 9 texts). - With q2k alone it **hurts: +10.3%** (4 of 9 better). The 4-level Lloyd-Max K codebook is MSE-optimal, so its reconstruction is shrunk: on real queries q2k's attention scores come out at **0.92–0.97×** the exact ones (q4_0: 0.997–0.998). Next to exact window cells that is a bias — the exact cells out-score the shrunk bulk, and the softmax over-weights the window by **+1.7..+5.9%** of its mass on 11 of 12 layers. - **`--kv-k-gain`** stores the K scale `B` × larger while choosing the codes against the un-gained scale, so no value moves to another level and only the reconstruction grows. With B = 1.10 the window turns into a gain: **−29.3%** at 128 cells, **−36.8%** at 256 (vs plain q2k). - Behaviorally the window recovers **symmetric q2's** short-answer loss (q2 2/3 → q2 + window 3/3); q2k matches the q4_0 reference on the recall probe without it (3/3). ## Measurements ### Gate (device kernels vs host reference) - `kv_q2_parity`: synthetic cache 40/40 checks (incl. the K-gain pin: stored scale = B × the rule, bit for bit, codes chosen against the un-gained scale); real cache layers 3/11/23/47 36/36 each. The q2k device arm (real append + gather kernels) lands on the host row: L3 1.910% device vs 1.911% host. - `kv_window_parity`: 10/10 — sink and window cells read bit-exactly equal to an FP16 pool; cells outside read the bulk pool bit-for-bit; `kv_window_restore` reproduces the bulk dequantization. - `kv_q4_parity`, `kv_q8_parity`, `kv_stream_parity`, `kv_hybrid_parity`: pass (existing formats untouched). ### Attention error by layer (real cache) | layer | K channel spread | q4_0 | **q2k (K2c+V4)** | K4+V2c | q2 (K2c+V2c) | |---|---:|---:|---:|---:|---:| | L3 | 5.8× | 0.888% | **1.911%** | 3.171% | 3.508% | | L11 | 5.9× | 0.740% | **2.002%** | 2.589% | 3.471% | | L23 | 14.2× | 0.941% | **2.211%** | 2.768% | 3.655% | | L47 | 74.9× | 1.040% | **1.645%** | 2.663% | 2.948% | The outlier layer (L47) is where q2k comes closest to q4_0. ### Attention error under the engine's append patterns (real cache) The row above appends every cell in one call — whole 32-cell groups — so it never runs the partial-group scale rule. The engine does, every request: speculative verify appends 2–5-cell windows that cross group boundaries, decode appends into the group the prompt ended in, and after a reused conversation prefix the 2048-cell prefill chunks fall mid-group. `kv_q2_parity` now replays those patterns on the same K/V and readers (attention output vs FP16). Three scale rules for a group first written by a partial batch: **old** = the pre-review kernel (sum / 32), **/n** = RMS of the n cells, **shrink** = shipped (full-group RMS, the previous group's mean square standing in for the cells not yet written): | layer | q4_0 | q2k one-shot | spec verify (3-cell windows) old / /n / shrink | chunked prefill (100-cell chunks, stress) old / /n / shrink | prompt + decode | |---|---:|---:|---:|---:|---:| | L3 | 0.888% | 1.910% | 1.978% / 1.912% / **1.892%** | 3.631% / 2.076% / 2.186% | 1.910% | | L11 | 0.740% | 2.002% | 2.030% / 2.011% / 2.012% | 3.617% / 2.727% / **2.626%** | 2.002% | | L23 | 0.941% | 2.211% | 2.895% / 2.667% / **2.245%** | 3.767% / 2.509% / **2.161%** | 2.211% | | L47 | 1.040% | 1.648% | 1.457% / 1.799% / **1.720%** | 1.438% / 1.346% / 1.803% | 1.648% | - Speculative verify (what every decode does at each group boundary): the excess over one-shot, summed over the four layers, is +8.0% with `/n` and **+1.3% with shrink**. - Chunked prefill is a stress case (real chunks are 2048 cells, aligned from position 0): shrink is mixed by layer there (1.4% worse summed than `/n`) and 30% better than the pre-review kernel. - Prompt + decode lands exactly on the one-shot row (pinned). On the extreme-outlier layer 47 an undersized scale acts as clipping, which is why the pre-review kernel measures better there. ### Logits (512-token prompts, prompt mode, vs FP16: top-1 agreement / mean KL) — re-measured with the CPU share off | text | q4_0 | q2 | **q2k** | |---|---|---|---| | code | 90.4% / 0.060 | 74.6% / 0.329 | **77.1% / 0.226** | | document | 91.6% / 0.030 | 81.2% / 0.203 | **83.8% / 0.133** | | chat | 92.4% / 0.027 | 81.2% / 0.177 | **83.4% / 0.144** | q2k's KL is 3.8–5.3× q4_0's at the prompt level: it is a cheaper format, not a lossless one. (The previous revision's table, measured with the CPU share on, read 2.5–5×.) ### Decode path (teacher-forced decode, 9 texts, vs FP16) Every arm is fed the same 128-token continuation, one token per window, and each row is compared with a forced FP16 run's row at the same position. Nine texts: three built-in prompts (chat, document, code agent) and six repo files up to 6144 tokens. A second FP16 run scores KL 0.0000 against the reference on all nine. Change = geometric mean over the texts vs plain q2k, with the texts that improved. | arm | mean KL | top-1 | vs q2k | |---|---:|---:|---:| | q4_0 | 0.0198 | 96.6% | −89.9% (9/9) | | q4_0 + window 128 | 0.0174 | 96.9% | −91.9% (9/9) | | q2k | 0.1825 | 88.5% | | | q2k + window 128 | 0.2060 | 87.3% | +10.3% (4/9) | | q2k + window 128 + gain 1.10 | 0.1338 | 89.8% | −29.3% (7/9) | | **q2k + window 256 + gain 1.10** | **0.1203** | **90.3%** | **−36.8% (8/9)** | Gain sweep at window 128 (same texts, development build): 1.03 −9%, 1.05 −15%, 1.08 −26%, 1.10 −30%, 1.13 −29%; the gain alone, with no exact cells, −1%. Even the best q2k setting keeps ~6× q4_0's decode KL. These rows were measured on this PR's build with a temporary copy of our teacher-forced decode tooling (`--force-tokens` + a per-window logits dump; not part of this PR). The PR build's prompt logits are byte-identical to our development build's under the same flags (`--kv q2k`, and `--kv q2k --kv-window 256 --kv-sink 8 --kv-k-gain 1.10`). The two builds sit on different upstream bases, and their decode rows differ slightly for every quantized format — plain q4_0 included — but never for FP16, so the development build's numbers are not quoted as this PR's. ### Behavioral A/B (~5K-token buried-fact probe, `tools/kv_recall_report.py`) Eight vault codes buried in a document: **mid** = the body; **late** = the last few paragraphs (~180–350 tokens before generation: outside a 128-cell window, inside a 512/1024 one). Scored by the instructed (vault, code) pair. Release q4_0 is the shipped binary; every other arm is this branch. | arm | mid | late | short answers | decode | |---|---|---|---|---| | release q4_0 (reference) | 4/4 | 4/4 | 3/3 | 158.3 t/s | | q4_0 (this branch) | 4/4 | 4/4 | 3/3 | 159.0 t/s | | q2 (symmetric) | 4/4 | 4/4 | **2/3** | 134.6 t/s | | **q2k (no window)** | 4/4 | 4/4 | **3/3** | 137.5 t/s | q2k matches the q4_0 reference on every measure at 22% less KV memory and ~13% lower decode speed; symmetric q2 is the arm that loses a short answer. An earlier 5-arm run (substring-scored) agreed, with 0/3 repetition loops for release q4_0 and q2k. ### Long-context recall at depth (smoke test) ~200K-token operations log (199,337 prompt tokens) served with `--kv q2k --max-context 262144`; three needles at **25% / 50% / 90%** depth — all three **recalled exactly** (WALRUS-CANARY-2247, QUARTZ-DELTA-8813, TUNDRA-FALCON-6631). Cold prefill of the full prompt: **2574 tok/s**. The verification pass rode the serve's conversation cache, which restores the same q2k-quantized state. Re-run on the final kernel (after the partial-group scale changes, fresh service, nothing cached): cold prefill of all 199,337 tokens at 2529 tok/s, 3/3 recalled. Re-run with the recommended `--kv q2k --kv-window 256 --kv-sink 8 --kv-k-gain 1.10` (fresh service, nothing cached): 199,337 tokens, **3/3 recalled**, 78.6 s wall including generation (~2537 tok/s). One model, one document. A small multi-turn agent task (find and fix two planted bugs across two files, iterate pytest to green) also completed correctly against the served q2k/262144 endpoint. ### Window sizing (symmetric q2 bulk + window) | arm | mid | late | short answers | decode | |---|---|---|---|---| | q2 + window 128 | 4/4 | 4/4 | 3/3 | 127.7 t/s | | q2 + window 512 | 4/4 | 4/4 | 3/3 | 136.1 t/s | | q2 + window 1024 | 3/4 | **0/4** | 3/3 | 129.0 t/s | 128 and 512 are behaviorally identical (512 decodes faster: the FP16 overlay is a cheaper read than the q2 bulk). 1024 regresses — the late facts sit *inside* a 1024-cell window, so exact reads should help, not collapse; this points at a defect at that size, not a trade-off. Unexplained; do not use 1024. ### Memory (262144 ctx, 12 QSA layers, 2 KV heads × 256 dims; the gain adds nothing) | format | B/cell | KV total | |---|---:|---:| | FP16 | 2048 | 6.00 GiB | | q4_0 | 576 | 1.69 GiB | | **q2k** | **448** | **1.31 GiB** | | + window 128 / sinks 8 | — | + 3.56 MiB | | + window 256 / sinks 8 | — | + 6.56 MiB | ## Reference papers - **KIVI** (arXiv 2402.02750) — K per-channel, V per-token, asymmetric 2-bit, 128 recent tokens in FP16. The K placement transfers (per-channel K wins on real layers); the V placement does not on this rotated cache (K2c+V2t 5.188% vs symmetric per-channel 3.508% at the same 160 B). - **SKVQ** (arXiv 2405.06219) — channel reordering, clipped dynamic quantization, an FP16 sliding window; K 2-bit / V 1.5-bit. Reordering is a no-op for per-channel-scaled K (a relabeling). During development (tooling not included in this PR) it helped per-token V on real layers, but SKVQ's byte budget still lost to plain per-channel 2-bit on every real layer. Clipping did not help (L3, in this PR's gate: clipped 4.731% vs unclipped 4.627%). - **KVSink** (arXiv 2508.04257) — attention-sink preservation under KV quantization; the reason the overlay keeps the first cells exact. - **QuaRot** (arXiv 2404.00456) — the Hadamard rotation the KV formats here (q4_0, q2, q2k) apply before quantizing. - **KVQuant** (arXiv 2401.18079) — per-channel (pre-RoPE) K and non-uniform codebooks; background for the per-channel K scale and the Lloyd-Max codebook. - **"More for Keys, Less for Values"** (arXiv 2502.15075) — argues K deserves more bits. At equal bytes on this rotated cache the measurement went the other way (above). - **AsymKV** (arXiv 2410.13212) — the 2-bit-K / 1-bit-V split; 1-bit V measured 9.7% (per-channel) to 14.4% (per-token) attention error on L3 here. ## Review fixes (Copilot review of this PR) All 15 findings were reproduced and fixed; the engine fixes are pinned by new gate checks, each shown to FAIL against the pre-fix code: - **q2/q2k pools are sized and moved in whole 32-cell groups** (high): fully resident pools, elastic VMM pools, the staging copy, the reverse DMA, and conversation snapshots (image size and reusable prefix). A page is not a byte range in the group-major layout. - **Fresh partial-group scale**: the RMS of the cells present (`/n`), not `/32` — then, measured under the engine's append patterns (table above), shrunk toward the previous group's scale in the batch path too: `s = sqrt((ss + (32 − n)·prev²)/32)`. `prev` is race-free: a previous group completed in the same launch is recomputed in-thread with its block's exact sum order; otherwise its stored scale is read. Pinned bit-exact (two-call and one-call appends must store the same scale). - **`--dump-logits` header repair** on every path, not only the native pack (CUDA and SYCL). - **Tools**: truncated KV dumps and zero-vocab logit headers fail cleanly instead of crashing; the no-e validator checks the letter anywhere; the engine-failure row prints; recall is scored by the (vault, code) pair (codes repeat between groups). Re-scoring the saved outputs left every arm above unchanged except q2 + window 1024 (late 1/4 → 0/4). - **`kv_pr_report.py`**: each tail code is now asked in its own request, inside the window. The 2026-10-11 README carries a correction: its earlier "tail" codes sat outside the window. - **Docs**: the overlay footprint (304 KiB/layer, 3.56 MiB total) and the q4_0 baseline (1.69 GiB at 262144) were ~2× off; a stale "dump-logits writes 0 bytes" note was removed. - Also fixed while re-measuring: two inverted gate labels (the K-vs-V check printed "K is the sensitive side" while proving V is), and the AsymKV citation (2410.13212, not 2411.17034). - **No machine-specific paths**: the harnesses and A/B scripts resolve everything from the repo's layout (`tools/kv_bench_env.py`: repo root, `Strata-data` next to it, `strata-<model>.json`, engines under `engine/` and `build/`) with an environment override for each; the READMEs carry a generic CUDA 13.0 build recipe instead of local scripts. ## Known limits - 2-bit K is the quality floor: q2k's prompt-level KL is 3.8–5.3× q4_0's, and even window 256 + gain 1.10 keeps ~6× q4_0's decode KL. - Reproducible measurements need `STRATA_PREFILL_CPU_SHARE=0` (prompt chunks under 1024 tokens otherwise split MoE experts with the CPU, and the split varies run to run). Engine default unchanged. - The gain is calibrated on one model (uniform 1.10, from a 1.03–1.13 sweep on nine texts). - Window 1024 regresses recall (above); unexplained. - Behavioral and long-context results are single-model, single-document. ## Commits 1. `kv_window` — FP16 sliding window + attention sinks over the quantized KV cache 2. `kv_q2` — 2-bit per-channel KV format, parity gate, measurement tooling 3. `kv_q2k` — K 2-bit per-channel + V 4-bit mixed-width format 4. `kv_q2` — whole 32-cell groups wherever a q2/q2k pool is sized or moved 5. `kv_q2` — a fresh partial group's scale is the RMS of the cells it has 6. `kv_q2_parity` — pins for the review fixes, and the inverted K-vs-V labels 7. `generate` — repair the `--dump-logits` header on every path 8. `tools` — crash fixes and (vault, code) pair scoring 9. `kv_pr_report` — tail probes inside the window 10. `docs` — footprint arithmetic, the tail-probe correction, the stale dump-logits gap, the AsymKV citation 11. `tools + scripts` — no machine-specific paths: repo-relative defaults, env overrides 12. `docs` — a generic CUDA 13.0 build recipe instead of local paths and scripts 13. `kv_q2_parity` — q2k under the engine's append patterns (spec verify, chunked prefill, prompt + decode) 14. `kv_q2` — a fresh partial group's scale shrinks toward the previous group's, in the batch path too 15. `kv_q2` — K reconstruction gain (`--kv-k-gain`): undo the 2-bit score shrink, codes unchanged, zero bytes --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-11-07 15:32:11 +07:00
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Niko1221/Strata#3978
No description provided.