mirror of
https://github.com/Niko1221/Strata.git
synced 2026-12-03 19:03:30 +07:00
[PR #4068] [Engine] KV cache: the exact-cell window for q4lm8v (opt-in, hardened) #4896
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#4896
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/4068
Author: @monscoro
Created: 10/25/2026
Status: 🔄 Open
Base:
main← Head:kv-window-0.2📝 Commits (10+)
38ea4a0KV: 4-bit Lloyd KV with an exact-cell window (opt-in)7af3ab5KV window: the free ring caps the auto chunk scan at 6,144 cells toofd97adeKV window: --kv-resident and the exact-cell window refuse each otherfd3fc13KV window: freeze the grid after the prompt chunk settles (A3-lite)1e4933eKV window: tag the empty ring rows with 0xFF (A5)0497be1KV cache: --kv-check helper and a DETAILS.md sectiond5a337aKV cache: document the quantization choices and the window method955ceb6docs: add the KV-window hardening paper (two-column LaTeX)f3eb28bdocs: revise the KV-window paper (related work, survey table, design alternatives, discussion, provenance; 8 pp)ca1bca0docs: needle A/B evidence for the window (int8 against 256/64)📊 Changes
39 files changed (+2652 additions, -157 deletions)
View changed files
➕
bench/results/2026-10-24-needle-window/README.md(+50 -0)➕
bench/results/2026-10-24-needle-window/cfg-needle-int8.json(+37 -0)➕
bench/results/2026-10-24-needle-window/cfg-needle-win.json(+40 -0)➕
bench/results/2026-10-24-needle-window/needle-int8.engine.txt(+100 -0)➕
bench/results/2026-10-24-needle-window/needle-win.engine.txt(+101 -0)➕
bench/results/2026-10-24-needle-window/needle_ab.py(+83 -0)➕
bench/results/2026-10-24-needle-window/needles-int8.json(+56 -0)➕
bench/results/2026-10-24-needle-window/needles-win.json(+56 -0)📝
docs/AMD_HIP.md(+4 -0)📝
docs/DETAILS.md(+38 -0)➕
docs/paper/KV-Window-Hardening.pdf(+0 -0)➕
docs/paper/KV-Window-Hardening.tex(+493 -0)📝
include/strata/core/layer.hpp(+62 -1)📝
include/strata/kernels/kv_q4.hpp(+118 -5)📝
include/strata/kernels/kv_stream.hpp(+25 -1)📝
include/strata/kernels/qsa_decode_attn.hpp(+62 -0)📝
setup.py(+241 -14)📝
src/core/conversation_snapshot.cpp(+9 -0)📝
src/core/layer.cpp(+163 -4)📝
src/core/mtp.cpp(+28 -4)...and 19 more files
📄 Description
[Engine] KV cache: the exact-cell window for q4lm8v (opt-in, hardened)
What this is, and what it is not
A basis, not the finished answer. It makes one KV mode safe, measurable and opt-in — the exact-cell
window on 4-bit Lloyd K/V — and it fixes the four bugs that shape exposed (A1–A5). What it enables is the
next step: a bug-corrected, more aggressive KV quantization that is checked for correctness instead of
tuned by feel. The levers that remain are named, not built: per-channel K before the rotation, lower-bit V,
a parity test over the whole cell→row contract, and the format-agnostic overlay of #2318 (see Follow-up).
And the KV cache is only one building block of the footprint problem. On this model the expert cache, the
PLE table and the dense weights are where the rest of it sits; the numbers in this PR are one card's
(RX 9060 XT 16 GB) on one quantization (IQ3_XXS).
Problem and result
int8KV costs 8.25 bit/cell: 1,584 MiB at 128K context. On a 16 GB card that is the difference betweenfitting the expert cache the model wants and paging. The exact-cell window is the memory/accuracy answer:
quantize the KV bulk with 4-bit Lloyd (K and V), keep the most recent cells (S=256) and the first cells
(sinks, R=64) exact in a small resident side pool. Measured result: 5.29 bit/cell, 1,016 MiB at 128K
(RX 9060 XT, Windows HIP), with the 128K-tail teacher-forced KL better than int8's: window 0.00663
against int8's 0.00959 and plain q4lm8v's 0.01587 (KL vs the fp16 reference, last 4,096 of 131,062
positions, measurement of the feature commit).
This PR ships the feature together with the hardening it needed to be safe (A1–A5 below), a
--kv-checkhelper, and the documentation. Every window-affecting line is gated behind
qsa_kv_win()/st.k_win != nullptr; the default path is untouched (the byte-identity SHA is the regression gate, run8 times old-vs-new).
Related discussion
comes as a draft instead, so the shape can be discussed on the diff itself. If you prefer the issue
first, I will open one and follow it with this branch.
0.2.0-beta tracker reset ("closed does not mean rejected"). The maintainer's bar there — "It would need
our KL and needle checks before it can be offered as an experimental option" — is the bar this PR is
measured against: KL checks below, needle check under Validation. Differences to #2318 are in
Related work at the end.
STRATA_KV_RING_ADAPT, open) makes--kv-residenta cap for adaptive ring sizing. This PR's A2 refuses
--kv-residentwith the window before anythingloads, so the two do not interact: RING_ADAPT only ever grows a resident ring, and a resident ring beside
the window is exactly what A2 refuses. If #3919 merges first, nothing here changes; if this merges first,
#3919 needs nothing either.
Approach
Why this shape. The window is a memory plan, not a tunable: its exact cells live in an always-resident
side pool, so the whole design follows from that one property. It cannot combine with KV streaming (the
streamed bulk has no resident pool to read the exact cells from — A2), the prompt chunk that sizes the ring
must never exceed the ring's scan limit (A1), every state carved later must read the same grid (A3), and an
empty ring slot must be distinguishable from cell 0 (A5). The four fixes are that shape's consequences, not
bolt-ons.
The fixes, one commit each, each with the default-path byte-identity proof:
7af3ab59kv_append_win: 8191 cells ... 6400-row ... ring,std::exit(1)mid-prompt. After:prompt chunk auto: 6144,DONE 8192.fd97ade2--kv-resident(streaming) and the window refuse each other: the engine refuses the pair loudly (exit 2, before anything loads); setup never writes it (aq4lm8vconfig's KV stays in VRAM, streaming explained off).--kv-checkreports the pair asNO - refused (exit 2).fd3fc135qsa_kv_win_freeze()), so main/MTP-drafter/MTP-twin states cannot drift.1e4933e10xFF(-1) instead of0, so an unwritten row can never be read as exact cell 0.Plus
0497be1b(--kv-checkhelper + adocs/DETAILS.mdKV section),d5a337a2(documented numbers +method note),
955ceb65+6acc91de(a two-column paper of the design and its decisions, and the same paperafter an independent desk review;
docs/paper/KV-Window-Hardening.tex),ca1bca07(the needle run's rawJSON, configs, engine logs and runner under
bench/results/), and6c3bd969(setup installs an engine builtfrom this tree:
--engine-dir DIR/STRATA_ENGINE_DIR, or the newestbuild-hip*/strata.exeby itself whenq4lm8vischosen — no ready-made engine carries the mode, so without this the feature cannot be tried before a
release; the default download path is untouched).
Known limits of the design (why A3-lite and not a full state-layout refactor): the full A3 refactor is
held back until the follow-up parity test (below) exists; A3-lite freezes and asserts instead of moving
fields. An explicit small ring (
STRATA_KV_WINDOW_BATCH) with--prefillabove it still refuses by design— the message names what to change.
Trying it (reviewer path)
No ready-made engine carries
q4lm8vyet, so setup has to install one built from this branch.6c3bd969wires that in; without it a reviewer would have to package a release zip first.
tools\hip\build_windows.baton Windows (it packagesdist\), or any build of thistree that left a
build-hip*/strata.exe; Linux as indocs/AMD_HIP.md.START-HERE.bat --setup --kv q4lm8v— setup picks the newestbuild-hip*/strata.exeon its own andsays
q4lm8v is only in an engine built from this tree: using <folder> instead of the ready-made one.An explicit folder works too (
--engine-dir <folder>orSTRATA_ENGINE_DIR); only the Windows HIP pathwas run (see Not run). If no build is found, setup stops with what to do instead of downloading an
engine that cannot run the mode.
build-vision\bin,or compiled once); a self-built engine has no GPU reader unless one was built.
--kv q4lm8vandSTRATA_KV_WINDOW=1/_S=256/_R=64into the model's config.python setup.py --kv-checkthen prints mode, env, effective bits/cell and whether the engine wouldstart; the engine log names the window (
KV window ring sized for the prompt chunk (6144 cells)).--kv int8(the default) never takes this path: no build folder is looked for and the ready-made engineis downloaded exactly as before.
UPDATE.batreplaces the engine folder with a ready-made one, so it is not part of this test.Validation
Hardware for every run below: AMD Ryzen 9 3900XT, 64 GB DDR4-3000, RX 9060 XT 16 GB, Windows 11, ROCm 7.1,
Swift-Qwen3.8-Flash-Next IQ3_XXS. One GPU job at a time, quiet machine; timing numbers from noisy sessions
are not quoted. Reproduction commands live in the PR's commits and in
docs/DETAILS.md.Passed:
int8dump-logits SHAA014F504BA315831DA1D13C6A0B3D23D6393B919872396C2A1464182710BA052(4,330,448 bytes, 4,095 positions) — 8/8 runs (4K A/B, rounds 1–4, old/new interleaved), identical
to the pre-change binary.
0768398A...94CA(8,191 rows, 8,192 ids,--prefill auto:16384),4161376D...707E(4,095 rows, cwe-4k),71B0B586...6463(4,095 rows, set-4096).STRATA_LOGPOS,quant_quality.py compare): window vs int8 on the same segment setKL 0.04524, top-1 98.00%; the feature commit's 128K-tail KL vs the fp16 reference: window 0.00663,
int8 0.00959, plain q4lm8v 0.01587.
DONE 8192, chunk 6144, no refusal. Probe C (explicit ring 512 +--prefill 2048): refused as the contract says.--kv-resident+ window pair refused in ~1 s (exit 2, message names thefix); window-alone and int8+streaming configs get past it.
tools/test_setup_choices.py: 56/56 pass (incl. the new A2 setup assertions).6c3bd969, Windows HIP,engine_steprun directly withkv="q4lm8v"): installsbuild-hip-port\strata.exeintoengine\withBUILD.json"source": "local"and the version readfrom the binary, copies the CPU image reader from
build-vision\bin(hip_reader→mode: cpu), andnames a running model ("… is in use: a model is running from it") instead of a
PermissionError.tools/needle_bench.pythroughserve/server.py, 32k and 128k prompt tokens at depths10/50/90, identical deterministic prompts for both arms,
STRATA_PREFILL_CPU_SHARE=0): 6/6 found withint8, 6/6 found with the window — the code word was recalled at every depth at both lengths in both
arms (31,643–31,644 and 126,015–126,017 prompt tokens). Raw data, configs and logs:
bench/results/2026-10-24-needle-window/. Single run per arm, one model, repo-file haystack; wall-clocktimes are not quoted as a speed comparison (see the limits).
Failed: none observed.
User test (setup journey)
A Strata user set the branch up the way the project documents it, not as a developer:
START-HERE.bat --setup --family swift --model IQ2_XS --gguf-dir <their own abliterated IQ2_XS shards> --port 7601, KV menu choice 3(
q4lm8v), 131K context, pictures on (CPU reader). The first attempt is what produced6c3bd969: setup wentfor the ready-made engine (404 for this version on the release page, then the signed update feed), which
cannot run the chosen KV mode, instead of a build of the branch. After the fix the same run installs the
local build and the CPU reader, writes
--kv q4lm8vwithSTRATA_KV_WINDOW=1/_S=256/_R=64, and themodel starts and answers in chat. The engine's own status reports
kv: q4lm8v,kv_resident: 0,prefill_cap: 6144(A1) andimages: true, with 5.94 GiB of expert cache and 2.3 GiB VRAM free at 131K.Covered: setup, start, short chat (IQ2_XS, RX 9060 XT 16 GB, Windows HIP). Not covered by this user test:
long-context work, pictures through an app, switching the same install back to
int8, third-party appwiring. A speed suite ran on the same install afterwards; it is a single arm without an
int8comparisonand is therefore not used as window evidence.
Not run:
backend-agnostic (globals, argument checks, setup Python, one memset value); SYCL does not offer
q4lm8vat all (WINDOW_KVis False there), so the window paths are dead code on SYCL but stillcompile-checked there would be the ask. Requesting a targeted CUDA + SYCL build in this thread.
reasoned about (the gating is per-session), not executed.
int8install through the new code path was not re-run(the branch is entered only with
--engine-dir/STRATA_ENGINE_DIRorq4lm8v), nor was--engine-dirwith a CUDA build or on Linux.
docs/paper/KV-Window-Hardening.texcompiled by CI: the author's TeX build is local (MiKTeX); the fileis documentation, no GPU build needed per CONTRIBUTING.
Limits
(setup's
--kv-checkprints the effective bits/cell so the plan is inspectable).--prefill autois capped at 6,144 cells in windowed runs (A1) — a deliberate contract, visible in theprompt chunk auto:line.the repo-file haystack (needles). The KL numbers are single-model, single-document measurements.
server during both arms (runner bug on the author's side), which queues the requests. Found/missed is
unaffected — both clients asked the same deterministic prompts and every answer was found — but the
seconds per request are not a clean speed measurement.
teacher-forced read path and long-context recall, not every ring-wrap/stale-tag/sink shape.
--prefillabove it still refuses (by design; the messagenames the remedy). SYCL ignores
STRATA_KV_WINDOWsilently (setup never writes it there).Related work (vs #2318)
Both PRs keep recent cells exact over a quantized bulk; they differ in what the exactness is made of and
where the device sits:
--kv-window N,--kv-sink S) on top of any formatq4lm8v= 4-bit Lloyd K+V + exact side pool (S=256/R=64)--kv-k-gain#2318's overlay is format-agnostic and its q2k format is the cheaper bulk; this PR's window is one format
whose measured point (5.29 bit @128K) sits between q4_0 (576 B/cell) and q2k (448 B/cell) while its 128K
tail KL beats int8. If both land, they compose differently and do not conflict: #2318's device would sit on
top of formats, this one is a format; nothing in either diff touches the other's paths.
Follow-up (not in this PR)
A window parity test over the whole cell→row contract: dump every window row at write time and re-read it
through
qsa_win_sloton each shape (writerwin_row_ofkv_q4.cu:391↔ readerqsa_decode_attn.hpp:73,host
:93; ring wrap; stale-tag→quantized fallback; sink rows; batch-boundary shapes; the empty-tag caseA5 guards). The KL/needle checks above cover the read path, not these shapes; this is why A3 was shipped
as A3-lite. Meanwhile the window stays opt-in and the int8 default stays byte-identical.
🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.