mirror of
https://github.com/Niko1221/Strata.git
synced 2026-12-03 19:03:30 +07:00
[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
Labels
No labels
needs-format
pull-request
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set.
Reference
Niko1221/Strata#3978
Loading…
Add table
Add a link
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
📋 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+)
1aee5c9kv_window: FP16 sliding window + attention sinks over the quantized KV cache50bb59dkv_q2: 2-bit per-channel KV cache format, parity gate, and the measurement toolinga8d8469kv_q2k: K 2-bit per-channel + V 4-bit - the mixed-width point the real-cache gate found20ae0cbkv_q2: whole 32-cell groups wherever a q2/q2k pool is sized or movedcd8e5fakv_q2: a fresh partial group's scale is the RMS of the cells it has, not of 322408c22kv_q2_parity: pin the review fixes - fresh partial-group scale, whole-group stagingc0d8549generate: repair the --dump-logits header on every path, not only the native one63726fetools: review fixes - truncated dumps, zero-vocab headers, the no-e check, failure rows, pair scoring38ea09dkv_pr_report: ask each tail code in its own request, inside the window1f0b858docs: 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]Summary
Two composable KV-cache features behind opt-in flags, plus a correction that makes them work together:
--kv-window N(--kv-sink S) — an FP16 overlay over the firstScells (attention sinks) and the most recentNcells 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).--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).--kv-k-gain B(q2/q2k) — a K reconstruction gain: the stored K scale isB× 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.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:q2k)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: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.
--kv-k-gainstores the K scaleB× 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).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_restorereproduces 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)
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_paritynow 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):/nand +1.3% with shrink./n) and 30% better than the pre-review kernel.Logits (512-token prompts, prompt mode, vs FP16: top-1 agreement / mean KL) — re-measured with the CPU share off
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.
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.
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)
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)
Reference papers
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:
/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).previs 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-logitsheader repair on every path, not only the native pack (CUDA and SYCL).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.tools/kv_bench_env.py: repo root,Strata-datanext to it,strata-<model>.json, engines underengine/andbuild/) with an environment override for each; the READMEs carry a generic CUDA 13.0 build recipe instead of local scripts.Known limits
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.Commits
kv_window— FP16 sliding window + attention sinks over the quantized KV cachekv_q2— 2-bit per-channel KV format, parity gate, measurement toolingkv_q2k— K 2-bit per-channel + V 4-bit mixed-width formatkv_q2— whole 32-cell groups wherever a q2/q2k pool is sized or movedkv_q2— a fresh partial group's scale is the RMS of the cells it haskv_q2_parity— pins for the review fixes, and the inverted K-vs-V labelsgenerate— repair the--dump-logitsheader on every pathtools— crash fixes and (vault, code) pair scoringkv_pr_report— tail probes inside the windowdocs— footprint arithmetic, the tail-probe correction, the stale dump-logits gap, the AsymKV citationtools + scripts— no machine-specific paths: repo-relative defaults, env overridesdocs— a generic CUDA 13.0 build recipe instead of local paths and scriptskv_q2_parity— q2k under the engine's append patterns (spec verify, chunked prefill, prompt + decode)kv_q2— a fresh partial group's scale shrinks toward the previous group's, in the batch path tookv_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.