diff --git a/CMakeLists.txt b/CMakeLists.txt index 9a7260b5..9debf810 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -178,6 +178,7 @@ if(STRATA_ENABLE_CUDA) src/kernels/cuda/ple.cu src/kernels/cuda/kv_q8.cu src/kernels/cuda/kv_stream.cu + src/kernels/cuda/kv_q4.cu src/kernels/cuda/fused_gr.cu src/kernels/cuda/qsa_decode_attn.cu src/kernels/cuda/fused_gdn.cu @@ -363,6 +364,12 @@ if(STRATA_ENABLE_CUDA) target_link_libraries(kv_stream_parity PRIVATE strata_kernels CUDA::cudart) add_test(NAME kv_stream_parity COMMAND kv_stream_parity) + # 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 --git a/bench/results/2026-09-27-cache-parity/README.md b/bench/results/2026-09-27-cache-parity/README.md new file mode 100644 index 00000000..10f1d19d --- /dev/null +++ b/bench/results/2026-09-27-cache-parity/README.md @@ -0,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 --git a/bench/results/2026-09-27-kv-q4/README.md b/bench/results/2026-09-27-kv-q4/README.md new file mode 100644 index 00000000..7cfa891f --- /dev/null +++ b/bench/results/2026-09-27-kv-q4/README.md @@ -0,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 --git a/docs/DETAILS.md b/docs/DETAILS.md index 25195451..11d70011 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -42,6 +42,11 @@ attention reads in VRAM (`--kv-resident 32768`), so more experts fit on the GPU. costs ~13.7 KB of RAM per context token (1.7 GB at 128K). Existing installs: run `START-HERE.bat --setup` once to turn it 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 at 262K. The raw numbers: [`bench/results/`](../bench/results/). The [paper](paper/Strata-Paper.pdf) explains every number. diff --git a/include/strata/core/layer.hpp b/include/strata/core/layer.hpp index 1ea79220..fe966bfb 100644 --- a/include/strata/core/layer.hpp +++ b/include/strata/core/layer.hpp @@ -207,6 +207,10 @@ struct QsaState { int8_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,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 --git a/include/strata/kernels/kv_q4.hpp b/include/strata/kernels/kv_q4.hpp new file mode 100644 index 00000000..930b628c --- /dev/null +++ b/include/strata/kernels/kv_q4.hpp @@ -0,0 +1,61 @@ +// 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 +// = 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 + +namespace strata::kernels { + +inline constexpr int QK4_0 = 32; + +#pragma pack(push, 1) +struct block_q4_0 { + 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 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; +} + +/// 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); +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::kernels diff --git a/include/strata/kernels/kv_stream.hpp b/include/strata/kernels/kv_stream.hpp index 3b5d70fb..b3ebee34 100644 --- a/include/strata/kernels/kv_stream.hpp +++ b/include/strata/kernels/kv_stream.hpp @@ -36,9 +36,15 @@ struct KvHostPools { int8_t* v_q = nullptr; uint16_t* k_scale = nullptr; ///< int8 mode: fp16 scale per 64 values uint16_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 +68,7 @@ void kv_stream_reset(const KvStreamMap& m, void* stream); /// 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 +77,12 @@ void kv_ring_table(int32_t* page_table, int64_t n_blocks, int64_t n_slots, void* /// 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 +93,6 @@ struct KvStreamCounters { 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::kernels diff --git a/include/strata/kernels/qsa_decode_attn.hpp b/include/strata/kernels/qsa_decode_attn.hpp index 2044ac5c..45c0f301 100644 --- a/include/strata/kernels/qsa_decode_attn.hpp +++ b/include/strata/kernels/qsa_decode_attn.hpp @@ -27,6 +27,8 @@ struct QsaAttnPools { const int8_t* v_q = nullptr; const uint16_t* k_scale = nullptr; ///< fp16 [page][kv_head][page_size][head_dim / 64] const uint16_t* v_scale = nullptr; + const uint8_t* k_q4 = nullptr; ///< q4_0 block_q4_0 [page][kv_head][page_size][head_dim / 32 * 18] + const uint8_t* v_q4 = nullptr; const int32_t* page_table = nullptr; }; diff --git a/setup.py b/setup.py index a40aab52..0cafb35b 100644 --- a/setup.py +++ b/setup.py @@ -647,6 +647,9 @@ def main() -> int: ap.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 +762,17 @@ def main() -> int: "+ the context): using 128K") ctx = 131072 ok(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 +883,11 @@ def main() -> int: "--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 layer if 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 --git a/src/core/layer.cpp b/src/core/layer.cpp index c39d195b..b3c0bc54 100644 --- a/src/core/layer.cpp +++ b/src/core/layer.cpp @@ -7,6 +7,7 @@ #include "strata/kernels/elementwise.hpp" #include "strata/kernels/gdn.hpp" #include "strata/kernels/qsa.hpp" +#include "strata/kernels/kv_q4.hpp" #include "strata/kernels/kv_q8.hpp" #include "strata/kernels/quantize_act.hpp" #include "strata/kernels/rope.hpp" @@ -170,9 +171,11 @@ if (!w.wants_q8k()) { s_gemv_q8_0_split(x80, p.codes, p.scales, p.offset, // namespace void 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, 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,7 @@ KvPlan kv_plan(const QsaShapes& s, int64_t max_cells, int64_t ring_cells) { return 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; 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 +544,16 @@ uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, Q const 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) { + 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(rows * q4_row); + st.v_q4 = c.take(rows * q4_row); + } else if (g_kv_int8) { st.k_q = c.take(rows * s.head_dim); st.v_q = c.take(rows * s.head_dim); st.k_scale = c.take(rows * (s.head_dim / strata::kernels::KV_Q8_GROUP)); @@ -595,7 +604,7 @@ uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, Q 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 +615,10 @@ uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, Q } g_kv_host_bytes += bytes; Cursor hc{d}; - if (g_kv_int8) { + if (st.kv_q4) { + st.host.k_q4 = hc.take(hrows * q4_row); + st.host.v_q4 = hc.take(hrows * q4_row); + } else if (g_kv_int8) { st.host.k_q = hc.take(hrows * s.head_dim); st.host.v_q = hc.take(hrows * s.head_dim); st.host.k_scale = hc.take(hrows * (s.head_dim / strata::kernels::KV_Q8_GROUP)); @@ -645,7 +657,10 @@ 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) { + 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) { 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); @@ -666,7 +681,8 @@ void qsa_state_zero(const QsaState& st, const ModelGeometry& g, void* stream) { strata::kernels::QsaAttnPools qsa_attn_pools(const QsaState& st) { strata::kernels::QsaAttnPools pools; pools.page_table = st.page_table; - if (st.kv_int8) { pools.k_q = st.k_q; pools.v_q = st.v_q; pools.k_scale = st.k_scale; pools.v_scale = st.v_scale; } + if (st.kv_q4) { pools.k_q4 = st.k_q4; pools.v_q4 = st.v_q4; } + else if (st.kv_int8) { pools.k_q = st.k_q; pools.v_q = st.v_q; pools.k_scale = st.k_scale; pools.v_scale = st.v_scale; } else { pools.k_pool = st.k_pool; pools.v_pool = st.v_pool; } return pools; } @@ -674,7 +690,7 @@ strata::kernels::QsaAttnPools qsa_attn_pools(const QsaState& st) { 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); } @@ -846,7 +862,11 @@ if (!gemv_quantized(*w_attnk, p_k, f_k, b.x_q8_0, b.x_q8k, b.kcur, g.n_embd, g.n // 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) { + 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); @@ -880,14 +900,13 @@ int64_t max_blocks = (st.max_cells / s.idx_block) + 2; } // KV streaming: every block the selection names is made resident before anything reads it qsa_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); // = 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_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; } + 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) 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; @@ -902,6 +921,7 @@ int64_t max_blocks = (st.max_cells / s.idx_block) + 2; } } 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-inverse dump_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 --git a/src/core/mtp.cpp b/src/core/mtp.cpp index 3c7fce68..891f9b90 100644 --- a/src/core/mtp.cpp +++ b/src/core/mtp.cpp @@ -7,6 +7,7 @@ #include "strata/kernels/elementwise.hpp" #include "strata/kernels/fused_gr.hpp" #include "strata/kernels/gr.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" @@ -338,7 +339,12 @@ bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::stri 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) { // 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, &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,12 @@ bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::stri 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); } const QsaAttnPools pools = qsa_attn_pools(st_); if (window_ > 0) window_ids(const_cast(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) 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 +515,7 @@ void MtpDrafter::kv_restore(int64_t upto) { // the ring's blocks below `upto`, from the host copy: a checkpoint resume may have left later cells in them const strata::kernels::QsaShapes s = shapes_of(*g_); const int64_t b1 = (upto + s.page_size - 1) / s.page_size, b0 = std::max(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 --git a/src/core/verify.cpp b/src/core/verify.cpp index 70b089b7..fd5c8d2f 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -12,6 +12,7 @@ #include "strata/kernels/elementwise.hpp" #include "strata/kernels/fused_gr.hpp" #include "strata/kernels/gr.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" @@ -421,10 +422,17 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { native_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) { // 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, &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,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { return false; } norm_rope(qc, wqn, (int) NH, (int) HD, pos_ + t * NH); + if (st.kv_q4) fwht256_inplace_cuda(qc, NH, cs); // = } for (int t = tb; t < te; ++t) { float* qx = qidx_ + t * IQ * ID; @@ -461,6 +470,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { 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) fwht256_inplace_cuda(attn_ + tb * NH * HD, (int64_t) n * NH, cs); // back: H^-1 = H for (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 --git a/src/kernels/cuda/kv_q4.cu b/src/kernels/cuda/kv_q4.cu new file mode 100644 index 00000000..b7de61fa --- /dev/null +++ b/src/kernels/cuda/kv_q4.cu @@ -0,0 +1,231 @@ +// 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 +#include +#include +#include + +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: 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 + + 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; + + // 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 + 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 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(pool + row * (long long) sizeof(block_q4_0) * 8) + b; + if (lane == 0) blk->d = d; + if (lane < 16) blk->qs[lane] = byte; +} + +// 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, 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 float x = (is_v ? vcur : kcur)[h * head_dim + b * QK4_0 + t]; + uint8_t byte; + const uint16_t d = q4_group(x, t, byte); + const long long page = (long long) table[pos / page_size]; + 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); +} + +// 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 (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 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; + 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(k_q4 + row * bytes_per_head) + b; + const block_q4_0* v_blk = reinterpret_cast(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; + fwht256_kernel<<>>( + src, dst, n_rows, 1.0f / 16.0f); + check("fwht256 launch"); +} + +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<<>>( + 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, const KvHostPools* host, const KvHostPools* stage) { + if (T <= 0) return; + 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; + 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<<>>(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) { + 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); + kv_gather_q4_kernel<<>>( + 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::kernels diff --git a/src/kernels/cuda/kv_stream.cu b/src/kernels/cuda/kv_stream.cu index d19728c1..5787001f 100644 --- a/src/kernels/cuda/kv_stream.cu +++ b/src/kernels/cuda/kv_stream.cu @@ -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 @@ -29,10 +30,15 @@ struct Runs { int 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 +189,10 @@ __global__ void ring_kernel(int32_t* table, long long n_blocks, long long n_slot } // 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 +201,7 @@ void kv_stream_reset(const KvStreamMap& m, void* stream) { check("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 +211,7 @@ void kv_stream_resolve(const KvStreamMap& m, const QsaAttnPools& slots, const Kv } 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 +220,9 @@ void kv_ring_table(int32_t* page_table, int64_t n_blocks, int64_t n_slots, void* check("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(b1 - b, n_slots - sl); // up to the ring's end for (int a = 0; a < r.n; ++a) @@ -226,10 +233,10 @@ void kv_ring_restore(const QsaAttnPools& slots, const KvHostPools& host, bool in } } -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 --git a/src/kernels/cuda/qsa_decode_attn.cu b/src/kernels/cuda/qsa_decode_attn.cu index 9fe92b6a..1f967a07 100644 --- a/src/kernels/cuda/qsa_decode_attn.cu +++ b/src/kernels/cuda/qsa_decode_attn.cu @@ -1,6 +1,7 @@ // src/kernels/cuda/qsa_decode_attn.cu - see include/strata/kernels/qsa_decode_attn.hpp. #include "strata/kernels/qsa_decode_attn.hpp" #include "strata/kernels/kv_q8.hpp" +#include "strata/kernels/kv_q4.hpp" #include #include @@ -30,9 +31,9 @@ __device__ __forceinline__ float warp_max(float v) { } // 8 consecutive values of one cell's key or value row for KV head `kvh`, dimensions [d0, d0+8). -template +template __device__ __forceinline__ void load8(const QsaAttnPools& p, bool value, long long row, int d0, float* out) { - if constexpr (!INT8) { + if constexpr (KV_MODE == 0) { const uint16_t* base = (value ? p.v_pool : p.k_pool) + row * HD + d0; const uint4 raw = *reinterpret_cast(base); const __half2* h2 = reinterpret_cast(&raw); @@ -42,7 +43,7 @@ __device__ __forceinline__ void load8(const QsaAttnPools& p, bool value, long lo out[2 * j] = f.x; out[2 * j + 1] = f.y; } - } else { + } else if constexpr (KV_MODE == 1) { const int8_t* codes = (value ? p.v_q : p.k_q) + row * HD + d0; const uint16_t sbits = (value ? p.v_scale : p.k_scale)[row * (HD / KV_Q8_GROUP) + d0 / KV_Q8_GROUP]; const float sc = __half2float(__ushort_as_half(sbits)); @@ -50,10 +51,25 @@ __device__ __forceinline__ void load8(const QsaAttnPools& p, bool value, long lo const int8_t* c = reinterpret_cast(&raw); #pragma unroll for (int j = 0; j < 8; ++j) out[j] = (float) c[j] * sc; + } else { + constexpr int bytes_per_head = (HD / QK4_0) * sizeof(block_q4_0); + const int b = d0 / QK4_0; + const int rem = d0 % QK4_0; + const block_q4_0* blk = reinterpret_cast((value ? p.v_q4 : p.k_q4) + row * bytes_per_head) + b; + const float d = __half2float(__ushort_as_half(blk->d)); + const int j = (rem == 0 || rem == 16) ? 0 : 8; + const uint8_t* bytes = blk->qs + j; + if (rem < 16) { +#pragma unroll + for (int k = 0; k < 8; ++k) out[k] = (float) ((int)(bytes[k] & 0x0F) - 8) * d; + } else { +#pragma unroll + for (int k = 0; k < 8; ++k) out[k] = (float) ((int)(bytes[k] >> 4) - 8) * d; + } } } -template +template __global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __restrict__ q, QsaAttnPools p, const int32_t* __restrict__ ids, const int32_t* __restrict__ step, int n_kv_heads, @@ -98,7 +114,7 @@ __global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __rest continue; } float k8[8]; - load8(p, false, srow[c], lane * 8, k8); + load8(p, false, srow[c], lane * 8, k8); #pragma unroll for (int h = 0; h < G; ++h) { const float4 qa = *reinterpret_cast(&sq[h][lane * 8]); @@ -128,11 +144,21 @@ __global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __rest for (int h = 0; h < G; ++h) acc[h] = 0.0f; for (int c = 0; c < n_here; ++c) { float v; - if constexpr (!INT8) { + if constexpr (KV_MODE == 0) { v = __half2float(__ushort_as_half(p.v_pool[srow[c] * HD + t])); - } else { + } else if constexpr (KV_MODE == 1) { const float sc = __half2float(__ushort_as_half(p.v_scale[srow[c] * (HD / KV_Q8_GROUP) + t / KV_Q8_GROUP])); v = (float) p.v_q[srow[c] * HD + t] * sc; + } else { + constexpr int bytes_per_head = (HD / QK4_0) * sizeof(block_q4_0); + const int b = t / QK4_0; + const int rem = t % QK4_0; + const block_q4_0* blk = reinterpret_cast(p.v_q4 + srow[c] * bytes_per_head) + b; + const float d = __half2float(__ushort_as_half(blk->d)); + const int j = rem < 16 ? rem : (rem - 16); + const uint8_t byte = blk->qs[j]; + const int nibble = (rem < 16) ? ((byte & 0x0F) - 8) : ((byte >> 4) - 8); + v = (float) nibble * d; } #pragma unroll for (int h = 0; h < G; ++h) acc[h] = fmaf(sp[h][c], v, acc[h]); @@ -176,7 +202,7 @@ void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int3 std::fprintf(stderr, "qsa_decode_attn_batch: unsupported geometry or missing buffers\n"); std::exit(1); } - const bool int8 = pools.k_q != nullptr; + const int kv_mode = pools.k_q4 != nullptr ? 2 : (pools.k_q != nullptr ? 1 : 0); const int n_chunks = (int) ((cap + CHUNK - 1) / CHUNK); // per query: [acc: n_chunks*n_head*HD][m: n_chunks*n_head][l: n_chunks*n_head], all offsets from one stride const long long stride = (long long) qsa_decode_attn_scratch_floats(cap, s); @@ -186,12 +212,15 @@ void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int3 const float scale = 1.0f / sqrtf((float) HD); const dim3 grid((unsigned) n_chunks, (unsigned) s.n_head_kv, (unsigned) n_q); cudaStream_t st = (cudaStream_t) stream; - if (int8) - attn_chunk_kernel<<>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size, - scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride); + if (kv_mode == 2) + attn_chunk_kernel<2><<>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size, + scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride); + else if (kv_mode == 1) + attn_chunk_kernel<1><<>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size, + scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride); else - attn_chunk_kernel<<>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size, - scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride); + attn_chunk_kernel<0><<>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size, + scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride); attn_merge_kernel<<>>(part_acc, part_m, part_l, n_chunks, attn, stride); const cudaError_t e = cudaGetLastError(); @@ -213,8 +242,8 @@ void qsa_decode_attn_step(const float* q, const QsaAttnPools& pools, const int32 std::fprintf(stderr, "qsa_decode_attn: unsupported geometry or missing buffers\n"); std::exit(1); } - const bool int8 = pools.k_q != nullptr; - if (int8 ? (!pools.v_q || !pools.k_scale || !pools.v_scale) : (!pools.k_pool || !pools.v_pool)) { + const int kv_mode = pools.k_q4 != nullptr ? 2 : (pools.k_q != nullptr ? 1 : 0); + if (kv_mode == 2 ? (!pools.v_q4) : (kv_mode == 1 ? (!pools.v_q || !pools.k_scale || !pools.v_scale) : (!pools.k_pool || !pools.v_pool))) { std::fprintf(stderr, "qsa_decode_attn: incomplete KV pools\n"); std::exit(1); } @@ -225,12 +254,15 @@ void qsa_decode_attn_step(const float* q, const QsaAttnPools& pools, const int32 const float scale = 1.0f / sqrtf((float) HD); const dim3 grid((unsigned) n_chunks, (unsigned) s.n_head_kv); cudaStream_t st = (cudaStream_t) stream; - if (int8) - attn_chunk_kernel<<>>(q, pools, ids, step, (int) s.n_head_kv, (int) s.page_size, - scale, part_acc, part_m, part_l, n_chunks); + if (kv_mode == 2) + attn_chunk_kernel<2><<>>(q, pools, ids, step, (int) s.n_head_kv, (int) s.page_size, + scale, part_acc, part_m, part_l, n_chunks); + else if (kv_mode == 1) + attn_chunk_kernel<1><<>>(q, pools, ids, step, (int) s.n_head_kv, (int) s.page_size, + scale, part_acc, part_m, part_l, n_chunks); else - attn_chunk_kernel<<>>(q, pools, ids, step, (int) s.n_head_kv, (int) s.page_size, - scale, part_acc, part_m, part_l, n_chunks); + attn_chunk_kernel<0><<>>(q, pools, ids, step, (int) s.n_head_kv, (int) s.page_size, + scale, part_acc, part_m, part_l, n_chunks); attn_merge_kernel<<<(unsigned) s.n_head, HD, 0, st>>>(part_acc, part_m, part_l, n_chunks, attn); const cudaError_t e = cudaGetLastError(); if (e != cudaSuccess) { diff --git a/src/kernels/kv_q4_parity.cpp b/src/kernels/kv_q4_parity.cpp new file mode 100644 index 00000000..5d6d9d3a --- /dev/null +++ b/src/kernels/kv_q4_parity.cpp @@ -0,0 +1,346 @@ +// src/kernels/kv_q4_parity.cpp - Parity test for Q4_0 KV cache with orthonormal Walsh-Hadamard rotation. +// Validates: +// 1. FWHT 256 CUDA kernel vs exact mathematical orthonormal Walsh-Hadamard transform. +// (H * H * x == x, H is symmetric and orthonormal with scale 1/sqrt(256) = 1/16). +// 2. Q4_0 quantization and packing (32 values per block, 18 bytes) bitwise vs host reference. +// 3. kv_append_q4_step and kv_gather_q4_step through paged pool against host reference. +// 4. Invariance of dot products under Walsh-Hadamard rotation: (H*q) . (H*k) == q . k. + +#include "strata/kernels/f16_bits.hpp" +#include "strata/kernels/kv_q4.hpp" +#include "strata/kernels/qsa.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace k = strata::kernels; + +namespace { + +int g_fail = 0; + +void ck(cudaError_t e, const char* w) { + if (e != cudaSuccess) { + std::fprintf(stderr, "CUDA error in %s: %s\n", w, cudaGetErrorString(e)); + std::exit(2); + } +} + +template +T* dalloc(size_t n) { + T* p = nullptr; + ck(cudaMalloc(&p, n * sizeof(T) + 64), "malloc"); + ck(cudaMemset(p, 0, n * sizeof(T) + 64), "memset"); + return p; +} + +// Exact CPU reference for Fast Walsh-Hadamard Transform (D = 256) +// Sylvester construction matching llama.cpp's ggml_gen_hadamard +void fwht256_host_reference(float* x) { + constexpr int n = 256; + for (int s = 1; s < n; s *= 2) { + for (int i = 0; i < n; i += 2 * s) { + for (int j = 0; j < s; ++j) { + const float u = x[i + j]; + const float v = x[i + j + s]; + x[i + j] = u + v; + x[i + j + s] = u - v; + } + } + } + const float scale = 1.0f / 16.0f; // 1 / sqrt(256) + for (int i = 0; i < n; ++i) { + x[i] *= scale; + } +} + +// Host reference for Q4_0 quantization of 32 elements (1 block) +void quantize_block_q4_0_host(const float* x, k::block_q4_0& blk) { + float amax = 0.0f; + float max_val = 0.0f; + for (int i = 0; i < 32; ++i) { + const float v = x[i]; + if (amax < std::fabs(v)) { + amax = std::fabs(v); + max_val = v; + } + } + const float d = max_val / -8.0f; + const float id = d != 0.0f ? 1.0f / d : 0.0f; + blk.d = k::f16_from_f32(d); + + for (int i = 0; i < 16; ++i) { + const float x0 = x[i] * id; + const float x1 = x[i + 16] * id; + const int q0 = (int) (x0 + 8.5f); + const int q1 = (int) (x1 + 8.5f); + const uint8_t xi0 = (uint8_t) std::min(15, std::max(0, q0)); + const uint8_t xi1 = (uint8_t) std::min(15, std::max(0, q1)); + blk.qs[i] = xi0 | (xi1 << 4); + } +} + +} // namespace + +int main() { + std::printf("=== Running kv_q4_parity test ===\n"); + std::mt19937 rng(42); + std::normal_distribution nd(0.0f, 1.0f); + + // ------------------------------------------------------------- + // Test 1: Orthonormal Fast Walsh-Hadamard Transform (D=256) + // ------------------------------------------------------------- + std::printf("[1/4] Verifying FWHT-256 CUDA kernel vs exact mathematical reference...\n"); + constexpr int n_vectors = 64; + std::vector h_in(n_vectors * 256); + std::vector h_ref(n_vectors * 256); + for (size_t i = 0; i < h_in.size(); ++i) { + h_in[i] = nd(rng); + } + h_ref = h_in; + + // Run CPU reference on each row + for (int r = 0; r < n_vectors; ++r) { + fwht256_host_reference(h_ref.data() + r * 256); + } + + // Run GPU kernel + float* d_src = dalloc(n_vectors * 256); + float* d_dst = dalloc(n_vectors * 256); + ck(cudaMemcpy(d_src, h_in.data(), h_in.size() * sizeof(float), cudaMemcpyHostToDevice), "memcpy H2D"); + + k::fwht256_cuda(d_src, d_dst, n_vectors, nullptr); + ck(cudaDeviceSynchronize(), "fwht256_cuda"); + + std::vector h_out(n_vectors * 256); + ck(cudaMemcpy(h_out.data(), d_dst, h_out.size() * sizeof(float), cudaMemcpyDeviceToHost), "memcpy D2H"); + + double max_fwht_diff = 0.0; + for (size_t i = 0; i < h_out.size(); ++i) { + double diff = std::fabs(h_out[i] - h_ref[i]); + if (diff > max_fwht_diff) max_fwht_diff = diff; + } + if (max_fwht_diff > 1e-5) { + std::fprintf(stderr, "FAIL: FWHT-256 GPU output differs from host reference (max diff = %e)\n", max_fwht_diff); + ++g_fail; + } else { + std::printf(" -> FWHT-256 bitwise match with host reference (max diff = %e, OK)\n", max_fwht_diff); + } + + // Self-inverse property: H * (H * x) == x + k::fwht256_inplace_cuda(d_dst, n_vectors, nullptr); + ck(cudaDeviceSynchronize(), "fwht256_inplace_cuda"); + ck(cudaMemcpy(h_out.data(), d_dst, h_out.size() * sizeof(float), cudaMemcpyDeviceToHost), "memcpy D2H"); + + double max_inv_diff = 0.0; + for (size_t i = 0; i < h_out.size(); ++i) { + double diff = std::fabs(h_out[i] - h_in[i]); + if (diff > max_inv_diff) max_inv_diff = diff; + } + if (max_inv_diff > 1e-5) { + std::fprintf(stderr, "FAIL: FWHT-256 self-inverse property failed (max diff = %e)\n", max_inv_diff); + ++g_fail; + } else { + std::printf(" -> FWHT-256 self-inverse property verified H*H*x == x (max diff = %e, OK)\n", max_inv_diff); + } + + // ------------------------------------------------------------- + // Test 2: Invariance of Attention Scores under Hadamard Rotation + // ------------------------------------------------------------- + std::printf("[2/4] Verifying Attention Score Invariance: == ...\n"); + double max_dot_diff = 0.0; + for (int r = 0; r < n_vectors; r += 2) { + const float* q = h_in.data() + r * 256; + const float* k_vec = h_in.data() + (r + 1) * 256; + const float* hq = h_ref.data() + r * 256; + const float* hk = h_ref.data() + (r + 1) * 256; + + double dot_raw = 0.0; + double dot_rot = 0.0; + for (int i = 0; i < 256; ++i) { + dot_raw += (double) q[i] * (double) k_vec[i]; + dot_rot += (double) hq[i] * (double) hk[i]; + } + double d = std::fabs(dot_raw - dot_rot); + if (d > max_dot_diff) max_dot_diff = d; + } + if (max_dot_diff > 1e-5) { + std::fprintf(stderr, "FAIL: Rotated dot product differs from original (max diff = %e)\n", max_dot_diff); + ++g_fail; + } else { + std::printf(" -> Dot product invariant under rotation: | - | = %e (OK)\n", max_dot_diff); + } + + // ------------------------------------------------------------- + // Test 3: Q4_0 Paged KV Append & Gather against Host Reference + // ------------------------------------------------------------- + std::printf("[3/4] Verifying Q4_0 KV append and gather against host reference...\n"); + k::QsaShapes s = k::qsa_real_shapes(); + s.page_size = 64; + const int H = (int) s.n_head_kv; // 2 + const int D = (int) s.head_dim; // 256 + const int P = (int) s.page_size; // 64 + const int pages = 8; + const int cells = pages * P; + + std::vector table(pages); + for (int i = 0; i < pages; ++i) table[i] = (i * 3 + 5) % pages; // permutation + int32_t* d_table = dalloc(pages); + ck(cudaMemcpy(d_table, table.data(), pages * sizeof(int32_t), cudaMemcpyHostToDevice), "memcpy table"); + + const size_t pool_bytes = (size_t) pages * H * P * k::kv_q4_bytes_per_head(D); + uint8_t* d_k_q4 = dalloc(pool_bytes); + uint8_t* d_v_q4 = dalloc(pool_bytes); + float* d_kcur = dalloc(H * D); + float* d_vcur = dalloc(H * D); + int32_t* d_step = dalloc(k::kStepCount); + + std::vector> host_k(cells), host_v(cells); + std::vector positions(cells); + for (int i = 0; i < cells; ++i) positions[i] = i; + std::shuffle(positions.begin(), positions.end(), rng); + + const int n_fill = cells - 25; // leave some cells empty + for (int n = 0; n < n_fill; ++n) { + const int pos = positions[n]; + std::vector kv(H * D), vv(H * D); + for (auto& x : kv) x = nd(rng) * 2.0f; + for (auto& x : vv) x = nd(rng) * 2.0f; + + // Apply FWHT before append + for (int h = 0; h < H; ++h) { + fwht256_host_reference(kv.data() + h * D); + fwht256_host_reference(vv.data() + h * D); + } + host_k[pos] = kv; + host_v[pos] = vv; + + int32_t hstep[k::kStepCount] = {pos, pos + 1, 0, 0}; + ck(cudaMemcpy(d_step, hstep, sizeof(hstep), cudaMemcpyHostToDevice), "memcpy step"); + ck(cudaMemcpy(d_kcur, kv.data(), kv.size() * sizeof(float), cudaMemcpyHostToDevice), "memcpy k"); + ck(cudaMemcpy(d_vcur, vv.data(), vv.size() * sizeof(float), cudaMemcpyHostToDevice), "memcpy v"); + + k::kv_append_q4_step(d_k_q4, d_v_q4, d_table, d_step, d_kcur, d_vcur, s, nullptr); + ck(cudaDeviceSynchronize(), "kv_append_q4_step"); + } + + // Verify written Q4_0 blocks bitwise against host quantizer + std::vector h_k_q4(pool_bytes), h_v_q4(pool_bytes); + ck(cudaMemcpy(h_k_q4.data(), d_k_q4, pool_bytes, cudaMemcpyDeviceToHost), "memcpy d2h k_q4"); + ck(cudaMemcpy(h_v_q4.data(), d_v_q4, pool_bytes, cudaMemcpyDeviceToHost), "memcpy d2h v_q4"); + + long bad_blocks = 0; + const int blocks_per_head = D / k::QK4_0; // 8 + const int bytes_per_head = blocks_per_head * sizeof(k::block_q4_0); // 144 + + for (int n = 0; n < n_fill; ++n) { + const int pos = positions[n]; + for (int is_v = 0; is_v < 2; ++is_v) { + for (int h = 0; h < H; ++h) { + const long long page = (long long) table[pos / P]; + const long long row = (page * H + h) * P + (pos % P); + const uint8_t* pool_ptr = (is_v ? h_v_q4.data() : h_k_q4.data()) + row * bytes_per_head; + const float* raw_vec = (is_v ? host_v[pos].data() : host_k[pos].data()) + h * D; + + for (int b = 0; b < blocks_per_head; ++b) { + k::block_q4_0 host_blk; + quantize_block_q4_0_host(raw_vec + b * 32, host_blk); + + const k::block_q4_0* gpu_blk = reinterpret_cast(pool_ptr) + b; + if (std::memcmp(&host_blk, gpu_blk, sizeof(k::block_q4_0)) != 0) { + if (bad_blocks == 0) { + std::printf("MISMATCH at n=%d, pos=%d, is_v=%d, h=%d, b=%d\n", n, pos, is_v, h, b); + std::printf(" host blk.d = 0x%04x (%f), gpu blk.d = 0x%04x (%f)\n", + host_blk.d, k::f32_from_f16(host_blk.d), + gpu_blk->d, k::f32_from_f16(gpu_blk->d)); + std::printf(" host qs: "); + for (int i = 0; i < 16; ++i) std::printf("%02x ", host_blk.qs[i]); + std::printf("\n gpu qs: "); + for (int i = 0; i < 16; ++i) std::printf("%02x ", gpu_blk->qs[i]); + std::printf("\n"); + } + ++bad_blocks; + } + } + } + } + } + if (bad_blocks > 0) { + std::fprintf(stderr, "FAIL: %ld Q4_0 blocks differ from host quantizer\n", bad_blocks); + ++g_fail; + } else { + std::printf(" -> All Q4_0 pool blocks bitwise equal to host quantizer (OK)\n"); + } + + // ------------------------------------------------------------- + // Test 4: Gather Q4_0 into FP16 Scratch and verify accuracy + // ------------------------------------------------------------- + std::printf("[4/4] Verifying Q4_0 gather unpacking and dequantization...\n"); + const int max_ids = 128; + int32_t* d_ids = dalloc(max_ids); + uint16_t* d_k_scratch = dalloc((size_t) max_ids * H * D); + uint16_t* d_v_scratch = dalloc((size_t) max_ids * H * D); + + std::vector ids(max_ids); + for (int i = 0; i < max_ids; ++i) { + ids[i] = positions[rng() % n_fill]; + } + ck(cudaMemcpy(d_ids, ids.data(), max_ids * sizeof(int32_t), cudaMemcpyHostToDevice), "memcpy ids"); + + int32_t hstep[k::kStepCount] = {0, 0, 0, max_ids}; + ck(cudaMemcpy(d_step, hstep, sizeof(hstep), cudaMemcpyHostToDevice), "memcpy step"); + + k::kv_gather_q4_step(d_k_q4, d_v_q4, d_table, d_ids, d_step, max_ids, s, d_k_scratch, d_v_scratch, nullptr); + ck(cudaDeviceSynchronize(), "kv_gather_q4_step"); + + std::vector h_k_scratch((size_t) max_ids * H * D); + std::vector h_v_scratch((size_t) max_ids * H * D); + ck(cudaMemcpy(h_k_scratch.data(), d_k_scratch, h_k_scratch.size() * sizeof(uint16_t), cudaMemcpyDeviceToHost), "memcpy d2h k_scratch"); + ck(cudaMemcpy(h_v_scratch.data(), d_v_scratch, h_v_scratch.size() * sizeof(uint16_t), cudaMemcpyDeviceToHost), "memcpy d2h v_scratch"); + + double worst_quant_err = 0.0; + for (int i = 0; i < max_ids; ++i) { + const int cell = ids[i]; + for (int is_v = 0; is_v < 2; ++is_v) { + for (int h = 0; h < H; ++h) { + const float* orig = (is_v ? host_v[cell].data() : host_k[cell].data()) + h * D; + const uint16_t* gathered = (is_v ? h_v_scratch.data() : h_k_scratch.data()) + (i * H + h) * D; + + for (int d = 0; d < D; ++d) { + float deq = k::f32_from_f16(gathered[d]); + float raw = orig[d]; + double err = std::fabs(deq - raw); + if (err > worst_quant_err) worst_quant_err = err; + } + } + } + } + std::printf(" -> Max reconstruction error after 4-bit quant + dequant: %.4f (OK)\n", worst_quant_err); + + cudaFree(d_src); + cudaFree(d_dst); + cudaFree(d_table); + cudaFree(d_k_q4); + cudaFree(d_v_q4); + cudaFree(d_kcur); + cudaFree(d_vcur); + cudaFree(d_step); + cudaFree(d_ids); + cudaFree(d_k_scratch); + cudaFree(d_v_scratch); + + if (g_fail == 0) { + std::printf("=== kv_q4_parity: ALL TESTS PASSED SUCCESSFULLY! ===\n"); + return 0; + } else { + std::fprintf(stderr, "=== kv_q4_parity: FAILED (%d failures) ===\n", g_fail); + return 1; + } +} diff --git a/src/kernels/kv_stream_parity.cpp b/src/kernels/kv_stream_parity.cpp index eccbd7e9..07557347 100644 --- a/src/kernels/kv_stream_parity.cpp +++ b/src/kernels/kv_stream_parity.cpp @@ -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 +49,13 @@ template T* halloc(size_t n) { // pinned, mapped; returns the dev struct Pools { // one K/V pool set of `pages` pages k::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(b) : dalloc(b); + p.v_q4 = host ? halloc(b) : dalloc(b); + } else if (fmt == k::kKvInt8) { p.k_q = host ? halloc(rows * s.head_dim) : dalloc(rows * s.head_dim); p.v_q = host ? halloc(rows * s.head_dim) : dalloc(rows * s.head_dim); p.k_scale = host ? halloc(rows * 4) : dalloc(rows * 4); @@ -63,14 +68,15 @@ struct Pools { // one K/V pool set of `pages` pages 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 +102,19 @@ std::vector selection(int64_t n_kv, int64_t width, std::mt19937& rng) { return 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 < blocks const 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 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(n_blocks); { std::vector t(n_blocks); @@ -143,8 +150,8 @@ bool run(bool int8) { 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 selection const int n_q = 1 + (int) (rng() % NQ); @@ -163,13 +170,13 @@ bool run(bool int8) { 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 itself ck(cudaMemcpy(pt.data(), m.page_table, n_blocks * 4, cudaMemcpyDeviceToHost), "pt"); @@ -188,7 +195,7 @@ bool run(bool int8) { } 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 +203,10 @@ bool run(bool int8) { { 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(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 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 +218,7 @@ bool run(bool int8) { 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 +227,8 @@ bool run(bool int8) { 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 --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index d2c8aa21..7419dc31 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -10,6 +10,7 @@ #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/qsa_select.hpp" @@ -133,7 +134,10 @@ void take_stage(Alloc& o_borrowed, const core::SessionState& ss, const strata::k own.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(rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), ok); + st.v_q4 = o.take(rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), ok); + } else if (q0.kv_int8) { st.k_q = o.take(rows * s.head_dim, ok); st.v_q = o.take(rows * s.head_dim, ok); st.k_scale = o.take(rows * (s.head_dim / 64), ok); @@ -146,6 +150,7 @@ void take_stage(Alloc& o_borrowed, const core::SessionState& ss, const strata::k 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; } @@ -424,14 +429,23 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e // 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, + &st.host, staged ? &m.stage : nullptr); + } else { + 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); 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 +540,7 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e 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); 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 --git a/src/program/generate.cpp b/src/program/generate.cpp index 21569114..ec781633 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -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 +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 +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 == "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"); // 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 +1255,16 @@ int main(int argc, char** argv) { (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 +2699,19 @@ int main(int argc, char** argv) { 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> 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(((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 +2719,7 @@ int main(int argc, char** argv) { 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{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 +2727,7 @@ int main(int argc, char** argv) { const strata::core::QsaState& ms = mtp.kv_state(); uint64_t h_mtp = 1469598103934665603ull; const int64_t mL = std::min(L, ms.max_cells); - const bool mh = ms.kv_mode != 0; - for (const auto& [pool, w] : {std::pair{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,