From 3597c47ff8cd490dccfdafa2bd9d9b80ba9aa255 Mon Sep 17 00:00:00 2001 From: orange Date: Tue, 29 Sep 2026 09:12:45 -0500 Subject: [PATCH] Hybrid K8V4 KV cache: INT8 K + Hadamard-rotated Q4_0 V (--kv k8v4) K stays INT8 (unrotated - the attention scores stay exactly int8's), V uses the rotated q4_0 of kv_q4.hpp: 816 B per cell vs int8's 1,056. The K/V quantization asymmetry is the point: K enters through the softmax scores, V only through a softmax-weighted average (llama.cpp's q8_K/q4_V hybrids reason the same way). No new kernels: the append/gather entry points already select K/V by blockIdx.z and take separate K/V pointers, so the hybrid composes the existing validated q8/q4 kernels with the unused half's lanes folded onto the used pool (a bit-identical duplicate write). The fused attention gets KV_MODE 3 (K-side int8 loader, V-side q4); 0.1.22's tensor-core prompt path (qsa_prompt_attn) refuses the hybrid pools through its !v_q check and the old kernel runs - covered by the parity test. The MTP drafter stays INT8 (mtp.cpp toggles the format globals around its state creation, any ring shape); qsa_kv_format exits on a hybrid state rather than misreporting a layout (the kernels' own unsupported-geometry convention); the hybrid appends pass nullptr for the host mirror (mode 0 has none). setup.py excludes k8v4 from the whole auto-streaming decision (the engine refuses --kv-resident with it). kv_hybrid_parity: bitwise append/gather through a non-identity page table, step and batched mode-3 attention vs host references (<= 1.1e-07), and the qsa_prompt_attn refusal - all at machine precision; kv_q8/kv_q4 parity unchanged. Measured on a RTX 3090, Coder IQ1_M, 118.75k-token prompts, temp 0: decode 82-97 t/s (int8: 75; the band is draft-acceptance variance), prefill unchanged ~1,130-1,170 t/s, 26-needle seed 42 identical to int8's tokens, KV 1.39 GB at 131k (int8: 1.80). At --max-context 204800 on 24 GB: 1,024 t/s prefill, 82-91 t/s decode, 25/26 needles at 197.9k. --- CMakeLists.txt | 4 + include/strata/core/layer.hpp | 15 ++ setup.py | 15 +- src/core/layer.cpp | 69 ++++-- src/core/mtp.cpp | 8 + src/core/verify.cpp | 11 +- src/kernels/cuda/qsa_decode_attn.cu | 101 ++++---- src/kernels/kv_hybrid_parity.cpp | 343 ++++++++++++++++++++++++++++ src/prefill/prefill.cpp | 11 +- src/program/generate.cpp | 15 +- 10 files changed, 527 insertions(+), 65 deletions(-) create mode 100644 src/kernels/kv_hybrid_parity.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 130e04bd..e3da8964 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -387,6 +387,10 @@ if(STRATA_ENABLE_CUDA) 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_hybrid_parity src/kernels/kv_hybrid_parity.cpp) + target_include_directories(kv_hybrid_parity PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) + target_link_libraries(kv_hybrid_parity PRIVATE strata_kernels CUDA::cudart) + add_test(NAME kv_hybrid_parity COMMAND kv_hybrid_parity) 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) diff --git a/include/strata/core/layer.hpp b/include/strata/core/layer.hpp index fe966bfb..1669256f 100644 --- a/include/strata/core/layer.hpp +++ b/include/strata/core/layer.hpp @@ -40,6 +40,8 @@ #include "strata/kernels/ngram.hpp" #include "strata/kernels/ple.hpp" +#include +#include #include #include @@ -211,6 +213,10 @@ struct QsaState { bool kv_q4 = false; uint8_t* k_q4 = nullptr; uint8_t* v_q4 = nullptr; + /// Hybrid K8V4: K in INT8 (unrotated - the scores stay exact), V in rotated Q4_0 (kv_q4.hpp): 816 B per cell. + /// Uses k_q/k_scale + v_q4. Mode 0 only (no KV streaming, no ring); under this setting the MTP drafter's + /// ring state stays plain INT8, so the block movers never see the hybrid layout. + bool kv_hybrid = false; 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; @@ -276,8 +282,17 @@ 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(); +/// Hybrid K8V4 (`--kv k8v4`): K in INT8, V in rotated Q4_0 - 816 B per cell. Not with --kv-resident. +void qsa_set_kv_hybrid(bool enabled); +bool qsa_kv_hybrid(); /// 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) { + // A hybrid K8V4 state is mode 0 only and never reaches the block movers; refuse rather than let it + // fall through to kKvF16 - a wrong layout silently applied is worse than a hard stop (PR review). + if (st.kv_hybrid) { + std::fprintf(stderr, "strata: qsa_kv_format: a hybrid K8V4 state must never reach the block movers\n"); + std::exit(1); // the kernels' own "unsupported geometry" convention (kv_q8.cu, qsa_decode_attn.cu) + } 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, diff --git a/setup.py b/setup.py index e9b07f50..8c61587a 100644 --- a/setup.py +++ b/setup.py @@ -1283,9 +1283,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("--kv", choices=["int8", "q4_0", "k8v4"], + help="KV cache precision above 8K context: int8 (default), q4_0 (half the memory, a little less " + "precise) or k8v4 (hybrid: INT8 K + 4-bit V, 816 B/cell)") 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("--experimental-speed-projection", metavar="on|off|GGUF", @@ -1637,8 +1637,13 @@ def main() -> int: # 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 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 - # the RAM copy must be pinned, and under WSL the NVIDIA driver pins only about 1 GB in all - if is_wsl() and ctx >= 65536: + # Hybrid K8V4 never streams its KV (mode 0 only, layer.hpp), so it is excluded from the WHOLE streaming + # decision rather than one threshold at a time - a future tier added to this chain cannot reintroduce the + # combination the engine refuses (PR review). + if kv == "k8v4": + if ctx >= 65536: + ok("KV streaming off: not supported with --kv k8v4; the KV cache stays in VRAM") + elif is_wsl() and ctx >= 65536: ok("WSL: KV streaming off (the driver pins only about 1 GB of RAM); the KV cache stays in VRAM") elif ctx >= 65536 and ram >= MODELS[model]["ram_gb"] + kv_ram_gb + 1: args += ["--kv-resident", "32768"] diff --git a/src/core/layer.cpp b/src/core/layer.cpp index bfc2a327..5c6c06ef 100644 --- a/src/core/layer.cpp +++ b/src/core/layer.cpp @@ -172,11 +172,13 @@ 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, g_kv_q4 = false; } +namespace { bool g_kv_int8 = false, g_kv_q4 = false, g_kv_hybrid = 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; } +void qsa_set_kv_hybrid(bool enabled) { g_kv_hybrid = enabled; } +bool qsa_kv_hybrid() { return g_kv_hybrid; } 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,10 +509,15 @@ 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) { +uint64_t kv_pool_bytes(const QsaShapes& s, int64_t pages, bool hybrid, bool int8) { + if (hybrid) { // K8V4: the INT8 K half (codes + scales) plus the Q4_0 V half (kv_q4.hpp's rotation) + const uint64_t rows = (uint64_t) pages * s.page_size * s.n_head_kv; + return rows * (uint64_t) s.head_dim + rows * (uint64_t) (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2 + + rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim) + 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; + return 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; } } // namespace @@ -523,7 +530,8 @@ uint64_t qsa_state_bytes(const ModelGeometry& g, int64_t max_cells, bool with_ro const QsaShapes s = qsa_shapes(g); const KvPlan p = kv_plan(s, max_cells, ring_cells); uint64_t n = 0; - n += kv_pool_bytes(s, p.slots) + 4 * 16; // K/V pools (the VRAM slots) + n += kv_pool_bytes(s, p.slots, g_kv_hybrid && ring_cells <= 0, + g_kv_int8 || g_kv_hybrid) + 4 * 16; // K/V pools (the VRAM slots) n += (uint64_t) p.pages * 4; // page_table if (p.mode == 1) n += strata::kernels::kv_stream_map_bytes(p.slots) + 6 * 16; // the residency map n += (uint64_t) (s.idx_block - 1) * s.idx_dim * 4; // tail @@ -544,14 +552,29 @@ uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, Q Cursor c{(uint8_t*) base}; st.kv_int8 = g_kv_int8 && !g_kv_q4; st.kv_q4 = g_kv_q4; + // Hybrid K8V4, main layers only (the drafter's state is created with the globals toggled to INT8 - + // mtp.cpp). Streamed mode is refused outright; generate.cpp validates it too, this is the backstop. + if (g_kv_hybrid && ring_cells <= 0) { + if (p.mode == 1) { + std::fprintf(stderr, "strata: hybrid K8V4 KV does not support --kv-resident streaming\n"); + return 0; + } + st.kv_hybrid = true; + st.kv_int8 = false; + st.kv_q4 = false; + } 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 const uint64_t q4_row = strata::kernels::kv_q4_bytes_per_head((int) s.head_dim); - if (st.kv_q4) { + if (st.kv_hybrid) { + st.k_q = c.take(rows * s.head_dim); + st.k_scale = c.take(rows * (s.head_dim / strata::kernels::KV_Q8_GROUP)); + st.v_q4 = c.take(rows * q4_row); + } else 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) { + } else if (st.kv_int8) { // st, not the global: the drafter's ring is INT8 under --kv k8v4 too 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)); @@ -619,7 +642,7 @@ uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, Q 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) { + } else if (st.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)); @@ -658,7 +681,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_q4) { + if (st.kv_hybrid) { + cudaMemsetAsync(st.k_q, 0, rows * s.head_dim, cs); + cudaMemsetAsync(st.k_scale, 0, rows * (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2, cs); + cudaMemsetAsync(st.v_q4, 0, rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), cs); + } else 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) { @@ -682,7 +709,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_q4) { pools.k_q4 = st.k_q4; pools.v_q4 = st.v_q4; } + if (st.kv_hybrid) { pools.k_q = st.k_q; pools.k_scale = st.k_scale; pools.v_q4 = st.v_q4; } + else 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; @@ -863,11 +891,18 @@ 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_q4) { +if (st.kv_hybrid) { + // K8V4: only V is rotated (kv_q4.hpp's H); the scores pair unrotated q with unrotated INT8 K, and the + // output - a mix of rotated values - is rotated back after attention. Each append/gather call folds the + // unused half's lanes onto the used pool (a bit-identical duplicate write), so no kernel variants exist. + strata::kernels::fwht256_inplace_cuda(b.vcur, g.n_head_kv, stream); + kv_append_q8_step(st.k_q, st.k_q, st.k_scale, st.k_scale, st.page_table, st.step, b.kcur, b.kcur, s, stream, nullptr); // mode 0: no host mirror + strata::kernels::kv_append_q4_step(st.v_q4, st.v_q4, st.page_table, st.step, b.vcur, b.vcur, s, stream, nullptr); +} else 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()) { +} 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_hybrid) dump_slot(dump, g, layer, (const float*) st.k_pool, base, nvk / 2, stream); if (!st.kv_int8 && !st.kv_hybrid) 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); @@ -906,7 +941,13 @@ int64_t max_blocks = (st.max_cells / s.idx_block) + 2; 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_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); + if (st.kv_hybrid) { + kv_gather_q8_step(st.k_q, st.k_q, st.k_scale, st.k_scale, st.page_table, b.ids, st.step, cap, s, + b.k_scratch, b.k_scratch, stream); + strata::kernels::kv_gather_q4_step(st.v_q4, st.v_q4, st.page_table, b.ids, st.step, cap, s, + b.v_scratch, b.v_scratch, stream); + } + else 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"; @@ -922,7 +963,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 + if (st.kv_q4 || st.kv_hybrid) 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 23a03ef9..11d16f79 100644 --- a/src/core/mtp.cpp +++ b/src/core/mtp.cpp @@ -201,6 +201,12 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session // window (plus the cells a round writes ahead of its queries) over a host copy, refilled on a resume. The host copy // is pinned after the expert arena has pinned what it could: if it does not fit, the K/V stays whole in VRAM. int64_t ring = (window > 0 && window < max_cells) ? window + 4 * (int64_t) max_t + 64 : 0; + // K8V4 never applies to the drafter: its own attention paths (below, and verify.cpp) handle whole formats + // only, whatever ring shape it takes (0, a window, or the -1 fully-resident fallback). + const bool kv_hybrid_was = qsa_kv_hybrid(); + const bool kv_int8_was = qsa_kv_int8(); + qsa_set_kv_hybrid(false); + if (kv_hybrid_was) qsa_set_kv_int8(true); // the drafter under --kv k8v4: plain INT8 uint64_t sb = qsa_state_bytes(g, max_cells, false, ring); if (cudaMalloc(&state_arena_, sb) != cudaSuccess) { err = "mtp: the K/V state does not fit"; return false; } if (qsa_state_init(g, max_cells, state_arena_, st_, &ss.qsa_states[0], ring) == 0) { @@ -214,6 +220,8 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session if (cudaMalloc(&state_arena_, sb) != cudaSuccess) { err = "mtp: the K/V state does not fit"; return false; } if (qsa_state_init(g, max_cells, state_arena_, st_, &ss.qsa_states[0], ring) == 0) { err = "mtp: state init failed"; return false; } } + qsa_set_kv_int8(kv_int8_was); + qsa_set_kv_hybrid(kv_hybrid_was); qsa_state_zero(st_, g, nullptr); cudaDeviceSynchronize(); vram_ += sb; diff --git a/src/core/verify.cpp b/src/core/verify.cpp index 29643d6d..542ec8dc 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -510,12 +510,19 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { 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); + } else if (st.kv_hybrid) { // K8V4: only V is rotated + fwht256_inplace_cuda(vcur_ + tb * NKV * HD, (int64_t) n * NKV, cs); } stamp(l, 8, grp); 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_q4) + if (st.kv_hybrid) { // K8V4: the unused half's lanes folded onto the used pool (layer.cpp) + kv_append_q8_step(st.k_q, st.k_q, st.k_scale, st.k_scale, st.page_table, step_t, + kcur_ + t * NKV * HD, kcur_ + t * NKV * HD, s, cs, nullptr); + kv_append_q4_step(st.v_q4, st.v_q4, st.page_table, step_t, vcur_ + t * NKV * HD, + vcur_ + t * NKV * HD, s, cs, nullptr); + } else 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) @@ -573,7 +580,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { 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); stamp(l, 13, grp); - if (st.kv_q4) fwht256_inplace_cuda(attn_ + tb * NH * HD, (int64_t) n * NH, cs); // back: H^-1 = H + if (st.kv_q4 || st.kv_hybrid) fwht256_inplace_cuda(attn_ + tb * NH * HD, (int64_t) n * NH, cs); // back: H^-1 = H if (qb) native_qsa_gate_apply(attn_ + tb * NH * HD, qfull_ + tb * NH * 2 * HD, attn32_ + tb * NH * HD, (int) (n * NH), (int) HD, cs); else diff --git a/src/kernels/cuda/qsa_decode_attn.cu b/src/kernels/cuda/qsa_decode_attn.cu index 1f967a07..9f7fb884 100644 --- a/src/kernels/cuda/qsa_decode_attn.cu +++ b/src/kernels/cuda/qsa_decode_attn.cu @@ -31,42 +31,53 @@ __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). +// Per-format bodies; `load8` below is the KV_MODE dispatcher. value=false is the K side, true the V side. +__device__ __forceinline__ void load8_f16(const QsaAttnPools& p, bool value, long long row, int d0, float* out) { + 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); +#pragma unroll + for (int j = 0; j < 4; ++j) { + const float2 f = __half22float2(h2[j]); + out[2 * j] = f.x; + out[2 * j + 1] = f.y; + } +} +__device__ __forceinline__ void load8_q8(const QsaAttnPools& p, bool value, long long row, int d0, float* out) { + 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)); + const uint2 raw = *reinterpret_cast(codes); + const int8_t* c = reinterpret_cast(&raw); +#pragma unroll + for (int j = 0; j < 8; ++j) out[j] = (float) c[j] * sc; +} +__device__ __forceinline__ void load8_q4(const QsaAttnPools& p, bool value, long long row, int d0, float* out) { + 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 __device__ __forceinline__ void load8(const QsaAttnPools& p, bool value, long long row, int d0, float* out) { - 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); -#pragma unroll - for (int j = 0; j < 4; ++j) { - const float2 f = __half22float2(h2[j]); - out[2 * j] = f.x; - out[2 * j + 1] = f.y; - } - } 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)); - const uint2 raw = *reinterpret_cast(codes); - 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; - } - } + if constexpr (KV_MODE == 0) load8_f16(p, value, row, d0, out); + else if constexpr (KV_MODE == 1) load8_q8(p, value, row, d0, out); + else if constexpr (KV_MODE == 3) { + // hybrid K8V4: both sides are defined - K unrotated INT8, V rotated Q4_0 - so a value=true call + // reads the Q4_0 pool instead of dereferencing the null v_q (no call site does today; PR review) + if (value) load8_q4(p, value, row, d0, out); + else load8_q8(p, value, row, d0, out); + } else load8_q4(p, value, row, d0, out); } template @@ -149,7 +160,7 @@ __global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __rest } 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 { + } else { // modes 2 and 3: V is rotated Q4_0 (kv_q4.hpp); the caller rotates the output back constexpr int bytes_per_head = (HD / QK4_0) * sizeof(block_q4_0); const int b = t / QK4_0; const int rem = t % QK4_0; @@ -202,7 +213,8 @@ 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 int kv_mode = pools.k_q4 != nullptr ? 2 : (pools.k_q != nullptr ? 1 : 0); + const int kv_mode = pools.k_q4 != nullptr ? 2 : (pools.k_q != nullptr && pools.v_q4 != nullptr ? 3 + : (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); @@ -212,7 +224,10 @@ 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 (kv_mode == 2) + if (kv_mode == 3) + attn_chunk_kernel<3><<>>(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 == 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) @@ -242,8 +257,11 @@ 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 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))) { + const int kv_mode = pools.k_q4 != nullptr ? 2 : (pools.k_q != nullptr && pools.v_q4 != nullptr ? 3 + : (pools.k_q != nullptr ? 1 : 0)); + if (kv_mode == 3 ? (!pools.k_scale || !pools.v_q4) + : (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); } @@ -254,7 +272,10 @@ 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 (kv_mode == 2) + if (kv_mode == 3) + attn_chunk_kernel<3><<>>(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 == 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) diff --git a/src/kernels/kv_hybrid_parity.cpp b/src/kernels/kv_hybrid_parity.cpp new file mode 100644 index 00000000..1e05a80a --- /dev/null +++ b/src/kernels/kv_hybrid_parity.cpp @@ -0,0 +1,343 @@ +// src/kernels/kv_hybrid_parity.cpp - hybrid K8V4 KV against host references (GPU, no model). +// +// Exercises the EXACT composed calls the engine's hybrid path makes (layer.cpp / prefill.cpp): the q8/q4 +// append and gather kernels invoked with the unused half's pointers folded onto the used pool, and the +// fused decode attention's KV_MODE 3 (INT8 K, rotated Q4_0 V) followed by the output's inverse Hadamard. +// 1. K: INT8 codes + FP16 scales bitwise vs the host reference (kv_q8.hpp's rules); +// 2. V: after fwht256, Q4_0 blocks bitwise vs the host reference (kv_q4.hpp's rules, PR #21); +// 3. the composed gathers bitwise vs the host dequantization of those codes; +// 4. qsa_decode_attn<3> + output fwht vs a host attention over the SAME dequantized K/V (fp32 math), and +// bounded against the fp32-true attention from the unquantized K/V. +#include "strata/kernels/f16_bits.hpp" +#include "strata/kernels/kv_q4.hpp" +#include "strata/kernels/kv_q8.hpp" +#include "strata/kernels/qsa.hpp" +#include "strata/kernels/qsa_decode_attn.hpp" +#include "strata/kernels/qsa_prompt_attn.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, "%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; +} + +// kv_q4_parity.cpp's exact CPU references. +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; + for (int i = 0; i < n; ++i) x[i] *= scale; +} +void quantize_block_q4_0_host(const float* x, k::block_q4_0& blk) { + float amax = 0.0f, 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 int q0 = (int) (x[i] * id + 8.5f); + const int q1 = (int) (x[i + 16] * id + 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_hybrid_parity test ===\n"); + k::QsaShapes s = k::qsa_real_shapes(); + s.page_size = 64; + const int H = (int) s.n_head_kv, D = (int) s.head_dim, P = (int) s.page_size, G = D / k::KV_Q8_GROUP; + const int QH = (int) s.n_head, PER = QH / H; // query heads per KV head + const int pages = 24, cells = pages * P; // n_chunks >= n_head: the batched merge overlaps queries below that + std::mt19937 rng(17); + std::normal_distribution nd(0.0f, 1.0f); + + std::vector table(pages); + for (int i = 0; i < pages; ++i) table[i] = (i * 5 + 3) % pages; + int32_t* d_table = dalloc(pages); + ck(cudaMemcpy(d_table, table.data(), pages * 4, cudaMemcpyHostToDevice), "table"); + + std::vector K((size_t) cells * H * D), V((size_t) cells * H * D); + for (auto& x : K) x = nd(rng) * 0.5f; + for (auto& x : V) x = nd(rng) * 0.5f; + + // ---- host reference: K in INT8 (kv_q8.hpp), rotated V in Q4_0 (kv_q4.hpp) + std::vector rk((size_t) cells * H * D); + std::vector rk_s((size_t) cells * H * G); + for (int c = 0; c < cells; ++c) + for (int h = 0; h < H; ++h) + for (int g = 0; g < G; ++g) { + float amax = 0.0f; + for (int t = 0; t < k::KV_Q8_GROUP; ++t) + amax = std::max(amax, std::fabs(K[((size_t) c * H + h) * D + g * k::KV_Q8_GROUP + t])); + const uint16_t sb = k::f16_from_f32(amax / 127.0f); + const float sf = k::f32_from_f16(sb); + for (int t = 0; t < k::KV_Q8_GROUP; ++t) { + int q = 0; + if (sf > 0.0f) { + q = (int) std::nearbyint(K[((size_t) c * H + h) * D + g * k::KV_Q8_GROUP + t] / sf); // rn: ties to even, as the kernel + q = std::max(-127, std::min(127, q)); + } + rk[((size_t) c * H + h) * D + g * k::KV_Q8_GROUP + t] = (int8_t) q; + } + rk_s[((size_t) c * H + h) * G + g] = sb; + } + std::vector Vrot((size_t) cells * H * D); + std::memcpy(Vrot.data(), V.data(), V.size() * 4); + for (int c = 0; c < cells * H; ++c) fwht256_host_reference(Vrot.data() + (size_t) c * D); + std::vector rv4((size_t) cells * H * (D / 32)); + for (int c = 0; c < cells; ++c) + for (int h = 0; h < H; ++h) + for (int b = 0; b < D / 32; ++b) + quantize_block_q4_0_host(&Vrot[((size_t) c * H + h) * D + b * 32], + rv4[((size_t) c * H + h) * (D / 32) + b]); + + // ---- device: one cell appended through the COMPOSED hybrid calls, then gathered + const int64_t q4_row = (int64_t) k::kv_q4_bytes_per_head(D); + int8_t* d_kq = dalloc((size_t) cells * H * D); + uint16_t* d_ks = dalloc((size_t) cells * H * G); + uint8_t* d_v4 = dalloc((size_t) cells * H * q4_row); + float *d_kcur = dalloc((size_t) H * D), *d_vcur = dalloc((size_t) H * D); + int32_t* d_step = dalloc(k::kStepCount); + + int append_bad = 0, gather_bad = 0; + for (int c = 0; c < cells; ++c) { + ck(cudaMemcpy(d_kcur, &K[(size_t) c * H * D], (size_t) H * D * 4, cudaMemcpyHostToDevice), "kcur"); + ck(cudaMemcpy(d_vcur, &V[(size_t) c * H * D], (size_t) H * D * 4, cudaMemcpyHostToDevice), "vcur"); + int32_t step[k::kStepCount]; + k::qsa_step_fill(step, c, s); + ck(cudaMemcpy(d_step, step, sizeof step, cudaMemcpyHostToDevice), "step"); + // exactly what qsa_layer's hybrid branch does + k::fwht256_inplace_cuda(d_vcur, H, nullptr); + k::kv_append_q8_step(d_kq, d_kq, d_ks, d_ks, d_table, d_step, d_kcur, d_kcur, s, nullptr, nullptr); + k::kv_append_q4_step(d_v4, d_v4, d_table, d_step, d_vcur, d_vcur, s, nullptr, nullptr); + ck(cudaGetLastError() != cudaSuccess ? cudaGetLastError() : cudaSuccess, "append"); + } + ck(cudaDeviceSynchronize(), "append sync"); + + std::vector hk((size_t) cells * H * D); + std::vector hks((size_t) cells * H * G); + std::vector hv4((size_t) cells * H * q4_row); + ck(cudaMemcpy(hk.data(), d_kq, hk.size(), cudaMemcpyDeviceToHost), "kq"); + ck(cudaMemcpy(hks.data(), d_ks, hks.size() * 2, cudaMemcpyDeviceToHost), "ks"); + ck(cudaMemcpy(hv4.data(), d_v4, hv4.size(), cudaMemcpyDeviceToHost), "v4"); + // the pools are PHYSICAL (page, head, slot); the reference is by LOGICAL cell - compare through the table + const k::block_q4_0* hv4b = reinterpret_cast(hv4.data()); + for (int c = 0; c < cells; ++c) { + const long long row = ((long long) table[c / P] * H); + for (int h = 0; h < H; ++h) { + const long long r = (row + h) * P + c % P; + for (int d = 0; d < D; ++d) + if (hk[(size_t) r * D + d] != rk[((size_t) c * H + h) * D + d]) ++append_bad; + for (int g = 0; g < G; ++g) + if (hks[(size_t) r * G + g] != rk_s[((size_t) c * H + h) * G + g]) ++append_bad; + for (int b = 0; b < D / 32; ++b) { + const k::block_q4_0& got = hv4b[(size_t) r * (D / 32) + b]; + if (got.d != rv4[((size_t) c * H + h) * (D / 32) + b].d || + std::memcmp(got.qs, rv4[((size_t) c * H + h) * (D / 32) + b].qs, 16) != 0) ++append_bad; + } + } + } + std::printf("[1/3] composed appends: %s (%d bad values of %zu K / %zu V)\n", + append_bad == 0 ? "PASS" : "FAIL", append_bad, hk.size(), rv4.size()); + + // gather every cell (ids = all, ascending - the identity selection for width = cells) + std::vector ids(cells); + for (int i = 0; i < cells; ++i) ids[i] = i; + int32_t* d_ids = dalloc(cells); + ck(cudaMemcpy(d_ids, ids.data(), cells * 4, cudaMemcpyHostToDevice), "ids"); + int32_t step[k::kStepCount]; + k::qsa_step_fill(step, cells - 1, s); + step[k::kStepWidth] = cells; // select everything + ck(cudaMemcpy(d_step, step, sizeof step, cudaMemcpyHostToDevice), "step2"); + uint16_t *d_ksc = dalloc((size_t) cells * H * D), *d_vsc = dalloc((size_t) cells * H * D); + k::kv_gather_q8_step(d_kq, d_kq, d_ks, d_ks, d_table, d_ids, d_step, cells, s, d_ksc, d_ksc, nullptr); + k::kv_gather_q4_step(d_v4, d_v4, d_table, d_ids, d_step, cells, s, d_vsc, d_vsc, nullptr); + ck(cudaDeviceSynchronize(), "gather sync"); + std::vector h_ksc((size_t) cells * H * D), h_vsc((size_t) cells * H * D); + ck(cudaMemcpy(h_ksc.data(), d_ksc, h_ksc.size() * 2, cudaMemcpyDeviceToHost), "ksc"); + ck(cudaMemcpy(h_vsc.data(), d_vsc, h_vsc.size() * 2, cudaMemcpyDeviceToHost), "vsc"); + for (int c = 0; c < cells; ++c) + for (int h = 0; h < H; ++h) + for (int d = 0; d < D; ++d) { + const float kref = k::f32_from_f16(k::f16_from_f32( + (float) rk[((size_t) c * H + h) * D + d] * k::f32_from_f16(rk_s[((size_t) c * H + h) * G + d / k::KV_Q8_GROUP]))); + if (k::f32_from_f16(h_ksc[((size_t) c * H + h) * D + d]) != kref) ++gather_bad; + const k::block_q4_0& b = rv4[((size_t) c * H + h) * (D / 32) + d / 32]; + const int nib = d % 32 < 16 ? (b.qs[d % 32] & 0x0F) - 8 : ((b.qs[d % 32 - 16] >> 4) - 8); + const float vref = k::f32_from_f16(k::f16_from_f32((float) nib * k::f32_from_f16(b.d))); + if (k::f32_from_f16(h_vsc[((size_t) c * H + h) * D + d]) != vref) ++gather_bad; + } + std::printf("[2/3] composed gathers: %s (%d bad of %zu)\n", + gather_bad == 0 ? "PASS" : "FAIL", gather_bad, h_ksc.size()); + + // ---- attention: qsa_decode_attn KV_MODE 3 over the hybrid pools + output fwht, vs fp32 references + std::vector q((size_t) QH * D); + for (auto& x : q) x = nd(rng); + float* d_q = dalloc(q.size()); + ck(cudaMemcpy(d_q, q.data(), q.size() * 4, cudaMemcpyHostToDevice), "q"); + k::QsaAttnPools pools; + pools.k_q = d_kq; pools.k_scale = d_ks; pools.v_q4 = d_v4; pools.page_table = d_table; + float* d_scr = dalloc(k::qsa_decode_attn_scratch_floats(cells, s) + 16); + float* d_attn = dalloc((size_t) QH * D); + k::qsa_decode_attn_step(d_q, pools, d_ids, d_step, cells, s, d_scr, d_attn, nullptr); + k::fwht256_inplace_cuda(d_attn, QH, nullptr); // the engine's inverse rotation of the output + ck(cudaDeviceSynchronize(), "attn sync"); + std::vector h_attn((size_t) QH * D); + ck(cudaMemcpy(h_attn.data(), d_attn, h_attn.size() * 4, cudaMemcpyDeviceToHost), "attn"); + + // reference A: attention over the SAME dequantized K/V (isolates the kernel; fp32 host math) + // reference B: attention over the TRUE unquantized K/V (bounds the format's error) + auto host_attn = [&](const std::vector& Keq, const std::vector& Veq, std::vector& out) { + out.assign((size_t) QH * D, 0.0f); + for (int h = 0; h < QH; ++h) { + const int kvh = h / PER; + std::vector sc(cells); + float m = -1e30f; + for (int c = 0; c < cells; ++c) { + float d_ = 0.0f; + for (int t = 0; t < D; ++t) + d_ += q[(size_t) h * D + t] * Keq[((size_t) c * H + kvh) * D + t]; + sc[c] = d_ / std::sqrt((float) D); + m = std::max(m, sc[c]); + } + float l = 0.0f; + for (int c = 0; c < cells; ++c) { sc[c] = std::exp(sc[c] - m); l += sc[c]; } + for (int c = 0; c < cells; ++c) + for (int t = 0; t < D; ++t) out[(size_t) h * D + t] += sc[c] / l * Veq[((size_t) c * H + kvh) * D + t]; + } + }; + std::vector Kdq((size_t) cells * H * D), Vdq((size_t) cells * H * D); + for (int c = 0; c < cells; ++c) + for (int h = 0; h < H; ++h) + for (int d = 0; d < D; ++d) { + Kdq[((size_t) c * H + h) * D + d] = + (float) rk[((size_t) c * H + h) * D + d] * k::f32_from_f16(rk_s[((size_t) c * H + h) * G + d / k::KV_Q8_GROUP]); + const k::block_q4_0& b = rv4[((size_t) c * H + h) * (D / 32) + d / 32]; + const int nib = d % 32 < 16 ? (b.qs[d % 32] & 0x0F) - 8 : ((b.qs[d % 32 - 16] >> 4) - 8); + Vdq[((size_t) c * H + h) * D + d] = (float) nib * k::f32_from_f16(b.d); + } + // un-rotate the dequantized V (the kernel returns the output in the UNROTATED domain) + std::vector Vdq_un(Vdq.size()); + std::memcpy(Vdq_un.data(), Vdq.data(), Vdq.size() * 4); + for (int c = 0; c < cells * H; ++c) fwht256_host_reference(Vdq_un.data() + (size_t) c * D); + + // ---- batched form with TWO queries and per-query step arrays (the verify.cpp window's exact call) + { + const int nq = 2; + std::vector q2((size_t) nq * QH * D); + for (auto& x : q2) x = nd(rng); + float* d_q2 = dalloc(q2.size()); + ck(cudaMemcpy(d_q2, q2.data(), q2.size() * 4, cudaMemcpyHostToDevice), "q2"); + // the batched kernel indexes ids[z * cap + ...]: one FULL selection per query + std::vector ids2((size_t) nq * cells); + for (int i = 0; i < nq; ++i) for (int c = 0; c < cells; ++c) ids2[(size_t) i * cells + c] = c; + int32_t* d_ids2 = dalloc((size_t) nq * cells); + ck(cudaMemcpy(d_ids2, ids2.data(), ids2.size() * 4, cudaMemcpyHostToDevice), "ids2"); + int32_t* d_steps2 = dalloc(nq * k::kStepCount); + for (int i = 0; i < nq; ++i) { + int32_t st2[k::kStepCount]; + k::qsa_step_fill(st2, cells - 1 - i, s); + st2[k::kStepWidth] = cells - i; // slightly different widths, as verify's windows have + ck(cudaMemcpy(d_steps2 + i * k::kStepCount, st2, sizeof st2, cudaMemcpyHostToDevice), "steps2"); + } + float* d_scr2 = dalloc(k::qsa_decode_attn_scratch_floats(cells, s) * nq + 64); + float* d_at2 = dalloc((size_t) nq * QH * D); + k::qsa_decode_attn_batch(d_q2, pools, d_ids2, d_steps2, cells, s, d_scr2, d_at2, nq, nullptr); + k::fwht256_inplace_cuda(d_at2, (int64_t) nq * QH, nullptr); + ck(cudaDeviceSynchronize(), "attn2 sync"); + std::vector h_at2((size_t) nq * QH * D); + ck(cudaMemcpy(h_at2.data(), d_at2, h_at2.size() * 4, cudaMemcpyDeviceToHost), "at2"); + double max_b = 0.0; + double per_q[2] = {0.0, 0.0}; + for (int i = 0; i < nq; ++i) + for (int h = 0; h < QH; ++h) { + // reference over the cells this query's width selects (ids are ascending: the first width) + const int w = cells - i; + std::vector sc(w); + float m = -1e30f; + for (int c = 0; c < w; ++c) { + float d_ = 0.0f; + for (int t = 0; t < D; ++t) + d_ += q2[((size_t) i * QH + h) * D + t] * Kdq[((size_t) c * H + h / PER) * D + t]; + sc[c] = d_ / std::sqrt((float) D); + m = std::max(m, sc[c]); + } + float l = 0.0f; + for (int c = 0; c < w; ++c) { sc[c] = std::exp(sc[c] - m); l += sc[c]; } + for (int d = 0; d < D; ++d) { + float acc = 0.0f; + for (int c = 0; c < w; ++c) + acc += sc[c] / l * Vdq_un[((size_t) c * H + h / PER) * D + d]; // dim d only + const double e = (double) std::fabs(h_at2[((size_t) i * QH + h) * D + d] - acc); + max_b = std::max(max_b, e); + per_q[i] = std::max(per_q[i], e); + } + } + const bool bok = max_b < 5e-3; + std::printf(" (per-query max: q0 %.2e, q1 %.2e)\n", per_q[0], per_q[1]); + std::printf("[4/4] mode-3 BATCHED attention (verify's form): %s (vs dequant ref %.2e)\n", + bok ? "PASS" : "FAIL", max_b); + if (!bok) g_fail = 1; + } + + // The tensor-core prompt path (qsa_prompt_attn, 0.1.22+) supports fp16 and INT8 whole formats only; + // hybrid pools must make it refuse (its !v_q check) so the old mode-3 kernel runs - the guarantee the + // prefill fallback relies on, as a test (PR review). + { + float* d_q3 = dalloc((size_t) QH * D); + float* d_at3 = dalloc((size_t) QH * D); + const bool took = k::qsa_prompt_attn_batch(d_q3, pools, d_ids, d_step, cells, s, d_at3, 1, nullptr); + const bool refused = !took; + std::printf("[5/5] qsa_prompt_attn refuses hybrid pools: %s\n", refused ? "PASS (falls back)" : "FAIL"); + if (!refused) g_fail = 1; + } + + std::vector ref_deq, ref_true; + host_attn(Kdq, Vdq_un, ref_deq); + host_attn(K, V, ref_true); + double max_deq = 0.0, max_true = 0.0; + for (size_t i = 0; i < h_attn.size(); ++i) { + max_deq = std::max(max_deq, (double) std::fabs(h_attn[i] - ref_deq[i])); + max_true = std::max(max_true, (double) std::fabs(h_attn[i] - ref_true[i])); + } + const bool attn_ok = max_deq < 5e-3; // fp32 kernel math vs fp64-ish host accumulation + std::printf("[3/3] mode-3 attention + output fwht: %s (vs dequant ref %.2e, vs true fp32 %.2e)\n", + attn_ok ? "PASS" : "FAIL", max_deq, max_true); + + const bool ok = append_bad == 0 && gather_bad == 0 && attn_ok && g_fail == 0; + std::printf("=== kv_hybrid_parity: %s ===\n", ok ? "ALL PASS" : "FAILED"); + return ok ? 0 : 1; +} diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index e5c85077..4def74c2 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -1166,7 +1166,14 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e (p0 + s.page_size - 1) / s.page_size, s, m.cs); pt.mark(kPfQsa, cs); } - if (st.kv_q4) { // Q4_0 KV (kv_q4.hpp): rotated K and V, the queries below too, the output back + if (st.kv_hybrid) { // K8V4: K INT8 unrotated, V rotated Q4_0 (only V and the output rotate) + strata::kernels::fwht256_inplace_cuda(m.Vc, T * 2, m.cs); + kv_append(m.Kc, m.Kc, T, p0, st.page_table, s.page_size, nullptr, nullptr, + st.k_q, st.k_q, st.k_scale, st.k_scale, m.cs, nullptr, // mode 0: no host mirror + staged ? &m.stage : nullptr); + strata::kernels::kv_append_q4(st.v_q4, st.v_q4, st.page_table, p0, T, m.Vc, m.Vc, s, m.cs, + nullptr, staged ? &m.stage : nullptr); + } else 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, @@ -1319,7 +1326,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); + if (st.kv_q4 || st.kv_hybrid) strata::kernels::fwht256_inplace_cuda(m.attn, T * 24, m.cs); pt.mark(kPfQsa, 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; diff --git a/src/program/generate.cpp b/src/program/generate.cpp index ebfb2352..835a8520 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -326,6 +326,8 @@ void usage() { " 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 k8v4 hybrid: INT8 K (exact attention scores) + rotated Q4_0 V, 816 B/cell\n" + " (vs int8's 1,056); not with --kv-resident\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" @@ -1183,16 +1185,21 @@ int main(int argc, char** argv) { return 2; } 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"); + if (o.kv != "fp16" && o.kv != "int8" && o.kv != "q4_0" && o.kv != "k8v4") { + std::fprintf(stderr, "strata generate: --kv must be fp16, int8, q4_0 or k8v4\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) + strata::core::qsa_set_kv_hybrid(o.kv == "k8v4"); // K8V4: INT8 K + rotated Q4_0 V, 816 B/cell if (o.kv_resident < 0) { std::fprintf(stderr, "strata generate: --kv-resident must be >= 0\n"); return 2; } + if (o.kv == "k8v4" && o.kv_resident > 0) { + std::fprintf(stderr, "strata generate: --kv k8v4 does not support --kv-resident streaming (yet)\n"); + return 2; + } strata::core::qsa_set_kv_resident(o.kv_resident); // Prompt lookup (the suffix drafter, on by default): the MTP keeps its --spec windows and a lookup window may be // up to 2 tokens longer; the draft policy (strata/spec/draft_policy.hpp) takes one only where it pays. Code @@ -4169,6 +4176,10 @@ int main(int argc, char** argv) { 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 if (st.kv_hybrid) { + const int64_t q4b = (int64_t) strata::kernels::kv_q4_bytes_per_head((int) qs.head_dim); + a = {{h ? st.host.k_q : st.k_q, kvb}, {h ? st.host.v_q4 : st.v_q4, q4b}, + {h ? st.host.k_scale : st.k_scale, scb}}; } 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}};