Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
Merge PR #21: Q4_0 KV with Hadamard rotation (--kv q4_0), integrated with KV streaming; accurate expert-cache note (#23)
Niko122140542e8bb3ce
diff --cc CMakeLists.txtindex 9a7260b57,457a097e3..9debf8103--- a/CMakeLists.txt+++ b/CMakeLists.txt@@@ -363,6 -364,12 +364,12 @@@ if(STRATA_ENABLE_CUDAtarget_link_libraries(kv_stream_parity PRIVATE strata_kernels CUDA::cudart)add_test(NAME kv_stream_parity COMMAND kv_stream_parity)- # Q4_0 KV storage with Walsh-Hadamard rotation vs host reference (GPU, synthetic, no model).++ # PR #21: Q4_0 KV with Walsh-Hadamard rotation vs a host reference (GPU, synthetic, no model).+ add_executable(kv_q4_parity src/kernels/kv_q4_parity.cpp)+ target_include_directories(kv_q4_parity PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES})+ target_link_libraries(kv_q4_parity PRIVATE strata_kernels CUDA::cudart)+ add_test(NAME kv_q4_parity COMMAND kv_q4_parity)+# Plan v0.3 P3: native MMVQ for 1..8 tokens (bitwise selftest + --bench timing); synthetic data, no model.if(STRATA_BUILD_TESTS)add_executable(native_mmvq_multi bench/micro/native_mmvq_multi.cpp)diff --cc bench/results/2026-09-27-cache-parity/README.mdindex 000000000,000000000..10f1d19d8new file mode 100644--- /dev/null+++ b/bench/results/2026-09-27-cache-parity/README.md@@@ -1,0 -1,0 +1,29 @@@++# 2026-09-27: expert cache on vs off (issue #23)++++Question: the engine used to warn at start that "the GPU hit path is NOT CORRECT ... any OUTPUT from it is not". Does++the expert cache make the output worse?++++Method: teacher-forced. `strata --dump-logits` runs a text one token at a time and writes the logits at every++position, so both runs see the same text and each position's next-token prediction can be compared:++- cache off: no `--expert-cache`, every routed expert computed by the CPU pool;++- cache on: `--expert-profile pack/profile-decode-8k.bin --expert-cache auto`, 5,130 of the most-used experts on the GPU.++++Q2_0, RTX 5070, the first 512 or 1,024 tokens of three frozen prompts.++++| Text | Same top-1 | Median KL | Perplexity off | Perplexity on | On - off (nats per token) |++|---|---:|---:|---:|---:|---:|++| Code agent (512) | 97.7% | 3.0e-04 | 2.672 | 2.630 | -0.016 +- 0.019 |++| Long document (1,024) | 96.2% | 4.5e-03 | 29.844 | 29.843 | -0.000 +- 0.005 |++| Chat (1,024) | 95.0% | 4.4e-03 | 18.380 | 18.301 | -0.004 +- 0.006 |++| **All 2,557 tokens** | | | | | **-0.005 +- 0.005** |++++Reading:++- The cache changes which of two nearly equal candidates wins at 2-5% of positions. Most of the flips have a top-2++ margin under 0.5 logits (`logits-compare.txt`).++- Neither side is more accurate: the perplexity of the actual text is the same, within 1 standard error.++- A GPU expert and the CPU compute the same quantized expert with a different floating-point order. Both are an++ equally good approximation of the model.++++The start-up warning dates from round 328, when the GPU hit path had a real fault (divergence from token 0). That fault++was fixed long ago and is covered by `expert_parity`, `native_expert_parity` and the grouped kernels' tests. Since++engine 0.1.8 the warning is replaced by one accurate line.diff --cc bench/results/2026-09-27-kv-q4/README.mdindex 000000000,000000000..7cfa891f8new file mode 100644--- /dev/null+++ b/bench/results/2026-09-27-kv-q4/README.md@@@ -1,0 -1,0 +1,60 @@@++# 2026-09-27: Q4_0 KV with Hadamard rotation (PR #21, `--kv q4_0`)++++PR #21 (code-martin) adds a 4-bit K/V format: an orthonormal 256-point Walsh-Hadamard rotation of K, V and Q, then++ggml `q4_0` blocks (576 B per cell and layer, vs 1,056 B in int8).++++## Integration fixes made on merge++++- **Q4 + KV streaming (`--kv-resident`).** The PR had no host copy for Q4 and skipped the staging, so with streaming++ on, the prompt path wrote K/V through the residency map's -1 entries (out-of-bounds writes).++ - Q4 is now a third format in `kv_stream`: host copy, block residency, prompt-path staging, MTP ring and STATE_HASH.++ - `kv_stream_parity` checks it bitwise, streamed vs resident, with ring restore.++- **Duplicate attention.** The per-token decode path ran attention twice, the first time before the selection's++ blocks were made resident; it now runs once.++- **Tie-break.** The group maximum's tie-break is now deterministic across lanes: equal |x| with opposite signs++ could give one block two scales.++- **Unrelated changes dropped:** duplicate path fixes (already in 0.1.7), personal `.gitignore` entries, and a++ re-encoded CMakeLists.++++`kv_q4_parity` (the PR's test) and all 70 ctest tests pass.++++## Quality (teacher-forced, `tools/kv_precision_compare.py`)++++Same text, same fixed expert set (Q2_0, 3,000 slots, `--adapt-swaps 0`); only `--kv` differs. fp16 is the reference.++++| Text | KV | Same top-1 as fp16 | Mean KL | Perplexity | vs fp16 (nats/token) |++|---|---|---:|---:|---:|---:|++| code agent (512) | int8 | 98.4% | 0.014 | 2.649 | -0.011 +- 0.006 |++| | q4_0 | 95.7% | 0.030 | 2.598 | -0.031 +- 0.014 |++| document (1,024) | int8 | 95.6% | 0.009 | 30.18 | +0.012 +- 0.005 |++| | q4_0 | 91.3% | 0.039 | 32.26 | **+0.078 +- 0.011** |++| chat (1,024) | int8 | 95.5% | 0.009 | 18.24 | -0.003 +- 0.005 |++| | q4_0 | 90.7% | 0.028 | 18.52 | +0.012 +- 0.008 |++| document, 8K (every 8th position) | int8 | 92.3% | 0.114 | 7.63 | -0.013 +- 0.020 |++| | q4_0 | 88.0% | 0.297 | 8.65 | **+0.112 +- 0.037** |++++- **int8 is indistinguishable from fp16** (within about 2 standard errors everywhere).++- **q4_0 costs measurable precision, and more as the context grows:**++ - document perplexity +8% at 1K and +12% at 8K;++ - the KL from fp16 is 2.6-4.2x int8's;++ - code and chat are near-neutral.++- **Needles with `--kv q4_0 --kv-resident 32768`: 5/5** (1K, 32K, 128K at 10% and 90% depth, 262K;++ `needles-q4.*`). Retrieval holds.++++## Speed and memory (Q2_0, 128K, matrix bench, `--kv-resident 32768`)++++| KV | Expert slots | Decode tok/s | Tokens/round | Rounds/s | K/V in RAM |++|---|---:|---:|---:|---:|---:|++| int8 (`kv-stream/matrix-stream`) | 4,044 | 62.4 | 2.52 | 24.8 | 1.52 GiB |++| q4_0 (`matrix-q4`) | 4,190 | 67.4 | 2.62 | 25.7 (+3.7%) | 0.83 GiB |++++Without streaming (contexts up to 64K, or too little RAM for it) q4_0 halves the whole KV cache in VRAM instead.++++## Decision++++`--kv q4_0` is a user option:++- `START-HERE.bat --kv q4_0`, or the question setup asks above 8K context;++- or `--kv q4_0` in a `strata-*.json`.++++int8 stays the default: every published quality number was measured with it, and q4_0's precision cost is real,++though it passes the needles.diff --cc docs/DETAILS.mdindex 251954513,3c7ee34d8..11d70011b--- a/docs/DETAILS.md+++ b/docs/DETAILS.md@@@ -42,6 -42,6 +42,11 @@@ attention reads in VRAM (`--kv-residencosts ~13.7 KB of RAM per context token (1.7 GB at 128K). Existing installs: run `START-HERE.bat --setup` once to turnit on.++**4-bit KV cache (engine 0.1.8, optional):** `START-HERE.bat --setup` asks above 8K context (or pass `--kv q4_0`). It++halves the KV cache's memory with a Hadamard rotation before 4-bit rounding (PR #21), about 4% faster at 128K, but it++is measurably less precise on long documents (perplexity +8-12%; needle tests still pass). 8-bit stays the default.++Details: [`bench/results/2026-09-27-kv-q4`](../bench/results/2026-09-27-kv-q4/README.md).++Time to first token is prompt length / prompt speed: about 7 s at 4K, 55 s at 32K, 4 minutes at 128K and 9 minutes at262K. The raw numbers: [`bench/results/`](../bench/results/). The [paper](paper/Strata-Paper.pdf) explains every number.diff --cc include/strata/core/layer.hppindex 1ea792201,0eeecf277..fe966bfb9--- a/include/strata/core/layer.hpp+++ b/include/strata/core/layer.hpp@@@ -207,6 -211,6 +207,10 @@@ struct QsaStateint8_t* v_q = nullptr;uint16_t* k_scale = nullptr;uint16_t* v_scale = nullptr;++ /// PR #21: Q4_0 KV with Walsh-Hadamard rotation (qsa_set_kv_q4, kv_q4.hpp): 144 B per cell and head++ bool kv_q4 = false;++ uint8_t* k_q4 = nullptr;++ uint8_t* v_q4 = nullptr;int32_t* page_table = nullptr; ///< (n_pages,) logical page -> physical page (-1: not resident, streamed)int64_t n_pages = 0;int64_t max_cells = 0;@@@ -269,6 -273,8 +273,13 @@@ uint64_t qsa_kv_host_bytes()/// initializing the session; default off until gate G-C accepts it.void qsa_set_kv_int8(bool enabled);bool qsa_kv_int8();++/// PR #21: store K/V as Q4_0 after a Hadamard rotation (`--kv q4_0`): 576 B per cell, vs 1,056 in INT8.+ void qsa_set_kv_q4(bool enabled);+ bool qsa_kv_q4();++/// The state's KV format for the block-moving functions of kv_stream.hpp (kKvF16 / kKvInt8 / kKvQ4).++inline int qsa_kv_format(const QsaState& st) {++ return st.kv_q4 ? strata::kernels::kKvQ4 : st.kv_int8 ? strata::kernels::kKvInt8 : strata::kernels::kKvF16;++}uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, QsaState& st,const QsaState* share_rope = nullptr, int64_t ring_cells = 0);/// KV streaming: the pools a reader sees (the VRAM slots) and, when streamed, make the selection's blocks resident.diff --cc include/strata/kernels/kv_q4.hppindex 000000000,a75f2812d..930b628c1mode 000000,100644..100644--- a/include/strata/kernels/kv_q4.hpp+++ b/include/strata/kernels/kv_q4.hpp@@@ -1,0 -1,53 +1,61 @@@-// include/strata/kernels/kv_q4.hpp - Q4_0 KV storage with Walsh-Hadamard rotation for QSA layers.++// include/strata/kernels/kv_q4.hpp - Q4_0 KV storage with Walsh-Hadamard rotation for the QSA layers (`--kv q4_0`).++//++// From PR #21 (code-martin). K and V are rotated by the orthonormal 256-point Hadamard matrix H before they are++// quantized to ggml's q4_0 (32 values per block: an fp16 scale + 16 bytes of 4-bit codes, 144 B per head per cell,++// 576 B per cell for K and V of both heads, vs 1,056 B in INT8). The rotation spreads a head's outlier channels++// over all 256 dimensions, which is what makes 4 bits usable. The query is rotated the same way, so++// <Hq, Hk> = <q, k> and the scores are unchanged, and the attention output (a mix of rotated values) is rotated++// back with H (self-inverse). What is lossy is the 4-bit rounding itself: measured, not assumed, in++// bench/results/2026-09-27-kv-q4.++//++// With KV streaming (--kv-resident) the codes live in the host copy and the resident slots like INT8's (KvHostPools++// k_q4/v_q4, the same block granule), so both options combine.+ #pragma once++ #include "strata/kernels/qsa.hpp"-#include <cuda_fp16.h>+++ #include <cstdint>++ namespace strata::kernels {++ inline constexpr int QK4_0 = 32;++ #pragma pack(push, 1)+ struct block_q4_0 {- uint16_t d; // delta (half fp16 scale)- uint8_t qs[QK4_0 / 2]; // 16 bytes = 32 4-bit nibbles++ uint16_t d; // scale (fp16 bits)++ uint8_t qs[QK4_0 / 2]; // 32 4-bit codes: element j in the low nibble of qs[j], j + 16 in the high one+ };+ #pragma pack(pop)++ static_assert(sizeof(block_q4_0) == 18, "block_q4_0 must be 18 bytes");+-/// Bytes per cell (one token, one KV head): 8 blocks of 32 for head_dim=256 -> 144 bytes per head.-inline uint64_t kv_q4_bytes_per_head(int head_dim) {- return (uint64_t) (head_dim / QK4_0) * sizeof(block_q4_0);-}++/// Bytes per cell and KV head: 8 blocks of 32 for head_dim 256 -> 144.++inline uint64_t kv_q4_bytes_per_head(int head_dim) { return (uint64_t) (head_dim / QK4_0) * sizeof(block_q4_0); }+++/// Bytes per cell (one token, one layer): K and V of every KV head.+ inline uint64_t kv_q4_bytes_per_cell(const QsaShapes& s) {- return (uint64_t) s.n_head_kv * kv_q4_bytes_per_head((int) s.head_dim) * 2; // K and V++ return (uint64_t) s.n_head_kv * kv_q4_bytes_per_head((int) s.head_dim) * 2;+ }+-/// Orthonormal Fast Walsh-Hadamard Transform (FWHT) for dimension 256.-/// Self-inverse: H * H * x = x. Scale is 1 / sqrt(256) = 1/16.++/// Orthonormal Fast Walsh-Hadamard Transform of rows of 256 floats (scale 1/16): its own inverse.+ void fwht256_cuda(const float* src, float* dst, int64_t n_rows, void* stream);--/// In-place FWHT256-inline void fwht256_inplace_cuda(float* data, int64_t n_rows, void* stream) {- fwht256_cuda(data, data, n_rows, stream);-}--/// Append the cell at step[kStepPos] into Q4_0 pool with Hadamard rotation.-void kv_append_q4_step(uint8_t* k_q4, uint8_t* v_q4, const int32_t* page_table,- const int32_t* step, const float* kcur, const float* vcur,- const QsaShapes& s, void* stream);--/// Batched append of T cells into Q4_0 pool.-void kv_append_q4(uint8_t* k_q4, uint8_t* v_q4, const int32_t* page_table, int64_t pos0, int64_t T,- const float* K, const float* V, const QsaShapes& s, void* stream);--/// Gather step[kStepWidth] cells named by `ids` from Q4_0 pool into FP16 scratch [id][kv_head][head_dim].-void kv_gather_q4_step(const uint8_t* k_q4, const uint8_t* v_q4,- const int32_t* page_table, const int32_t* ids, const int32_t* step, int64_t max_ids,- const QsaShapes& s, uint16_t* k_scratch, uint16_t* v_scratch, void* stream);++inline void fwht256_inplace_cuda(float* data, int64_t n_rows, void* stream) { fwht256_cuda(data, data, n_rows, stream); }++++/// Append the (already rotated) cell at step[kStepPos]. With a host copy (KV streaming) it is written there too,++/// and to VRAM only if its block is resident.++void kv_append_q4_step(uint8_t* k_q4, uint8_t* v_q4, const int32_t* page_table, const int32_t* step,++ const float* kcur, const float* vcur, const QsaShapes& s, void* stream,++ const KvHostPools* host = nullptr);++++/// The prompt path: T consecutive (rotated) cells from pos0, K/V [T, n_head_kv, 256]; also into `stage` (identity++/// layout, the one-layer staging pool of a streamed session) when given.++void kv_append_q4(uint8_t* k_q4, uint8_t* v_q4, const int32_t* page_table, int64_t pos0, int64_t T, const float* K,++ const float* V, const QsaShapes& s, void* stream, const KvHostPools* host = nullptr,++ const KvHostPools* stage = nullptr);++++/// Gather step[kStepWidth] cells named by `ids` into FP16 scratch [id][kv_head][head_dim] (still rotated).++void kv_gather_q4_step(const uint8_t* k_q4, const uint8_t* v_q4, const int32_t* page_table, const int32_t* ids,++ const int32_t* step, int64_t max_ids, const QsaShapes& s, uint16_t* k_scratch,++ uint16_t* v_scratch, void* stream);++ } // namespace strata::kernelsdiff --cc include/strata/kernels/kv_stream.hppindex 3b5d70fbe,3b5d70fbe..b3ebee34d--- a/include/strata/kernels/kv_stream.hpp+++ b/include/strata/kernels/kv_stream.hpp@@@ -36,9 -36,9 +36,15 @@@ struct KvHostPoolsint8_t* v_q = nullptr;uint16_t* k_scale = nullptr; ///< int8 mode: fp16 scale per 64 valuesuint16_t* v_scale = nullptr;-- bool present() const { return k_pool != nullptr || k_q != nullptr; }++ uint8_t* k_q4 = nullptr; ///< q4_0 mode (kv_q4.hpp): block_q4_0 codes, 144 B per cell and head++ uint8_t* v_q4 = nullptr;++ bool present() const { return k_pool != nullptr || k_q != nullptr || k_q4 != nullptr; }};++/// The KV storage format, for the functions below that move whole blocks (`fmt`): fp16, int8 (+ scales), q4_0.++/// (A bool `int8` argument still reads as kKvF16 / kKvInt8.)++enum KvFormat : int { kKvF16 = 0, kKvInt8 = 1, kKvQ4 = 2 };++/// The residency map of a streamed layer, all device memory at fixed addresses (the graphs bake them in).struct KvStreamMap {int32_t* page_table = nullptr; ///< (n_blocks,) block -> slot, or -1@@@ -62,7 -62,7 +68,7 @@@ void kv_stream_reset(const KvStreamMap/// Make every block named by the selections of `n_q` queries resident (ids [n_q][cap], width from/// steps[q * kStepCount + kStepWidth]). Capturable. `n_slots` must hold the distinct blocks of one call/// (n_q x (cap / page_size + 2)); a call that cannot sets ctl[3] (see `kv_stream_counters`).--void kv_stream_resolve(const KvStreamMap& m, const QsaAttnPools& slots, const KvHostPools& host, bool int8,++void kv_stream_resolve(const KvStreamMap& m, const QsaAttnPools& slots, const KvHostPools& host, int fmt,const int32_t* ids, const int32_t* steps, int64_t n_q, int64_t cap, const QsaShapes& s,void* stream);@@@ -71,12 -71,12 +77,12 @@@ void kv_ring_table(int32_t* page_table/// Copy blocks [b0, b1) of the host copy into the pool pages `page_table` names (host-side table `phys(b)`/// computed as `b % n_slots`: the ring restore). Not capturable.--void kv_ring_restore(const QsaAttnPools& slots, const KvHostPools& host, bool int8, int64_t b0, int64_t b1,++void kv_ring_restore(const QsaAttnPools& slots, const KvHostPools& host, int fmt, int64_t b0, int64_t b1,int64_t n_slots, const QsaShapes& s, void* stream);/// Copy the first `n_blocks` blocks of the host copy into a fully resident (identity-layout) pool: the prompt/// path's staging of one layer. Not capturable (DMA).--void kv_stage_from_host(const QsaAttnPools& stage, const KvHostPools& host, bool int8, int64_t n_blocks,++void kv_stage_from_host(const QsaAttnPools& stage, const KvHostPools& host, int fmt, int64_t n_blocks,const QsaShapes& s, void* stream);struct KvStreamCounters {@@@ -87,6 -87,6 +93,6 @@@KvStreamCounters kv_stream_counters(const KvStreamMap& m);/// Bytes of one block (page) of K and V together.--uint64_t kv_block_bytes(const QsaShapes& s, bool int8);++uint64_t kv_block_bytes(const QsaShapes& s, int fmt);} // namespace strata::kernelsdiff --cc setup.pyindex a40aab526,66c81b7a1..0cafb35b8--- a/setup.py+++ b/setup.py@@@ -647,6 -647,6 +647,9 @@@ def main() -> intap.add_argument("--family", choices=list(FAMILIES), help="qwen = Qwen3.8-Flash-Next, swift = Swift 1.5")ap.add_argument("--model", choices=list(MODELS))ap.add_argument("--context", type=int)++ ap.add_argument("--kv", choices=["int8", "q4_0"],++ help="KV cache precision above 8K context: int8 (default) or q4_0 (half the memory, a little less "++ "precise)")ap.add_argument("--vision", choices=["yes", "no", "none", "gpu", "cpu"],help="let the model read images (yes = the encoder on the GPU)")ap.add_argument("--port", type=int, default=8080)@@@ -759,6 -752,6 +762,17 @@@"+ the context): using 128K")ctx = 131072ok(f"context: {ctx} tokens")++ # the KV cache (the model's memory of the conversation): 8-bit, or 4-bit after a Hadamard rotation (PR #21)++ kv = "fp16" if ctx <= 8192 else (a.kv or "int8")++ if ctx > 8192 and not a.kv and not a.yes:++ say()++ say(" KV cache precision (the model's memory of the conversation):")++ say(" 1) 8-bit (recommended: what every published number was measured with)")++ say(" 2) 4-bit half the memory (about 4% faster at 128K), but measurably less precise on long")++ say(" documents; long-context lookups (needle tests) still pass")++ kv = ["int8", "q4_0"][int(ask("KV cache?", ["1", "2"], "1", a.yes)) - 1]++ if ctx > 8192:++ ok(f"KV cache: {'8-bit' if kv == 'int8' else '4-bit (Hadamard-rotated)'}")if a.vision:vision = {"yes": "gpu", "no": "none"}.get(a.vision, a.vision)else:@@@ -869,11 -862,11 +883,11 @@@"--prefill", "2048", "--spec", "4", "--spec-min-p", "0.5", "--mtp", str(rt),"--max-context", str(ctx)]if ctx > 8192:-- args += ["--kv", "int8"]++ args += ["--kv", kv]# KV streaming: from 64K up the whole KV cache lives in RAM and only the part the attention reads (32K positions# per layer) stays in VRAM; the VRAM it frees holds more experts (+6% at 128K, +23% at 262K with Q2_0). It-- # costs ~13.7 KB of RAM per context token (1.7 GB at 128K, 3.4 GB at 262K), so only when that fits.-- kv_ram_gb = ctx * 13728 / 1e9++ # costs ~13.7 KB of RAM per context token with 8-bit KV (1.7 GB at 128K), 7.5 KB with 4-bit, so only when it fits.++ kv_ram_gb = ctx * (13 * (576 if kv == "q4_0" else 1056)) / 1e9 # 12 QSA layers + the draft layerif ctx >= 65536 and ram >= MODELS[model]["ram_gb"] + kv_ram_gb + 1:args += ["--kv-resident", "32768"]ok(f"KV streaming on: the context's KV cache lives in RAM ({kv_ram_gb:.1f} GB), more experts fit in VRAM")diff --cc src/core/layer.cppindex c39d195ba,4b223222b..b3c0bc545--- a/src/core/layer.cpp+++ b/src/core/layer.cpp@@@ -7,7 -7,8 +7,8 @@@#include "strata/kernels/elementwise.hpp"#include "strata/kernels/gdn.hpp"#include "strata/kernels/qsa.hpp"-#include "strata/kernels/kv_q8.hpp"+ #include "strata/kernels/kv_q4.hpp"+#include "strata/kernels/kv_q8.hpp"#include "strata/kernels/quantize_act.hpp"#include "strata/kernels/rope.hpp"#include "strata/kernels/router_top10.hpp"@@@ -170,9 -171,11 +171,11 @@@ if (!w.wants_q8k()) { s_gemv_q8_// namespacevoid layer_set_native_bf16(bool enabled) { native_bf16_projections = enabled; }void layer_set_native_flash_attn_short(bool enabled) { native_flash_attn_short = enabled; }- namespace { bool g_kv_int8 = false; }-namespace { bool g_kv_int8 = false; bool g_kv_q4 = false; }++namespace { bool g_kv_int8 = false, g_kv_q4 = false; }void qsa_set_kv_int8(bool enabled) { g_kv_int8 = enabled; }bool qsa_kv_int8() { return g_kv_int8; }+ void qsa_set_kv_q4(bool enabled) { g_kv_q4 = enabled; }+ bool qsa_kv_q4() { return g_kv_q4; }uint64_t gdn_buffers_bytes(const ModelGeometry& g) { const int64_t C = g.ssm_conv_channels; const int64_t V = g.ssm_value_dim; const uint64_t parts[] = { q8k_bytes(g.n_embd),// x_q8k(uint64_t) (g.n_embd / 32) * 34,@@@ -507,6 -510,9 +510,7 @@@ KvPlan kv_plan(const QsaShapes& s, int6return p;}uint64_t kv_pool_bytes(const QsaShapes& s, int64_t pages) {- if (g_kv_q4) {- return (uint64_t) pages * s.page_size * strata::kernels::kv_q4_bytes_per_cell(s) + 64;- }++ if (g_kv_q4) return (uint64_t) pages * s.page_size * strata::kernels::kv_q4_bytes_per_cell(s) + 64;return g_kv_int8 ? (uint64_t) pages * s.page_size * strata::kernels::kv_q8_bytes_per_cell(s) + 64: (uint64_t) pages * s.n_head_kv * s.page_size * s.head_dim * 2 * 2;}@@@ -540,11 -546,16 +544,16 @@@ uint64_t qsa_state_init(const ModelGeomconst KvPlan p = kv_plan(s, max_cells, ring_cells);const int64_t pages = p.pages;Cursor c{(uint8_t*) base};-- st.kv_int8 = g_kv_int8;++ st.kv_int8 = g_kv_int8 && !g_kv_q4;+ st.kv_q4 = g_kv_q4;st.kv_mode = p.mode;st.n_slots = p.slots;const uint64_t rows = (uint64_t) p.slots * s.n_head_kv * s.page_size; // VRAM rows: the slots- if (g_kv_int8) {- if (g_kv_q4) {- const uint64_t pool_bytes = (uint64_t) p.slots * s.n_head_kv * s.page_size * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim);- st.k_q4 = c.take_bytes(pool_bytes);- st.v_q4 = c.take_bytes(pool_bytes);++ const uint64_t q4_row = strata::kernels::kv_q4_bytes_per_head((int) s.head_dim);++ if (st.kv_q4) {++ st.k_q4 = c.take<uint8_t>(rows * q4_row);++ st.v_q4 = c.take<uint8_t>(rows * q4_row);+ } else if (g_kv_int8) {st.k_q = c.take<int8_t>(rows * s.head_dim);st.v_q = c.take<int8_t>(rows * s.head_dim);st.k_scale = c.take<uint16_t>(rows * (s.head_dim / strata::kernels::KV_Q8_GROUP));@@@ -595,7 -606,7 +604,7 @@@st.host = strata::kernels::KvHostPools{};if (p.mode != 0) {const uint64_t hrows = (uint64_t) pages * s.n_head_kv * s.page_size;-- const uint64_t bytes = (uint64_t) pages * strata::kernels::kv_block_bytes(s, g_kv_int8) + 4 * 256;++ const uint64_t bytes = (uint64_t) pages * strata::kernels::kv_block_bytes(s, qsa_kv_format(st)) + 4 * 256;uint8_t* h = nullptr;uint8_t* d = nullptr;if (cudaHostAlloc((void**) &h, bytes, cudaHostAllocMapped | cudaHostAllocPortable) != cudaSuccess ||@@@ -606,7 -617,7 +615,10 @@@}g_kv_host_bytes += bytes;Cursor hc{d};-- if (g_kv_int8) {++ if (st.kv_q4) {++ st.host.k_q4 = hc.take<uint8_t>(hrows * q4_row);++ st.host.v_q4 = hc.take<uint8_t>(hrows * q4_row);++ } else if (g_kv_int8) {st.host.k_q = hc.take<int8_t>(hrows * s.head_dim);st.host.v_q = hc.take<int8_t>(hrows * s.head_dim);st.host.k_scale = hc.take<uint16_t>(hrows * (s.head_dim / strata::kernels::KV_Q8_GROUP));@@@ -644,8 -655,12 +656,11 @@@void qsa_state_zero(const QsaState& st, const ModelGeometry& g, void* stream) {const QsaShapes s = qsa_shapes(g);cudaStream_t cs = (cudaStream_t) stream;+ const size_t rows = (size_t) st.n_slots * s.n_head_kv * s.page_size;- if (st.kv_int8) {+ if (st.kv_q4) {- const size_t pool_bytes = (size_t) st.n_slots * s.n_head_kv * s.page_size * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim);- cudaMemsetAsync(st.k_q4, 0, pool_bytes, cs);- cudaMemsetAsync(st.v_q4, 0, pool_bytes, cs);++ cudaMemsetAsync(st.k_q4, 0, rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), cs);++ cudaMemsetAsync(st.v_q4, 0, rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), cs);+ } else if (st.kv_int8) {- const size_t rows = (size_t) st.n_slots * s.n_head_kv * s.page_size;cudaMemsetAsync(st.k_q, 0, rows * s.head_dim, cs);cudaMemsetAsync(st.v_q, 0, rows * s.head_dim, cs);cudaMemsetAsync(st.k_scale, 0, rows * (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2, cs);@@@ -674,10 -691,9 +690,10 @@@ strata::kernels::QsaAttnPools qsa_attn_void qsa_kv_resolve(const QsaState& st, const ModelGeometry& g, const int32_t* ids, const int32_t* steps, int64_t n_q,int64_t cap, void* stream) {if (st.kv_mode != 1) return;-- strata::kernels::kv_stream_resolve(st.map, qsa_attn_pools(st), st.host, st.kv_int8, ids, steps, n_q, cap,++ strata::kernels::kv_stream_resolve(st.map, qsa_attn_pools(st), st.host, qsa_kv_format(st), ids, steps, n_q, cap,qsa_shapes(g), stream);}+uint64_t qsa_buffers_bytes(const ModelGeometry& g, int64_t max_cells) { const QsaShapes s = qsa_shapes(g); const int64_t cap = strata::kernels::qsa_selection_width(strata::kernels::kTopkMaxCells, s); uint64_t n = 0; n += (uint64_t) q8k_bytes(g.n_embd); n += (uint64_t) (g.n_embd / 32) * 34;// block_q8_0n += (uint64_t) g.n_embd * 2; n += (uint64_t) g.n_head * 2 * g.head_dim * 4; n += (uint64_t) g.n_head * g.head_dim * 4; n += (uint64_t) g.n_head_kv * g.head_dim * 4 * 2; n += (uint64_t) g.idx_key_dim * 4; n += (uint64_t) g.idx_q_heads * g.idx_key_dim * 4; n += (uint64_t) max_cells * 4; n += (uint64_t) cap * 4; n += (uint64_t) cap * g.n_head_kv * g.head_dim * 2 * 2; n += (uint64_t) g.n_head * g.head_dim * 4;@@@ -846,24 -862,51 +862,28 @@@ if (!gemv_quantized(*w_attnk, p_k, f_k// EVERY ENTRY POINT FROM HERE ON IS THE CAPTURABLE ONE: the per-token counts come from `st.step` and every// launch is sized from a capacity in `st`/`b`, so this sequence can be captured and replayed. The// host-scalar wrappers would be correct here today and silently wrong in a graph.- if (st.kv_int8) kv_append_q8_step(st.k_q, st.v_q, st.k_scale, st.v_scale, st.page_table, st.step, b.kcur, b.vcur, s, stream, &st.host); else kv_append_step(st.k_pool, st.v_pool, st.page_table, st.step, b.kcur, b.vcur, s, stream, &st.host); { const uint64_t nvk = (uint64_t) g.n_head_kv * g.head_dim; const uint64_t base = (uint64_t) 2 * g.n_embd + 2 * g.hc + (uint64_t) g.n_head * g.head_dim + 2 * nvk + 8; if (!st.kv_int8) dump_slot(dump, g, layer, (const float*) st.k_pool, base, nvk / 2, stream); if (!st.kv_int8) dump_slot(dump, g, layer, (const float*) st.v_pool, base + nvk / 2, nvk / 2, stream); dump_slot(dump, g, layer, b.vcur, base + nvk, nvk, stream); dump_slot(dump, g, layer, b.kcur, base + 2 * nvk, nvk, stream); } { const QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos}; if (native_qsa_indexer_enabled()) {+ if (st.kv_q4) {- // In-place Hadamard rotation for K and V prior to 4-bit quantization- fwht256_inplace_cuda(b.kcur, g.n_head_kv, stream);- fwht256_inplace_cuda(b.vcur, g.n_head_kv, stream);- kv_append_q4_step(st.k_q4, st.v_q4, st.page_table, st.step, b.kcur, b.vcur, s, stream);-} else if (st.kv_int8) {- kv_append_q8_step(st.k_q, st.v_q, st.k_scale, st.v_scale, st.page_table, st.step, b.kcur, b.vcur, s, stream, &st.host);-} else {- kv_append_step(st.k_pool, st.v_pool, st.page_table, st.step, b.kcur, b.vcur, s, stream, &st.host);-}-{- const uint64_t nvk = (uint64_t) g.n_head_kv * g.head_dim;- const uint64_t base = (uint64_t) 2 * g.n_embd + 2 * g.hc + (uint64_t) g.n_head * g.head_dim + 2 * nvk + 8;- if (!st.kv_int8 && !st.kv_q4) dump_slot(dump, g, layer, (const float*) st.k_pool, base, nvk / 2, stream);- if (!st.kv_int8 && !st.kv_q4) dump_slot(dump, g, layer, (const float*) st.v_pool, base + nvk / 2, nvk / 2, stream);- dump_slot(dump, g, layer, b.vcur, base + nvk, nvk, stream);- dump_slot(dump, g, layer, b.kcur, base + 2 * nvk, nvk, stream);-}-{- const QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos};- if (native_qsa_indexer_enabled()) {- try {- native_qsa_indexer_append(b.idx_raw, st.step + kStepPos, pos_base,- (const float*) w_ikn->data, RMS_EPS, ib, s, st.max_cells, (float) qsa_freq_base(), stream);- } catch (const std::exception& error) { err = v.name("native_indexer") + ": " + error.what(); return false; }- } else {- indexer_key_append(b.idx_raw, st.pos_dev, pos_base, (const float*) w_ikn->data, RMS_EPS, ib, s,- st.cos_tab, st.sin_tab, stream);- }-}++ strata::kernels::fwht256_inplace_cuda(b.kcur, g.n_head_kv, stream); // Q4_0: rotated K and V (kv_q4.hpp)++ strata::kernels::fwht256_inplace_cuda(b.vcur, g.n_head_kv, stream);++ strata::kernels::kv_append_q4_step(st.k_q4, st.v_q4, st.page_table, st.step, b.kcur, b.vcur, s, stream, &st.host);++} else if (st.kv_int8) kv_append_q8_step(st.k_q, st.v_q, st.k_scale, st.v_scale, st.page_table, st.step, b.kcur, b.vcur, s, stream, &st.host); else kv_append_step(st.k_pool, st.v_pool, st.page_table, st.step, b.kcur, b.vcur, s, stream, &st.host); { const uint64_t nvk = (uint64_t) g.n_head_kv * g.head_dim; const uint64_t base = (uint64_t) 2 * g.n_embd + 2 * g.hc + (uint64_t) g.n_head * g.head_dim + 2 * nvk + 8; if (!st.kv_int8) dump_slot(dump, g, layer, (const float*) st.k_pool, base, nvk / 2, stream); if (!st.kv_int8) dump_slot(dump, g, layer, (const float*) st.v_pool, base + nvk / 2, nvk / 2, stream); dump_slot(dump, g, layer, b.vcur, base + nvk, nvk, stream); dump_slot(dump, g, layer, b.kcur, base + 2 * nvk, nvk, stream); } { const QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos}; if (native_qsa_indexer_enabled()) {+ try {+ native_qsa_indexer_append(b.idx_raw, st.step + kStepPos, pos_base,+ (const float*) w_ikn->data, RMS_EPS, ib, s, st.max_cells, (float) qsa_freq_base(), stream);+ } catch (const std::exception& error) { err = v.name("native_indexer") + ": " + error.what(); return false; }+} else indexer_key_append(b.idx_raw, st.pos_dev, pos_base, (const float*) w_ikn->data, RMS_EPS, ib, s,+ st.cos_tab, st.sin_tab, stream); }// ---- 6. the query projection, and the HALF-SPLIT into q and gate.-if (!gemv_quantized(*w_attnq, p_q, f_q, b.x_q8_0, b.x_q8k, b.q_full, g.n_embd, g.n_head * 2 * g.head_dim,- v.name("attn_q.weight"), stream, err, x, w_attnv->native_data && w_attnq->native_data)) return false;--if (cudaMemcpy2DAsync(b.qcur, (size_t) g.head_dim * 4, b.q_full, (size_t) g.head_dim * 2 * 4,- (size_t) g.head_dim * 4, (size_t) g.n_head, cudaMemcpyDeviceToDevice,- (cudaStream_t) stream) != cudaSuccess) {- err = "qsa_layer: the q/gate split failed";- return false;-}-if (!normalize_rotate(b.qcur, w_qn, (int) g.n_head, (int) g.head_dim)) return false;-if (st.kv_q4) {- // In-place Hadamard rotation for Q so Q*K^T is invariant- fwht256_inplace_cuda(b.qcur, g.n_head, stream);-}+//+// **`attn_q` IS *NOT* ALWAYS Q2_0.** It is Q2_0 on TWO of the twelve QSA layers, Q3_K on six and IQ4_XS on+// four, and this line used to call `s2_gemv_q8` unconditionally - so TEN of the twelve layers decoded an+// S4 code plane with a Q8_0 activation. Both are "a quantized activation", both produce a plausible+// vector, and the difference is 0.6-1.4%.+if (!gemv_quantized(*w_attnq, p_q, f_q, b.x_q8_0, b.x_q8k, b.q_full, g.n_embd, g.n_head * 2 * g.head_dim, v.name("attn_q.weight"), stream, err, x, w_attnv->native_data && w_attnq->native_data)) return false;+// `per_head[:, :head_dim]` - the FIRST half of each head's 2*head_dim block, copied out contiguously so+// the norm and the rotation see whole rows. A 2-D copy is a memcpy node, which captures (`pinned_capture`+// case A) and needs no kernel.+if (cudaMemcpy2DAsync(b.qcur, (size_t) g.head_dim * 4, b.q_full, (size_t) g.head_dim * 2 * 4, (size_t) g.head_dim * 4, (size_t) g.n_head, cudaMemcpyDeviceToDevice, (cudaStream_t) stream) != cudaSuccess) { err = "qsa_layer: the q/gate split failed"; return false; } if (!normalize_rotate(b.qcur, w_qn, (int) g.n_head, (int) g.head_dim)) return false;// ---- 7. the indexer's query: BF16, then norm and rotateproject_bf16(x, b.x_bf16, (const uint16_t*) w_idxq->data, b.q_idx, g.n_embd, g.idx_q_heads * g.idx_key_dim, false, stream);if (!normalize_rotate(b.q_idx, w_iqn, (int) g.idx_q_heads, (int) g.idx_key_dim)) return false;@@@ -880,28 -954,40 +900,28 @@@ int64_t max_blocks = (st.max_cells / s.}// KV streaming: every block the selection names is made resident before anything reads itqsa_kv_resolve(st, g, b.ids, st.step, 1, cap, stream);++ if (st.kv_q4) strata::kernels::fwht256_inplace_cuda(b.qcur, g.n_head, stream); // <Hq, Hk> = <q, k>if (g_fast_attn && !native_flash_attn_short && dump == nullptr) {-- strata::kernels::QsaAttnPools pools;-- pools.k_pool = st.k_pool; pools.v_pool = st.v_pool; pools.k_q = st.k_q; pools.v_q = st.v_q;- pools.k_q4 = st.k_q4; pools.v_q4 = st.v_q4;-- pools.k_scale = st.k_scale; pools.v_scale = st.v_scale; pools.page_table = st.page_table;-- if (!st.kv_int8) { pools.k_q = nullptr; pools.v_q = nullptr; }- if (!st.kv_q4) { pools.k_q4 = nullptr; pools.v_q4 = nullptr; }++ const strata::kernels::QsaAttnPools pools = qsa_attn_pools(st);strata::kernels::qsa_decode_attn_step(b.qcur, pools, b.ids, st.step, cap, s, b.attn_scratch, b.attn, stream);} else {- if (st.kv_int8) kv_gather_q8_step(st.k_q, st.v_q, st.k_scale, st.v_scale, st.page_table, b.ids, st.step, cap, s, b.k_scratch, b.v_scratch, stream); else kv_gather_step(st.k_pool, st.v_pool, st.page_table, b.ids, st.step, cap, s, b.k_scratch, b.v_scratch, stream); if (native_flash_attn_short) {- if (st.kv_q4) kv_gather_q4_step(st.k_q4, st.v_q4, st.page_table, b.ids, st.step, cap, s, b.k_scratch, b.v_scratch, stream);- else if (st.kv_int8) kv_gather_q8_step(st.k_q, st.v_q, st.k_scale, st.v_scale, st.page_table, b.ids, st.step, cap, s, b.k_scratch, b.v_scratch, stream);- else kv_gather_step(st.k_pool, st.v_pool, st.page_table, b.ids, st.step, cap, s, b.k_scratch, b.v_scratch, stream);- if (native_flash_attn_short) {- if (st.max_cells < 1 || st.max_cells > 256 || !st.attention_status || !st.host_step) {- err = v.name("native_flash_attn") + ": short adapter requires context <=256 and persistent status storage";- return false;- }- try {- native_flash_attn_short_step(b.qcur, b.k_scratch, b.v_scratch, st.step, cap,- (int) st.max_cells, s, b.attn, st.attention_status, nullptr, stream);- } catch (const std::exception& error) { err = v.name("native_flash_attn") + ": " + error.what(); return false; }- if (cudaMemcpyAsync(st.host_step + kStepCount, st.attention_status, sizeof(int32_t),- cudaMemcpyDeviceToHost, (cudaStream_t) stream) != cudaSuccess) {- err = v.name("native_flash_attn") + ": status readback failed"; return false;- }- } else {- qsa_attend_step(b.qcur, b.k_scratch, b.v_scratch, st.step, cap, s, b.attn, nullptr, stream);- }++ if (st.kv_q4) strata::kernels::kv_gather_q4_step(st.k_q4, st.v_q4, st.page_table, b.ids, st.step, cap, s, b.k_scratch, b.v_scratch, stream);++ else if (st.kv_int8) kv_gather_q8_step(st.k_q, st.v_q, st.k_scale, st.v_scale, st.page_table, b.ids, st.step, cap, s, b.k_scratch, b.v_scratch, stream); else kv_gather_step(st.k_pool, st.v_pool, st.page_table, b.ids, st.step, cap, s, b.k_scratch, b.v_scratch, stream); if (native_flash_attn_short) {+ if (st.max_cells < 1 || st.max_cells > 256 || !st.attention_status || !st.host_step) {+ err = v.name("native_flash_attn") + ": short adapter requires context <=256 and persistent status storage";+ return false;}- if (st.kv_q4) {- // Un-rotate attention output- fwht256_inplace_cuda(b.attn, g.n_head, stream);+ try {+ native_flash_attn_short_step(b.qcur, b.k_scratch, b.v_scratch, st.step, cap,+ (int) st.max_cells, s, b.attn, st.attention_status, nullptr, stream);+ } catch (const std::exception& error) { err = v.name("native_flash_attn") + ": " + error.what(); return false; }+ if (cudaMemcpyAsync(st.host_step + kStepCount, st.attention_status, sizeof(int32_t),+ cudaMemcpyDeviceToHost, (cudaStream_t) stream) != cudaSuccess) {+ err = v.name("native_flash_attn") + ": status readback failed"; return false;}-}+} else qsa_attend_step(b.qcur, b.k_scratch, b.v_scratch, st.step, cap, s, b.attn, nullptr, stream);+ }++ if (st.kv_q4) strata::kernels::fwht256_inplace_cuda(b.attn, g.n_head, stream); // the output back: H is self-inversedump_slot(dump, g, layer, b.attn, (uint64_t) 2 * g.n_embd + 2 * g.hc, (uint64_t) g.n_head * g.head_dim, stream); { const uint64_t vs = (uint64_t) 2 * g.n_embd + 2 * g.hc + (uint64_t) g.n_head * g.head_dim + (uint64_t) 2 * g.n_head_kv * g.head_dim; dump_slot(dump, g, layer, (const float*) b.v_scratch, vs, (uint64_t) g.n_head_kv * g.head_dim / 2, stream); dump_slot(dump, g, layer, (const float*) b.ids, vs + (uint64_t) g.n_head_kv * g.head_dim / 2, 4, stream); dump_slot(dump, g, layer, (const float*) st.step, vs + (uint64_t) g.n_head_kv * g.head_dim / 2 + 4, 4, stream); }// ---- 9. Gate the attention output before its projection. Native CUDA keeps F32// sigmoid/multiply arithmetic and uses Q8_1 for the native quantized projection.diff --cc src/core/mtp.cppindex 3c7fce68c,a353fcbaa..891f9b909--- a/src/core/mtp.cpp+++ b/src/core/mtp.cpp@@@ -7,7 -7,8 +7,8 @@@#include "strata/kernels/elementwise.hpp"#include "strata/kernels/fused_gr.hpp"#include "strata/kernels/gr.hpp"-#include "strata/kernels/kv_q8.hpp"+ #include "strata/kernels/kv_q4.hpp"+#include "strata/kernels/kv_q8.hpp"#include "strata/kernels/native_moe.hpp"#include "strata/kernels/native_mmvq.hpp"#include "strata/kernels/native_qsa.hpp"@@@ -338,7 -339,12 +339,12 @@@ bool MtpDrafter::record_forward(int T,native_mmvq(GGML_Q8_0, q8("self_attn.v_proj.weight"), xq_, vcur_, (int) N, (int) (NKV * HD), T, cs);for (int t = 0; t < T; ++t) {norm_rope(kcur_ + t * NKV * HD, f32("self_attn.k_norm.weight"), (int) NKV, (int) HD, pos + t * NH);- if (st_.kv_int8)- if (st_.kv_q4) {++ if (st_.kv_q4) { // Q4_0 KV (kv_q4.hpp): rotated K and V+ fwht256_inplace_cuda(kcur_ + t * NKV * HD, NKV, cs);+ fwht256_inplace_cuda(vcur_ + t * NKV * HD, NKV, cs);- kv_append_q4_step(st_.k_q4, st_.v_q4, st_.page_table, step + t * 4,- kcur_ + t * NKV * HD, vcur_ + t * NKV * HD, s, cs);++ kv_append_q4_step(st_.k_q4, st_.v_q4, st_.page_table, step + t * 4, kcur_ + t * NKV * HD,++ vcur_ + t * NKV * HD, s, cs, &st_.host);+ } else if (st_.kv_int8)kv_append_q8_step(st_.k_q, st_.v_q, st_.k_scale, st_.v_scale, st_.page_table, step + t * 4,kcur_ + t * NKV * HD, vcur_ + t * NKV * HD, s, cs, &st_.host);else@@@ -355,10 -361,18 +361,12 @@@return false;}norm_rope(qc, f32("self_attn.q_norm.weight"), (int) NH, (int) HD, pos + t * NH);- if (st_.kv_q4) {- fwht256_inplace_cuda(qc, NH, cs);- }++ if (st_.kv_q4) fwht256_inplace_cuda(qc, NH, cs);}const QsaAttnPools pools = qsa_attn_pools(st_);if (window_ > 0) window_ids(const_cast<int32_t*>(step), T, (int) window_, ident_, cap_, cs);qsa_decode_attn_batch(qcur_, pools, ident_, step, cap_, s, attn_scratch_, attn_, T, cs);- if (st_.kv_q4) {- for (int t = 0; t < T; ++t) {- fwht256_inplace_cuda(attn_ + t * NH * HD, NH, cs);- }- }++ if (st_.kv_q4) fwht256_inplace_cuda(attn_, (int64_t) T * NH, cs);for (int t = 0; t < T; ++t)native_qsa_gate_apply(attn_ + t * NH * HD, qfull_ + t * NH * 2 * HD, attn32_ + t * NH * HD, (int) NH, (int) HD, cs);native_quantize_q8_1(attn32_, xq_, (int) (NH * HD), T, cs);@@@ -507,7 -521,7 +515,7 @@@ void MtpDrafter::kv_restore(int64_t upt// the ring's blocks below `upto`, from the host copy: a checkpoint resume may have left later cells in themconst strata::kernels::QsaShapes s = shapes_of(*g_);const int64_t b1 = (upto + s.page_size - 1) / s.page_size, b0 = std::max<int64_t>(0, b1 - st_.n_slots);-- strata::kernels::kv_ring_restore(qsa_attn_pools(st_), st_.host, st_.kv_int8, b0, b1, st_.n_slots, s, cs_);++ strata::kernels::kv_ring_restore(qsa_attn_pools(st_), st_.host, qsa_kv_format(st_), b0, b1, st_.n_slots, s, cs_);cudaStreamSynchronize(cs_);}diff --cc src/core/verify.cppindex 70b089b77,ab988d746..fd5c8d2fb--- a/src/core/verify.cpp+++ b/src/core/verify.cpp@@@ -12,7 -12,8 +12,8 @@@#include "strata/kernels/elementwise.hpp"#include "strata/kernels/fused_gr.hpp"#include "strata/kernels/gr.hpp"-#include "strata/kernels/kv_q8.hpp"+ #include "strata/kernels/kv_q4.hpp"+#include "strata/kernels/kv_q8.hpp"#include "strata/kernels/native_mmvq.hpp"#include "strata/kernels/native_qsa.hpp"#include "strata/kernels/native_qsa_indexer.hpp"@@@ -421,10 -420,19 +422,17 @@@ bool Verifier::record_window(int T, cudnative_mmvq(wk->native_type, wk->native_data, xq_, kcur_ + tb * NKV * HD, (int) N, (int) (NKV * HD), n, cs);native_mmvq(wv->native_type, wv->native_data, xq_, vcur_ + tb * NKV * HD, (int) N, (int) (NKV * HD), n, cs);for (int t = tb; t < te; ++t) norm_rope(kcur_ + t * NKV * HD, wkn, (int) NKV, (int) HD, pos_ + t * NH);- if (st.kv_q4) {- for (int t = tb; t < te; ++t) {- fwht256_inplace_cuda(kcur_ + t * NKV * HD, NKV, cs);- fwht256_inplace_cuda(vcur_ + t * NKV * HD, NKV, cs);- }++ if (st.kv_q4) { // Q4_0 KV (kv_q4.hpp): K and V rotated before they are stored++ fwht256_inplace_cuda(kcur_ + tb * NKV * HD, (int64_t) n * NKV, cs);++ fwht256_inplace_cuda(vcur_ + tb * NKV * HD, (int64_t) n * NKV, cs);+ }if (grp == 0) copy_from_mapped(tail_snap_ + (size_t) qi * TS, st.idx_tail, TS, cs);for (int t = tb; t < te; ++t) {const int32_t* step_t = step_ + t * kStepCount;- if (st.kv_int8)+ if (st.kv_q4)- kv_append_q4_step(st.k_q4, st.v_q4, st.page_table, step_t,- kcur_ + t * NKV * HD, vcur_ + t * NKV * HD, s, cs);++ kv_append_q4_step(st.k_q4, st.v_q4, st.page_table, step_t, kcur_ + t * NKV * HD,++ vcur_ + t * NKV * HD, s, cs, &st.host);+ else if (st.kv_int8)kv_append_q8_step(st.k_q, st.v_q, st.k_scale, st.v_scale, st.page_table, step_t,kcur_ + t * NKV * HD, vcur_ + t * NKV * HD, s, cs, &st.host);else@@@ -446,6 -454,9 +454,7 @@@return false;}norm_rope(qc, wqn, (int) NH, (int) HD, pos_ + t * NH);- if (st.kv_q4) {- fwht256_inplace_cuda(qc, NH, cs);- }++ if (st.kv_q4) fwht256_inplace_cuda(qc, NH, cs); // <Hq, Hk> = <q, k>}for (int t = tb; t < te; ++t) {float* qx = qidx_ + t * IQ * ID;@@@ -461,6 -472,11 +470,7 @@@const QsaAttnPools pools = qsa_attn_pools(st);qsa_decode_attn_batch(qcur_ + tb * NH * HD, pools, sel_ + (size_t) tb * cap_, step_ + tb * kStepCount, cap_,s, attn_scratch_ + (size_t) tb * attn_scratch_floats_, attn_ + tb * NH * HD, n, cs);- if (st.kv_q4) {- for (int t = tb; t < te; ++t) {- fwht256_inplace_cuda(attn_ + t * NH * HD, NH, cs);- }- }++ if (st.kv_q4) fwht256_inplace_cuda(attn_ + tb * NH * HD, (int64_t) n * NH, cs); // back: H^-1 = Hfor (int t = tb; t < te; ++t) {if (native_qsa_enabled())native_qsa_gate_apply(attn_ + t * NH * HD, qfull_ + t * NH * 2 * HD, attn32_ + t * NH * HD,diff --cc src/kernels/cuda/kv_q4.cuindex 000000000,92bfe05f4..b7de61fadmode 000000,100644..100644--- a/src/kernels/cuda/kv_q4.cu+++ b/src/kernels/cuda/kv_q4.cu@@@ -1,0 -1,268 +1,231 @@@-// src/kernels/cuda/kv_q4.cu - Q4_0 KV storage with Fast Walsh-Hadamard Transform++// src/kernels/cuda/kv_q4.cu - see include/strata/kernels/kv_q4.hpp. Q4_0 KV with Walsh-Hadamard rotation++// (from PR #21 by code-martin; KV-streaming integration and the deterministic group maximum added on merge).+ #include "strata/kernels/kv_q4.hpp"+ #include "strata/kernels/f16_bits.hpp"++#include "strata/kernels/kv_stream.hpp"++ #include <cuda_fp16.h>+ #include <cuda_runtime.h>+ #include <cstdio>+ #include <cstdlib>++ namespace strata::kernels {+ namespace {++ void check(const char* what) {+ const cudaError_t e = cudaGetLastError();+ if (e != cudaSuccess) {+ std::fprintf(stderr, "kv_q4: %s: %s\n", what, cudaGetErrorString(e));+ std::exit(1);+ }+ }+-// Fast Walsh-Hadamard Transform for N = 256-// 1 warp of 32 threads computes FWHT on 256 floats in registers-// Scale = 1 / sqrt(256) = 1/16 = 0.0625f++// Fast Walsh-Hadamard Transform for N = 256: one warp per row, 8 values per lane in registers.++// Orthonormal (scale 1/sqrt(256) = 1/16), so it is its own inverse.+ __global__ void fwht256_kernel(const float* __restrict__ src, float* __restrict__ dst, int64_t n_rows, float scale) {+ constexpr int warp_size = 32;+ constexpr int N = 256;- constexpr int el_w = N / warp_size; // 8++ constexpr int el_w = N / warp_size; // 8++ const int64_t r = (int64_t) blockIdx.x * blockDim.y + threadIdx.y;+ if (r >= n_rows) return;++ const float* row_src = src + r * N;+ float* row_dst = dst + r * N;++ float reg[el_w];+ const int lane = threadIdx.x;++ #pragma unroll- for (int i = 0; i < el_w; ++i) {- reg[i] = row_src[i * warp_size + lane] * scale;- }++ for (int i = 0; i < el_w; ++i) reg[i] = row_src[i * warp_size + lane] * scale;+++ // the low 5 index bits live across lanes+ #pragma unroll+ for (int h = 1; h < warp_size; h *= 2) {+ #pragma unroll+ for (int j = 0; j < el_w; ++j) {+ const float val = reg[j];+ const float val2 = __shfl_xor_sync(0xffffffffu, val, h, warp_size);+ reg[j] = (lane & h) == 0 ? val + val2 : val2 - val;+ }+ }-++ // the high 3 bits across each lane's registers+ #pragma unroll+ for (int h = warp_size; h < N; h *= 2) {+ const int step = h / warp_size;+ #pragma unroll+ for (int j = 0; j < el_w; j += 2 * step) {+ #pragma unroll+ for (int k = 0; k < step; ++k) {+ const float x = reg[j + k];+ const float y = reg[j + k + step];- reg[j + k] = x + y;++ reg[j + k] = x + y;+ reg[j + k + step] = x - y;+ }+ }+ }++#pragma unroll++ for (int i = 0; i < el_w; ++i) row_dst[i * warp_size + lane] = reg[i];++}+++// One 32-value group in one warp (lane = element), ggml's q4_0: d = (the value of largest |x|) / -8,++// q = clamp(trunc(x / d + 8.5), 0, 15). Returns the scale bits; `byte` is lane t's packed byte for t < 16++// (element t in the low nibble, t + 16 in the high one). Ties in |x| resolve to the larger value in EVERY lane,++// so all lanes agree on d (a plain `a > amax` could leave lanes with opposite signs and one block two scales).++__device__ __forceinline__ uint16_t q4_group(float x, int lane, uint8_t& byte) {++ float amax = fabsf(x), mval = x;+ #pragma unroll- for (int i = 0; i < el_w; ++i) {- row_dst[i * warp_size + lane] = reg[i];++ for (int o = 16; o > 0; o >>= 1) {++ const float a = __shfl_xor_sync(0xffffffffu, amax, o);++ const float v = __shfl_xor_sync(0xffffffffu, mval, o);++ if (a > amax || (a == amax && v > mval)) { amax = a; mval = v; }+ }++ const float d = mval / -8.0f;++ const float id = d != 0.0f ? 1.0f / d : 0.0f;++ int q = __float2int_rz(x * id + 8.5f);++ const uint8_t qc = (uint8_t) (q < 0 ? 0 : (q > 15 ? 15 : q));++ const uint8_t qhi = __shfl_down_sync(0xffffffffu, qc, 16);++ byte = (uint8_t) (qc | (qhi << 4));++ (void) lane;++ return f16_from_f32(d);++}++++__device__ __forceinline__ void q4_store(uint8_t* pool, long long row, int b, int lane, uint16_t d, uint8_t byte) {++ block_q4_0* blk = reinterpret_cast<block_q4_0*>(pool + row * (long long) sizeof(block_q4_0) * 8) + b;++ if (lane == 0) blk->d = d;++ if (lane < 16) blk->qs[lane] = byte;+ }+-// 1 block = 1 32-value group of one KV head of K (blockIdx.z == 0) or V (1); 32 threads, 1 value each++// One block = one 32-value group of one KV head of K (blockIdx.z = 0) or V (1); 32 threads. KV streaming: the VRAM++// page only if the block is resident (table >= 0), the host copy always (identity layout) when there is one.+ __global__ void kv_append_q4_kernel(uint8_t* __restrict__ k_q4, uint8_t* __restrict__ v_q4,+ const int32_t* __restrict__ table, const int32_t* __restrict__ step,+ const float* __restrict__ kcur, const float* __restrict__ vcur,- int kv_heads, int head_dim, int page_size) {++ int kv_heads, int head_dim, int page_size, KvHostPools host) {+ const long long pos = (long long) __ldg(step + kStepPos);+ const int h = blockIdx.x, b = blockIdx.y, t = threadIdx.x;+ const bool is_v = blockIdx.z == 1;- const int blocks_per_head = head_dim / QK4_0; // 8 for 256- const int bytes_per_head = blocks_per_head * sizeof(block_q4_0); // 144+ const float x = (is_v ? vcur : kcur)[h * head_dim + b * QK4_0 + t];-- float amax = fabsf(x);- float max_val = x;-#pragma unroll- for (int o = 16; o > 0; o >>= 1) {- const float a = __shfl_xor_sync(0xffffffffu, amax, o);- const float v = __shfl_xor_sync(0xffffffffu, max_val, o);- if (a > amax) {- amax = a;- max_val = v;- }- }-- const float d = max_val / -8.0f;- const float id = d != 0.0f ? 1.0f / d : 0.0f;- const uint16_t d_f16 = f16_from_f32(d);-- const float x_scaled = x * id;- int q = __float2int_rz(x_scaled + 8.5f);- uint8_t q_clamped = (uint8_t) (q < 0 ? 0 : (q > 15 ? 15 : q));-- const uint8_t q_high = __shfl_down_sync(0xffffffffu, q_clamped, 16);-++ uint8_t byte;++ const uint16_t d = q4_group(x, t, byte);+ const long long page = (long long) table[pos / page_size];- const long long row = (page * kv_heads + h) * page_size + (pos % page_size);- uint8_t* base = (is_v ? v_q4 : k_q4) + row * bytes_per_head;- block_q4_0* blk = reinterpret_cast<block_q4_0*>(base) + b;++ if (page >= 0) q4_store(is_v ? v_q4 : k_q4, (page * kv_heads + h) * page_size + (pos % page_size), b, t, d, byte);++ if (host.k_q4 != nullptr)++ q4_store(is_v ? host.v_q4 : host.k_q4, ((pos / page_size) * kv_heads + h) * page_size + (pos % page_size), b, t,++ d, byte);++}+- if (t == 0) {- blk->d = d_f16;- }- if (t < 16) {- blk->qs[t] = q_clamped | (q_high << 4);- }++// The prompt path: grid (T, kv_heads, groups), K then V; also into the staging pool (identity layout) when given.++__global__ void kv_append_q4_batch_kernel(uint8_t* __restrict__ k_q4, uint8_t* __restrict__ v_q4,++ const int32_t* __restrict__ table, int64_t pos0,++ const float* __restrict__ K, const float* __restrict__ V,++ int kv_heads, int head_dim, int page_size, int is_v_grid, KvHostPools host,++ KvHostPools stage) {++ const long long t = blockIdx.x;++ const long long pos = pos0 + t;++ const int h = blockIdx.y, b = blockIdx.z, th = threadIdx.x;++ const bool is_v = is_v_grid != 0;++ const float x = (is_v ? V : K)[t * (kv_heads * head_dim) + h * head_dim + b * QK4_0 + th];++ uint8_t byte;++ const uint16_t d = q4_group(x, th, byte);++ const long long page = (long long) table[pos / page_size];++ const long long row_id = ((pos / page_size) * kv_heads + h) * page_size + (pos % page_size);++ if (page >= 0) q4_store(is_v ? v_q4 : k_q4, (page * kv_heads + h) * page_size + (pos % page_size), b, th, d, byte);++ if (host.k_q4 != nullptr) q4_store(is_v ? host.v_q4 : host.k_q4, row_id, b, th, d, byte);++ if (stage.k_q4 != nullptr) q4_store(is_v ? stage.v_q4 : stage.k_q4, row_id, b, th, d, byte);+ }+-// Gather step[kStepWidth] cells into FP16 scratch++// Gather step[kStepWidth] cells into FP16 scratch (the non-fused attention paths)+ __global__ void kv_gather_q4_kernel(const uint8_t* __restrict__ k_q4, const uint8_t* __restrict__ v_q4,+ const int32_t* __restrict__ table, const int32_t* __restrict__ ids,+ const int32_t* __restrict__ step, int kv_heads, int head_dim, int page_size,+ uint16_t* __restrict__ k_scratch, uint16_t* __restrict__ v_scratch) {+ const long long n_ids = (long long) __ldg(step + kStepWidth);- const int blocks_per_head = head_dim / QK4_0; // 8- const int bytes_per_head = blocks_per_head * sizeof(block_q4_0); // 144++ const int blocks_per_head = head_dim / QK4_0; // 8++ const int bytes_per_head = blocks_per_head * sizeof(block_q4_0); // 144+ const long long total_blocks = n_ids * kv_heads * blocks_per_head;++ const long long blk_idx = (long long) blockIdx.x * blockDim.y + threadIdx.y;+ if (blk_idx >= total_blocks) return;+- const int t = threadIdx.x; // 0..31 inside block++ const int t = threadIdx.x;+ const long long id = blk_idx / (kv_heads * blocks_per_head);+ const int rem = (int) (blk_idx % (kv_heads * blocks_per_head));+ const int h = rem / blocks_per_head;+ const int b = rem % blocks_per_head;++ const int cell = ids[id];+ const long long page = (long long) table[cell / page_size];+ const long long row = (page * kv_heads + h) * page_size + (cell % page_size);++ const block_q4_0* k_blk = reinterpret_cast<const block_q4_0*>(k_q4 + row * bytes_per_head) + b;+ const block_q4_0* v_blk = reinterpret_cast<const block_q4_0*>(v_q4 + row * bytes_per_head) + b;-+ const float kd = f32_from_f16(k_blk->d);+ const float vd = f32_from_f16(v_blk->d);-+ const int j = t < 16 ? t : (t - 16);+ const uint8_t k_byte = k_blk->qs[j];+ const uint8_t v_byte = v_blk->qs[j];-+ const int kq = (t < 16) ? ((k_byte & 0x0F) - 8) : ((k_byte >> 4) - 8);+ const int vq = (t < 16) ? ((v_byte & 0x0F) - 8) : ((v_byte >> 4) - 8);-+ const long long dst_offset = ((id * kv_heads + h) * head_dim) + (b * QK4_0 + t);+ k_scratch[dst_offset] = f16_from_f32((float) kq * kd);+ v_scratch[dst_offset] = f16_from_f32((float) vq * vd);+ }+++void need_256(const QsaShapes& s, const char* what) {++ if (s.head_dim != 256) {++ std::fprintf(stderr, "%s: head_dim must be 256 (the Hadamard transform's size)\n", what);++ std::exit(1);++ }++}+++ } // namespace++ void fwht256_cuda(const float* src, float* dst, int64_t n_rows, void* stream) {+ if (n_rows <= 0) return;+ const int rows_per_block = 4;+ const int64_t num_blocks = (n_rows + rows_per_block - 1) / rows_per_block;- dim3 grid((unsigned) num_blocks);- dim3 block(32, rows_per_block);- const float scale = 1.0f / 16.0f; // 1 / sqrt(256)- fwht256_kernel<<<grid, block, 0, (cudaStream_t) stream>>>(src, dst, n_rows, scale);++ fwht256_kernel<<<dim3((unsigned) num_blocks), dim3(32, rows_per_block), 0, (cudaStream_t) stream>>>(++ src, dst, n_rows, 1.0f / 16.0f);+ check("fwht256 launch");+ }+-// Batched append for prefill: grid = dim3(T, kv_heads, blocks_per_head), block = 32-__global__ void kv_append_q4_batch_kernel(uint8_t* __restrict__ k_q4, uint8_t* __restrict__ v_q4,- const int32_t* __restrict__ table, int64_t pos0,- const float* __restrict__ K, const float* __restrict__ V,- int kv_heads, int head_dim, int page_size, int is_v_grid) {- const long long t = blockIdx.x;- const long long pos = pos0 + t;- const int h = blockIdx.y, b = blockIdx.z, th = threadIdx.x;- const bool is_v = is_v_grid != 0;- const int blocks_per_head = head_dim / QK4_0; // 8 for 256- const int bytes_per_head = blocks_per_head * sizeof(block_q4_0); // 144- const float x = (is_v ? V : K)[t * (kv_heads * head_dim) + h * head_dim + b * QK4_0 + th];-- float amax = fabsf(x);- float max_val = x;-#pragma unroll- for (int o = 16; o > 0; o >>= 1) {- const float a = __shfl_xor_sync(0xffffffffu, amax, o);- const float v = __shfl_xor_sync(0xffffffffu, max_val, o);- if (a > amax) {- amax = a;- max_val = v;- }- }-- const float d = max_val / -8.0f;- const float id = d != 0.0f ? 1.0f / d : 0.0f;- const uint16_t d_f16 = f16_from_f32(d);-- const float x_scaled = x * id;- int q = __float2int_rz(x_scaled + 8.5f);- uint8_t q_clamped = (uint8_t) (q < 0 ? 0 : (q > 15 ? 15 : q));-- const uint8_t q_high = __shfl_down_sync(0xffffffffu, q_clamped, 16);-- const long long page = (long long) table[pos / page_size];- const long long row = (page * kv_heads + h) * page_size + (pos % page_size);- uint8_t* base = (is_v ? v_q4 : k_q4) + row * bytes_per_head;- block_q4_0* blk = reinterpret_cast<block_q4_0*>(base) + b;-- if (th == 0) {- blk->d = d_f16;- }- if (th < 16) {- blk->qs[th] = q_clamped | (q_high << 4);- }-}--void kv_append_q4_step(uint8_t* k_q4, uint8_t* v_q4, const int32_t* page_table,- const int32_t* step, const float* kcur, const float* vcur,- const QsaShapes& s, void* stream) {- if (s.head_dim != 256) {- std::fprintf(stderr, "kv_append_q4: head_dim must be 256\n");- std::exit(1);- }++void kv_append_q4_step(uint8_t* k_q4, uint8_t* v_q4, const int32_t* page_table, const int32_t* step,++ const float* kcur, const float* vcur, const QsaShapes& s, void* stream,++ const KvHostPools* host) {++ need_256(s, "kv_append_q4");+ const dim3 grid((unsigned) s.n_head_kv, (unsigned) (s.head_dim / QK4_0), 2);+ kv_append_q4_kernel<<<grid, 32, 0, (cudaStream_t) stream>>>(- k_q4, v_q4, page_table, step, kcur, vcur, (int) s.n_head_kv, (int) s.head_dim, (int) s.page_size);++ k_q4, v_q4, page_table, step, kcur, vcur, (int) s.n_head_kv, (int) s.head_dim, (int) s.page_size,++ host ? *host : KvHostPools{});+ check("kv_append_q4 launch");+ }+-void kv_append_q4(uint8_t* k_q4, uint8_t* v_q4, const int32_t* page_table, int64_t pos0, int64_t T,- const float* K, const float* V, const QsaShapes& s, void* stream) {++void kv_append_q4(uint8_t* k_q4, uint8_t* v_q4, const int32_t* page_table, int64_t pos0, int64_t T, const float* K,++ const float* V, const QsaShapes& s, void* stream, const KvHostPools* host, const KvHostPools* stage) {+ if (T <= 0) return;- if (s.head_dim != 256) {- std::fprintf(stderr, "kv_append_q4: head_dim must be 256\n");- std::exit(1);- }++ need_256(s, "kv_append_q4");+ const dim3 grid((unsigned) T, (unsigned) s.n_head_kv, (unsigned) (s.head_dim / QK4_0));+ cudaStream_t cs = (cudaStream_t) stream;- kv_append_q4_batch_kernel<<<grid, 32, 0, cs>>>(- k_q4, v_q4, page_table, pos0, K, V, (int) s.n_head_kv, (int) s.head_dim, (int) s.page_size, 0);- kv_append_q4_batch_kernel<<<grid, 32, 0, cs>>>(- k_q4, v_q4, page_table, pos0, K, V, (int) s.n_head_kv, (int) s.head_dim, (int) s.page_size, 1);++ const KvHostPools h = host ? *host : KvHostPools{}, st = stage ? *stage : KvHostPools{};++ for (int is_v = 0; is_v < 2; ++is_v)++ kv_append_q4_batch_kernel<<<grid, 32, 0, cs>>>(k_q4, v_q4, page_table, pos0, K, V, (int) s.n_head_kv,++ (int) s.head_dim, (int) s.page_size, is_v, h, st);+ check("kv_append_q4 batch launch");+ }+-void kv_gather_q4_step(const uint8_t* k_q4, const uint8_t* v_q4,- const int32_t* page_table, const int32_t* ids, const int32_t* step, int64_t max_ids,- const QsaShapes& s, uint16_t* k_scratch, uint16_t* v_scratch, void* stream) {++void kv_gather_q4_step(const uint8_t* k_q4, const uint8_t* v_q4, const int32_t* page_table, const int32_t* ids,++ const int32_t* step, int64_t max_ids, const QsaShapes& s, uint16_t* k_scratch,++ uint16_t* v_scratch, void* stream) {+ if (max_ids <= 0) return;+ const int blocks_per_head = (int) (s.head_dim / QK4_0);+ const int64_t total_blocks = max_ids * s.n_head_kv * blocks_per_head;+ const int rows_per_block = 4;+ const unsigned num_blocks = (unsigned) ((total_blocks + rows_per_block - 1) / rows_per_block);- dim3 grid(num_blocks);- dim3 block(32, rows_per_block);- kv_gather_q4_kernel<<<grid, block, 0, (cudaStream_t) stream>>>(- k_q4, v_q4, page_table, ids, step, (int) s.n_head_kv, (int) s.head_dim, (int) s.page_size,- k_scratch, v_scratch);++ kv_gather_q4_kernel<<<dim3(num_blocks), dim3(32, rows_per_block), 0, (cudaStream_t) stream>>>(++ k_q4, v_q4, page_table, ids, step, (int) s.n_head_kv, (int) s.head_dim, (int) s.page_size, k_scratch,++ v_scratch);+ check("kv_gather_q4 launch");+ }++ } // namespace strata::kernelsdiff --cc src/kernels/cuda/kv_stream.cuindex d19728c18,d19728c18..5787001f2--- a/src/kernels/cuda/kv_stream.cu+++ b/src/kernels/cuda/kv_stream.cu@@@ -1,5 -1,5 +1,6 @@@// src/kernels/cuda/kv_stream.cu - see include/strata/kernels/kv_stream.hpp.#include "strata/kernels/kv_stream.hpp"++#include "strata/kernels/kv_q4.hpp"#include "strata/kernels/kv_q8.hpp"#include <cuda_runtime.h>@@@ -29,10 -29,10 +30,15 @@@ struct Runsint n;};--Runs runs_of(const QsaAttnPools& slots, const KvHostPools& host, bool int8, const QsaShapes& s) {++Runs runs_of(const QsaAttnPools& slots, const KvHostPools& host, int fmt, const QsaShapes& s) {const int rows = (int) (s.n_head_kv * s.page_size);Runs r{};-- if (int8) {++ if (fmt == kKvQ4) {++ const int bytes = rows * (int) kv_q4_bytes_per_head((int) s.head_dim);++ r.src[0] = (const uint8_t*) host.k_q4; r.dst[0] = (uint8_t*) slots.k_q4; r.len[0] = bytes;++ r.src[1] = (const uint8_t*) host.v_q4; r.dst[1] = (uint8_t*) slots.v_q4; r.len[1] = bytes;++ r.n = 2;++ } else if (fmt == kKvInt8) {const int codes = rows * (int) s.head_dim, scales = rows * (int) (s.head_dim / KV_Q8_GROUP) * 2;r.src[0] = (const uint8_t*) host.k_q; r.dst[0] = (uint8_t*) slots.k_q; r.len[0] = codes;r.src[1] = (const uint8_t*) host.v_q; r.dst[1] = (uint8_t*) slots.v_q; r.len[1] = codes;@@@ -183,9 -183,9 +189,10 @@@ __global__ void ring_kernel(int32_t* ta} // namespace--uint64_t kv_block_bytes(const QsaShapes& s, bool int8) {++uint64_t kv_block_bytes(const QsaShapes& s, int fmt) {const uint64_t rows = (uint64_t) (s.n_head_kv * s.page_size);-- return int8 ? rows * (uint64_t) s.head_dim * 2 + rows * (uint64_t) (s.head_dim / KV_Q8_GROUP) * 2 * 2++ if (fmt == kKvQ4) return rows * kv_q4_bytes_per_head((int) s.head_dim) * 2;++ return fmt == kKvInt8 ? rows * (uint64_t) s.head_dim * 2 + rows * (uint64_t) (s.head_dim / KV_Q8_GROUP) * 2 * 2: rows * (uint64_t) s.head_dim * 2 * 2;}@@@ -194,7 -194,7 +201,7 @@@ void kv_stream_reset(const KvStreamMapcheck("reset");}--void kv_stream_resolve(const KvStreamMap& m, const QsaAttnPools& slots, const KvHostPools& host, bool int8,++void kv_stream_resolve(const KvStreamMap& m, const QsaAttnPools& slots, const KvHostPools& host, int fmt,const int32_t* ids, const int32_t* steps, int64_t n_q, int64_t cap, const QsaShapes& s,void* stream) {if (n_q <= 0) return;@@@ -204,7 -204,7 +211,7 @@@}resolve_kernel<<<1, RT, 0, (cudaStream_t) stream>>>(m, ids, steps, (int) n_q, (int) cap, (int) s.page_size);check("resolve");-- copy_kernel<<<96, 128, 0, (cudaStream_t) stream>>>(m, runs_of(slots, host, int8, s));++ copy_kernel<<<96, 128, 0, (cudaStream_t) stream>>>(m, runs_of(slots, host, fmt, s));check("copy");}@@@ -213,9 -213,9 +220,9 @@@ void kv_ring_table(int32_t* page_tablecheck("ring table");}--void kv_ring_restore(const QsaAttnPools& slots, const KvHostPools& host, bool int8, int64_t b0, int64_t b1,++void kv_ring_restore(const QsaAttnPools& slots, const KvHostPools& host, int fmt, int64_t b0, int64_t b1,int64_t n_slots, const QsaShapes& s, void* stream) {-- const Runs r = runs_of(slots, host, int8, s);++ const Runs r = runs_of(slots, host, fmt, s);for (int64_t b = b0; b < b1;) {const int64_t sl = b % n_slots, run = std::min<int64_t>(b1 - b, n_slots - sl); // up to the ring's endfor (int a = 0; a < r.n; ++a)@@@ -226,10 -226,10 +233,10 @@@}}--void kv_stage_from_host(const QsaAttnPools& stage, const KvHostPools& host, bool int8, int64_t n_blocks,++void kv_stage_from_host(const QsaAttnPools& stage, const KvHostPools& host, int fmt, int64_t n_blocks,const QsaShapes& s, void* stream) {if (n_blocks <= 0) return;-- const Runs r = runs_of(stage, host, int8, s);++ const Runs r = runs_of(stage, host, fmt, s);for (int a = 0; a < r.n; ++a)if (cudaMemcpyAsync(r.dst[a], r.src[a], (size_t) (n_blocks * r.len[a]), cudaMemcpyDefault,(cudaStream_t) stream) != cudaSuccess)diff --cc src/kernels/kv_stream_parity.cppindex eccbd7e9e,eccbd7e9e..07557347e--- a/src/kernels/kv_stream_parity.cpp+++ b/src/kernels/kv_stream_parity.cpp@@@ -8,7 -8,7 +8,8 @@@// 2. the residency map is consistent after every call (slot_block and page_table invert each other);// 3. no call overflowed, and the hit/miss counters add up;// 4. a ring (the MTP drafter's layout) restored from the host copy reads the same values as the resident pool.--// INT8 and FP16 pools both.++// INT8, FP16 and Q4_0 (PR #21) pools.++#include "strata/kernels/kv_q4.hpp"#include "strata/kernels/kv_q8.hpp"#include "strata/kernels/kv_stream.hpp"#include "strata/kernels/qsa.hpp"@@@ -48,9 -48,9 +49,13 @@@ template <typename T> T* halloc(size_tstruct Pools { // one K/V pool set of `pages` pagesk::KvHostPools p; // reused as a plain pointer bundle-- void alloc(int64_t pages, const k::QsaShapes& s, bool int8, bool host) {++ void alloc(int64_t pages, const k::QsaShapes& s, int fmt, bool host) {const size_t rows = (size_t) pages * s.n_head_kv * s.page_size;-- if (int8) {++ if (fmt == k::kKvQ4) {++ const size_t b = rows * k::kv_q4_bytes_per_head((int) s.head_dim);++ p.k_q4 = host ? halloc<uint8_t>(b) : dalloc<uint8_t>(b);++ p.v_q4 = host ? halloc<uint8_t>(b) : dalloc<uint8_t>(b);++ } else if (fmt == k::kKvInt8) {p.k_q = host ? halloc<int8_t>(rows * s.head_dim) : dalloc<int8_t>(rows * s.head_dim);p.v_q = host ? halloc<int8_t>(rows * s.head_dim) : dalloc<int8_t>(rows * s.head_dim);p.k_scale = host ? halloc<uint16_t>(rows * 4) : dalloc<uint16_t>(rows * 4);@@@ -63,14 -63,14 +68,15 @@@k::QsaAttnPools attn(const int32_t* table) const {k::QsaAttnPools a;a.k_pool = p.k_pool; a.v_pool = p.v_pool; a.k_q = p.k_q; a.v_q = p.v_q; a.k_scale = p.k_scale;-- a.v_scale = p.v_scale; a.page_table = table;++ a.v_scale = p.v_scale; a.k_q4 = p.k_q4; a.v_q4 = p.v_q4; a.page_table = table;return a;}};void append(const Pools& pl, const int32_t* table, const int32_t* step, const float* kc, const float* vc,-- const k::QsaShapes& s, bool int8, const k::KvHostPools* host) {-- if (int8) k::kv_append_q8_step(pl.p.k_q, pl.p.v_q, pl.p.k_scale, pl.p.v_scale, table, step, kc, vc, s, nullptr, host);++ const k::QsaShapes& s, int fmt, const k::KvHostPools* host) {++ if (fmt == k::kKvQ4) k::kv_append_q4_step(pl.p.k_q4, pl.p.v_q4, table, step, kc, vc, s, nullptr, host);++ else if (fmt == k::kKvInt8) k::kv_append_q8_step(pl.p.k_q, pl.p.v_q, pl.p.k_scale, pl.p.v_scale, table, step, kc, vc, s, nullptr, host);else k::kv_append_step(pl.p.k_pool, pl.p.v_pool, table, step, kc, vc, s, nullptr, host);}@@@ -96,18 -96,18 +102,19 @@@ std::vector<int32_t> selection(int64_treturn ids;}--bool run(bool int8) {++bool run(int fmt) {++ const char* name = fmt == k::kKvQ4 ? "q4_0" : fmt == k::kKvInt8 ? "int8" : "fp16";k::QsaShapes s = k::qsa_real_shapes();const int64_t N = 40000, n_blocks = (N + 3) / 4, n_slots = 8 * 516 + 700; // must evict: slots < blocksconst int64_t cap = k::qsa_selection_width(k::kTopkMaxCells, s), NQ = 8;const int64_t H = s.n_head_kv, D = s.head_dim, NH = s.n_head;-- std::mt19937 rng(int8 ? 7 : 11);++ std::mt19937 rng(7 + 4 * fmt);std::normal_distribution<float> nd(0.f, 1.f);Pools ref, slots, host;-- ref.alloc(n_blocks, s, int8, false);-- slots.alloc(n_slots, s, int8, false);-- host.alloc(n_blocks, s, int8, true);++ ref.alloc(n_blocks, s, fmt, false);++ slots.alloc(n_slots, s, fmt, false);++ host.alloc(n_blocks, s, fmt, true);int32_t* ident = dalloc<int32_t>(n_blocks);{std::vector<int32_t> t(n_blocks);@@@ -143,8 -143,8 +150,8 @@@ck(cudaMemcpy(kc, hk.data(), hk.size() * 4, cudaMemcpyHostToDevice), "k");ck(cudaMemcpy(vc, hv.data(), hv.size() * 4, cudaMemcpyHostToDevice), "v");ck(cudaMemcpy(step, st, sizeof(st), cudaMemcpyHostToDevice), "step");-- append(ref, ident, step, kc, vc, s, int8, nullptr);-- append(slots, m.page_table, step, kc, vc, s, int8, &host.p);++ append(ref, ident, step, kc, vc, s, fmt, nullptr);++ append(slots, m.page_table, step, kc, vc, s, fmt, &host.p);if (pos % 131 != 130 && pos != N - 1) continue;// a batch: n_q queries at the last n_q positions (as a verify window), each with its own selectionconst int n_q = 1 + (int) (rng() % NQ);@@@ -163,13 -163,13 +170,13 @@@ck(cudaMemcpy(steps, hst.data(), hst.size() * 4, cudaMemcpyHostToDevice), "steps");ck(cudaMemcpy(q, hq.data(), hq.size() * 4, cudaMemcpyHostToDevice), "q");k::qsa_decode_attn_batch(q, ref.attn(ident), ids, steps, cap, s, scratch, out_ref, n_q, nullptr);-- k::kv_stream_resolve(m, slots.attn(m.page_table), host.p, int8, ids, steps, n_q, cap, s, nullptr);++ k::kv_stream_resolve(m, slots.attn(m.page_table), host.p, fmt, ids, steps, n_q, cap, s, nullptr);k::qsa_decode_attn_batch(q, slots.attn(m.page_table), ids, steps, cap, s, scratch, out_str, n_q, nullptr);ck(cudaDeviceSynchronize(), "batch");ck(cudaMemcpy(a.data(), out_ref, (size_t) n_q * NH * D * 4, cudaMemcpyDeviceToHost), "a");ck(cudaMemcpy(b2.data(), out_str, (size_t) n_q * NH * D * 4, cudaMemcpyDeviceToHost), "b");if (std::memcmp(a.data(), b2.data(), (size_t) n_q * NH * D * 4) != 0) {-- if (bad++ < 5) std::fprintf(stderr, " %s pos %lld n_q %d: streamed attention differs\n", int8 ? "int8" : "fp16", (long long) pos, n_q);++ if (bad++ < 5) std::fprintf(stderr, " %s pos %lld n_q %d: streamed attention differs\n", name, (long long) pos, n_q);}// the map inverts itselfck(cudaMemcpy(pt.data(), m.page_table, n_blocks * 4, cudaMemcpyDeviceToHost), "pt");@@@ -188,7 -188,7 +195,7 @@@}const k::KvStreamCounters c = k::kv_stream_counters(m);std::printf(" %s: %d batches, %llu block lookups, %llu misses (%.1f%% hit), overflow %d, %d failures\n",-- int8 ? "int8" : "fp16", batches, (unsigned long long) c.lookups, (unsigned long long) c.misses,++ name, batches, (unsigned long long) c.lookups, (unsigned long long) c.misses,c.lookups ? 100.0 * (double) (c.lookups - c.misses) / (double) c.lookups : 0.0, (int) c.overflow, bad);if (c.overflow || c.calls != (uint64_t) batches || c.misses == 0 || c.misses >= c.lookups) ++bad;@@@ -196,10 -196,10 +203,10 @@@{const int64_t R = 1500, b1 = n_blocks, b0 = b1 - R;Pools ring;-- ring.alloc(R, s, int8, false);++ ring.alloc(R, s, fmt, false);int32_t* rt = dalloc<int32_t>(n_blocks);k::kv_ring_table(rt, n_blocks, R, nullptr);-- k::kv_ring_restore(ring.attn(rt), host.p, int8, b0, b1, R, s, nullptr);++ k::kv_ring_restore(ring.attn(rt), host.p, fmt, b0, b1, R, s, nullptr);const int64_t width = cap;std::vector<int32_t> hids((size_t) cap), hst = {(int32_t) (N - 1), (int32_t) N, (int32_t) (N / 4), (int32_t) width};for (int64_t i = 0; i < width; ++i) hids[i] = (int32_t) (N - width + i); // the window's last cells@@@ -211,7 -211,7 +218,7 @@@ck(cudaMemcpy(a.data(), out_ref, (size_t) NH * D * 4, cudaMemcpyDeviceToHost), "a");ck(cudaMemcpy(b2.data(), out_str, (size_t) NH * D * 4, cudaMemcpyDeviceToHost), "b");const bool ok = std::memcmp(a.data(), b2.data(), (size_t) NH * D * 4) == 0;-- std::printf(" %s ring restore: %s\n", int8 ? "int8" : "fp16", ok ? "identical" : "DIFFERS");++ std::printf(" %s ring restore: %s\n", name, ok ? "identical" : "DIFFERS");if (!ok) ++bad;}return bad == 0;@@@ -220,8 -220,8 +227,8 @@@int main() {std::printf("kv_stream_parity: streamed vs resident KV, bitwise\n");-- const bool a = run(true), b = run(false);-- if (!a || !b) ++g_fail;++ const bool a = run(k::kKvInt8), b = run(k::kKvF16), c = run(k::kKvQ4);++ if (!a || !b || !c) ++g_fail;std::printf(g_fail ? "FAIL\n" : "PASS\n");return g_fail ? 1 : 0;}diff --cc src/prefill/prefill.cppindex d2c8aa217,a80af1b33..7419dc31a--- a/src/prefill/prefill.cpp+++ b/src/prefill/prefill.cpp@@@ -10,8 -10,9 +10,9 @@@#include "strata/kernels/cpu/expert_layout.hpp"#include "strata/kernels/qsa.hpp"#include "strata/kernels/kv_stream.hpp"++#include "strata/kernels/kv_q4.hpp"#include "strata/core/layer.hpp"#include "strata/kernels/qsa_decode_attn.hpp"-#include "strata/kernels/kv_q4.hpp"#include "strata/kernels/qsa_select.hpp"#include "strata/prefill/gemm.hpp"#include "strata/prefill/kernels.hpp"@@@ -133,7 -134,7 +134,10 @@@ void take_stage(Alloc& o_borrowed, consown.owned = o_borrowed.owned;Alloc& o = stage_own() ? own : o_borrowed;const size_t rows = (size_t) q0.n_pages * s.n_head_kv * s.page_size;-- if (q0.kv_int8) {++ if (q0.kv_q4) {++ st.k_q4 = o.take<uint8_t>(rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), ok);++ st.v_q4 = o.take<uint8_t>(rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), ok);++ } else if (q0.kv_int8) {st.k_q = o.take<int8_t>(rows * s.head_dim, ok);st.v_q = o.take<int8_t>(rows * s.head_dim, ok);st.k_scale = o.take<uint16_t>(rows * (s.head_dim / 64), ok);@@@ -146,6 -147,6 +150,7 @@@strata::kernels::QsaAttnPools pools_of(const strata::kernels::KvHostPools& h, const int32_t* table) {strata::kernels::QsaAttnPools p;p.k_pool = h.k_pool; p.v_pool = h.v_pool; p.k_q = h.k_q; p.v_q = h.v_q; p.k_scale = h.k_scale; p.v_scale = h.v_scale;++ p.k_q4 = h.k_q4; p.v_q4 = h.v_q4;p.page_table = table;return p;}@@@ -420,18 -421,27 +425,27 @@@ bool Prefill::run(const int64_t* tokensif (!bf16_proj(m.gemm, wiq, m.mixed_bf, m.q_idx, T, v.name("indexer.q_proj.weight"), err)) return false;rms_rows(m.Kc, (const float*) wkn->data, T * 2, 256, 256, EPS, m.cs);rope(m.Kc, T, 2, 256, 512, p0, (float) strata::kernels::qsa_freq_base(), m.cs);- const bool staged = st.kv_mode == 1 && !st.kv_q4;- if (st.kv_q4) {+ // KV streaming: this layer's cells [0, p0) come in from the host copy to the staging pool, and the+ // chunk's cells go to the host copy, the staging pool, and the VRAM slots of resident blocks+ const bool staged = st.kv_mode == 1;+ if (staged)- strata::kernels::kv_stage_from_host(pools_of(m.stage, m.ident_table), st.host, st.kv_int8,++ strata::kernels::kv_stage_from_host(pools_of(m.stage, m.ident_table), st.host,++ core::qsa_kv_format(st),+ (p0 + s.page_size - 1) / s.page_size, s, m.cs);- kv_append(m.Kc, m.Vc, T, p0, st.page_table, s.page_size, st.kv_int8 ? nullptr : st.k_pool,- st.kv_int8 ? nullptr : st.v_pool, st.k_q, st.v_q, st.k_scale, st.v_scale, m.cs,- &st.host, staged ? &m.stage : nullptr);++ if (st.kv_q4) { // Q4_0 KV (kv_q4.hpp): rotated K and V, the queries below too, the output back+ strata::kernels::fwht256_inplace_cuda(m.Kc, T * 2, m.cs);+ strata::kernels::fwht256_inplace_cuda(m.Vc, T * 2, m.cs);- strata::kernels::kv_append_q4(st.k_q4, st.v_q4, st.page_table, p0, T, m.Kc, m.Vc, s, m.cs);++ strata::kernels::kv_append_q4(st.k_q4, st.v_q4, st.page_table, p0, T, m.Kc, m.Vc, s, m.cs,++ &st.host, staged ? &m.stage : nullptr);+ } else {- // KV streaming: this layer's cells [0, p0) come in from the host copy to the staging pool, and the- // chunk's cells go to the host copy, the staging pool, and the VRAM slots of resident blocks- if (staged)- strata::kernels::kv_stage_from_host(pools_of(m.stage, m.ident_table), st.host, st.kv_int8,- (p0 + s.page_size - 1) / s.page_size, s, m.cs);+ kv_append(m.Kc, m.Vc, T, p0, st.page_table, s.page_size, st.kv_int8 ? nullptr : st.k_pool,+ st.kv_int8 ? nullptr : st.v_pool, st.k_q, st.v_q, st.k_scale, st.v_scale, m.cs,+ &st.host, staged ? &m.stage : nullptr);+ }split_q(m.Qf, m.q, T, m.cs);rms_rows(m.q, (const float*) wqn->data, T * 24, 256, 256, EPS, m.cs);rope(m.q, T, 24, 256, 6144, p0, (float) strata::kernels::qsa_freq_base(), m.cs);- if (st.kv_q4) {- strata::kernels::fwht256_inplace_cuda(m.q, T * 24, m.cs);- }++ if (st.kv_q4) strata::kernels::fwht256_inplace_cuda(m.q, T * 24, m.cs);rms_rows(m.q_idx, (const float*) wiqn->data, T * 4, 128, 128, EPS, m.cs);rope(m.q_idx, T, 4, 128, 512, p0, (float) strata::kernels::qsa_freq_base(), m.cs);// the indexer appends, token by token; then scores + selection for many queries at once:@@@ -526,6 -536,9 +540,7 @@@m.steps_dev + t0 * strata::kernels::kStepCount, m.cap, s,m.attn_scratch, m.attn + t0 * ZV, nb, m.cs);}- if (st.kv_q4) {- strata::kernels::fwht256_inplace_cuda(m.attn, T * 24, m.cs);- }++ if (st.kv_q4) strata::kernels::fwht256_inplace_cuda(m.attn, T * 24, m.cs);gate_attn(m.attn, m.Qf, m.attn_h, T, m.cs);if (!native_proj(m.gemm, wo, m.attn_h, m.bo, T, v.name("attn_output.weight"), err)) return false;++qsa_index;diff --cc src/program/generate.cppindex 215691140,3ae319c1b..ec781633d--- a/src/program/generate.cpp+++ b/src/program/generate.cpp@@@ -34,6 -34,6 +34,7 @@@#include "strata/kernels/native_qsa_indexer.hpp"#include "strata/kernels/native_rope.hpp"#include "strata/kernels/mrope.hpp"++#include "strata/kernels/kv_q4.hpp"#include "strata/kernels/qsa.hpp"#include "strata/core/native_head.hpp"#include "strata/core/verify.hpp"@@@ -277,6 -275,6 +278,8 @@@ void usage()" --ple-sync-submit A/B arm: submit table reads on the token thread (default: an I/O thread)\n"" --kv fp16|int8 KV storage (plan v0.3 P7): int8 codes + fp16 scale per 64 values, half the\n"" VRAM; default fp16 until gate G-C accepts int8\n"++ " --kv q4_0 4-bit K/V after a Hadamard rotation (PR #21): half of int8's memory,\n"++ " slightly lower precision (see bench/results/2026-09-27-kv-q4)\n"" --kv-resident N KV streaming: keep N cells of each QSA layer in VRAM (min 20480) and the\n"" whole K/V in pinned RAM; the freed VRAM goes to expert slots. 0 (default):\n"" all of it in VRAM. A context of N cells or fewer is not streamed\n"@@@ -725,11 -722,12 +728,13 @@@ int main(int argc, char** argv)std::fprintf(stderr, "strata generate: invalid --ple-io/--ple-row-cache/--ple-inflight/--ple-delay-us\n");return 2;}- if (o.kv != "fp16" && o.kv != "int8") {- std::fprintf(stderr, "strata generate: --kv must be fp16 or int8\n");- if (o.kv != "fp16" && o.kv != "int8" && o.kv != "q4_0" && o.kv != "q4") {- std::fprintf(stderr, "strata generate: --kv must be fp16, int8, or q4_0\n");++ if (o.kv == "q4") o.kv = "q4_0";++ if (o.kv != "fp16" && o.kv != "int8" && o.kv != "q4_0") {++ std::fprintf(stderr, "strata generate: --kv must be fp16, int8 or q4_0\n");return 2;}strata::core::qsa_set_kv_int8(o.kv == "int8");- strata::core::qsa_set_kv_q4(o.kv == "q4_0" || o.kv == "q4");++ strata::core::qsa_set_kv_q4(o.kv == "q4_0"); // PR #21: 4-bit codes after a Hadamard rotation (kv_q4.hpp)if (o.kv_resident < 0) {std::fprintf(stderr, "strata generate: --kv-resident must be >= 0\n");return 2;@@@ -1250,19 -1241,19 +1255,16 @@@(long long) xcache.slots(), xcache.gib());mem_mark("opening the expert cache");xcache.set_per_layer_admission(o.expert_cache_per_layer);-- // **ROUND 328: THE HIT PATH IS PROVABLY WRONG, AND THIS SAYS SO OUT LOUD RATHER THAN LETTING IT-- // CORRUPT A RUN QUIETLY.** With the cache on, the generated tokens DIVERGE from the cache-off run:-- // at 256 global slots (2.97% hits) the first difference is at **token 40**; at 4096 per-layer slots-- // (54.4% hits) it is at **token 0**. The cache-off run is deterministic across repeated runs, so-- // this is a real fault in `moe_hit_grouped_s2`'s inputs or the fill - not noise. It also explains-- // what R4 recorded as "a better profile makes the token worse": more hits means more wrong rows, so-- // the payoff is non-monotone BY CONSTRUCTION rather than by any memory-system effect.-- // The cache stays opt-in and this warning is not a refusal, because the divergence IS the diagnostic.++ // Round 328 warned here that the GPU hit path was wrong (tokens diverged from a cache-off run from++ // token 0). That fault was fixed long since (native_expert_parity, expert_parity, the grouped kernels'++ // tests), and the warning outlived it (issue #23). What remains is rounding: a GPU expert and the CPU's++ // compute the same quantized expert with different float order, so a near-tie can flip. Measured teacher-++ // forced on 2,557 tokens (bench/results/2026-09-27-cache-parity): 95-98% same top-1, and perplexity equal++ // (on - off = -0.005 +- 0.005 nats). Neither output is more correct than the other.std::fprintf(stderr,-- "strata generate: *** WARNING: --expert-cache is enabled and the GPU hit path is NOT\n"-- " CORRECT. The generated tokens diverge from a cache-off run (measured:\n"-- " first difference at token 40 at 2.97%% hits, token 0 at 54.4%%). Any\n"-- " timing from this run is real; any OUTPUT from it is not. ***\n");++ "strata generate: the GPU computes the experts in the cache; it rounds differently from the CPU,\n"++ " so a reply can differ slightly from a run without the cache (same quality:\n"++ " bench/results/2026-09-27-cache-parity).\n");if (o.expert_cache_per_layer) {int64_t lo = 0, hi = 0;xcache.layer_slot_range(0, lo, hi);@@@ -2697,6 -2606,6 +2699,19 @@@uint64_t h_ple = hash_dev(ss.ple_hist, z.ple, 1469598103934665603ull);uint64_t h_tail = 1469598103934665603ull, h_pool = h_tail, h_kv = h_tail, h_stale = h_tail;const int64_t kvb = qs.head_dim, scb = (qs.head_dim / 64) * 2;++ // a state's K/V arrays and their bytes per (cell, head) row: the host copy when it has one++ auto kv_arrays = [&](const strata::core::QsaState& st) {++ const bool h = st.kv_mode != 0;++ std::vector<std::pair<const void*, int64_t>> a;++ if (st.kv_q4) {++ const int64_t q4b = (int64_t) strata::kernels::kv_q4_bytes_per_head((int) qs.head_dim);++ a = {{h ? st.host.k_q4 : st.k_q4, q4b}, {h ? st.host.v_q4 : st.v_q4, q4b}};++ } else {++ a = {{h ? st.host.k_q : st.k_q, kvb}, {h ? st.host.v_q : st.v_q, kvb},++ {h ? st.host.k_scale : st.k_scale, scb}, {h ? st.host.v_scale : st.v_scale, scb}};++ }++ return a;++ };const int64_t end_cell = std::min<int64_t>(((L + qs.page_size - 1) / qs.page_size) * qs.page_size,ss.qsa_states[0].max_cells);for (int64_t i = 0; i < g.n_qsa_layers(); ++i) {@@@ -2704,11 -2613,11 +2719,7 @@@h_tail = hash_dev(st.idx_tail, z.tail, h_tail);h_pool = hash_dev(st.idx_pooled, (size_t) (L / qs.idx_block) * qs.idx_dim * 4, h_pool);// KV streaming: the host copy is the identity layout and holds every cell-- const bool hs = st.kv_mode != 0;-- for (const auto& [pool, w] : {std::pair<const void*, int64_t>{hs ? st.host.k_q : st.k_q, kvb},-- {hs ? st.host.v_q : st.v_q, kvb},-- {hs ? st.host.k_scale : st.k_scale, scb},-- {hs ? st.host.v_scale : st.v_scale, scb}}) {++ for (const auto& [pool, w] : kv_arrays(st)) {h_kv = hash_cells(pool, w, 0, L, h_kv);h_stale = hash_cells(pool, w, L, end_cell, h_stale);}@@@ -2716,11 -2625,11 +2727,7 @@@const strata::core::QsaState& ms = mtp.kv_state();uint64_t h_mtp = 1469598103934665603ull;const int64_t mL = std::min<int64_t>(L, ms.max_cells);-- const bool mh = ms.kv_mode != 0;-- for (const auto& [pool, w] : {std::pair<const void*, int64_t>{mh ? ms.host.k_q : ms.k_q, kvb},-- {mh ? ms.host.v_q : ms.v_q, kvb},-- {mh ? ms.host.k_scale : ms.k_scale, scb},-- {mh ? ms.host.v_scale : ms.v_scale, scb}})++ for (const auto& [pool, w] : kv_arrays(ms))if (pool != nullptr) h_mtp = hash_cells(pool, w, 0, mL, h_mtp);std::fprintf(stderr, "strata serve: STATE_HASH L=%lld gdn=%016llx ple=%016llx tail=%016llx pooled=%016llx ""kv=%016llx mtp=%016llx stale=%016llx ple_prev=%d,%d\n", (long long) L,