From eb0803af7853a2a4277fafb32a43e90934a4fbcd Mon Sep 17 00:00:00 2001 From: Chen Bao Date: Thu, 1 Oct 2026 21:48:27 -0500 Subject: [PATCH] qsa_prompt_attn: Q4_0 K and V on tensor cores (mode 4) - long prompts with --kv q4_0 no longer take the old kernel The tensor-core prompt attention (D-1) refused Q4_0 pools, so --kv q4_0 read every prompt through the FP32 per-query kernel. Mode 4 is mode 1 (int8) with a scale per 32 values: each q4_0 block's 16 code bytes become 32 exact int8 codes (code - 8) at gather, its fp16 scale goes to the per-group scales, which are applied in FP32 as int8's are (q.k per 32-dim group; p.v folds each group's scale into p, two groups per warp). The p.v fold is bounded by the chunk's largest |scale|: q4_0 scales are signed (ggml's d = max / -8). The caller's rotation of q and of the output is unchanged. STRATA_PROMPT_ATTN_Q4=0: the old kernel (A/B). qsa_prompt_attn_parity gets Q4_0 cases with signed scales spread over two decades, as a pool holds them (32K and 1.5K contexts), against FP64 and the old kernel. --- include/strata/kernels/qsa_prompt_attn.hpp | 5 +- src/kernels/cuda/qsa_prompt_attn.cu | 102 ++++++++++++++++----- src/kernels/qsa_prompt_attn_parity.cpp | 46 ++++++++-- 3 files changed, 120 insertions(+), 33 deletions(-) diff --git a/include/strata/kernels/qsa_prompt_attn.hpp b/include/strata/kernels/qsa_prompt_attn.hpp index 37261a10..2391aaeb 100644 --- a/include/strata/kernels/qsa_prompt_attn.hpp +++ b/include/strata/kernels/qsa_prompt_attn.hpp @@ -14,7 +14,8 @@ // * q and p are split into FP16 hi + lo parts (two MMAs each), so they keep ~22 bits: the result differs from // the FP32 kernel by summation order and the exp2 rounding, not by an FP16 cast. // Not bitwise equal to `qsa_decode_attn_batch`; `qsa_prompt_attn_parity` bounds the difference and the prompt -// quality gate (needles, teacher-forced top-1) checks it end to end. Q4_0 KV is not handled (returns false). +// quality gate (needles, teacher-forced top-1) checks it end to end. Q4_0 KV (mode 4): each block's codes enter +// exactly as int8 and its scale (one per 32 values) in FP32, as int8 KV's do (STRATA_PROMPT_ATTN_Q4=0: the old kernel). #pragma once #include "strata/kernels/qsa_decode_attn.hpp" @@ -24,7 +25,7 @@ namespace strata::kernels { /// Same arguments and output as `qsa_decode_attn_batch` minus the scratch. Returns false (nothing launched) when the -/// pools are Q4_0 or the geometry is not 24 heads / 2 KV heads / 256: the caller then uses the old kernel. +/// geometry is not 24 heads / 2 KV heads / 256: the caller then uses the old kernel. bool qsa_prompt_attn_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, int64_t cap, const QsaShapes& s, float* attn, int64_t n_q, void* stream); diff --git a/src/kernels/cuda/qsa_prompt_attn.cu b/src/kernels/cuda/qsa_prompt_attn.cu index 4af82be2..889cb3de 100644 --- a/src/kernels/cuda/qsa_prompt_attn.cu +++ b/src/kernels/cuda/qsa_prompt_attn.cu @@ -78,18 +78,22 @@ __device__ __forceinline__ uint32_t pack_h2(float lo_k, float hi_k) { // eleme // KV_MODE 1: int8 codes + fp16 scale per 64 values. KV_MODE 0: fp16 values (scales 1). // KV_MODE 3 (hybrid K8V4): K as mode 1, V as mode 0 - the row's q4_0 blocks are dequantized to fp16 at // gather, so everything downstream of the load is the mode-0 V path; the caller un-rotates the output. +// KV_MODE 4 (Q4_0 K and V, `--kv q4_0`): mode 1 with a scale per 32 values - each q4_0 block's codes enter as exact +// int8 (code - 8) and its fp16 scale is applied in FP32, as mode 1's are; the caller rotates q and un-rotates the +// output (kv_q4.hpp). template struct Smem { using KElem = typename std::conditional::type; - using VElem = typename std::conditional::type; + using VElem = typename std::conditional::type; static constexpr int KROW = KV_MODE == 0 ? HD + 8 : HD + 16; // elements; 16-byte aligned rows, banks spread - static constexpr int VROW = KV_MODE == 1 ? HD + 16 : HD + 8; + static constexpr int VROW = (KV_MODE == 1 || KV_MODE == 4) ? HD + 16 : HD + 8; + static constexpr int NG = KV_MODE == 4 ? HD / QK4_0 : 4; // scale groups per row (q4_0: 8 of 32, else 4 of 64) __half qh[16][QS]; __half ql[16][QS]; KElem k[CH][KROW]; VElem v[CH][VROW]; - float ks[CH][4]; - float vs[CH][4]; + float ks[CH][NG]; + float vs[CH][NG]; float s[16][CH + 1]; float qmax[THREADS / 32]; float alpha[16]; @@ -154,7 +158,39 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_kernel(const float* __res __syncthreads(); // rows ready; the previous chunk's p.v is done with k, v, s // gather the chunk's K and V rows (16-byte pieces; K8V4's V as q4_0 blocks dequantized to fp16) // and their scales - { + if constexpr (KV_MODE == 4) { + // q4_0 K and V: one (K or V, cell, block) per item - the block's 16 code bytes (2-byte aligned: eight + // 16-bit loads) become 32 exact int8 codes (element j in the low nibble of byte j, j + 16 in the high + // one), its fp16 scale goes to ks/vs + constexpr int BLKS = HD / QK4_0; + constexpr int BYTES = BLKS * (int) sizeof(block_q4_0); + for (int i = t; i < 2 * CH * BLKS; i += THREADS) { + const int kv = i / (CH * BLKS), rem = i % (CH * BLKS), c = rem / BLKS, b = rem % BLKS; + const long long r = S.row[c]; + uint4 lo = make_uint4(0, 0, 0, 0), hi = make_uint4(0, 0, 0, 0); + float d = 0.0f; + if (r >= 0) { + const block_q4_0* blk = reinterpret_cast((kv == 0 ? p.k_q4 : p.v_q4) + r * BYTES) + b; + d = __half2float(__ushort_as_half(__ldg(&blk->d))); + const uint16_t* q16 = reinterpret_cast(blk->qs); + uint32_t w[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) + w[j] = (uint32_t) __ldg(q16 + 2 * j) | ((uint32_t) __ldg(q16 + 2 * j + 1) << 16); + // per byte: the low nibble minus 8 is element j, the high one minus 8 element j + 16 + lo = make_uint4(__vsub4(w[0] & 0x0F0F0F0Fu, 0x08080808u), __vsub4(w[1] & 0x0F0F0F0Fu, 0x08080808u), + __vsub4(w[2] & 0x0F0F0F0Fu, 0x08080808u), __vsub4(w[3] & 0x0F0F0F0Fu, 0x08080808u)); + hi = make_uint4(__vsub4((w[0] >> 4) & 0x0F0F0F0Fu, 0x08080808u), + __vsub4((w[1] >> 4) & 0x0F0F0F0Fu, 0x08080808u), + __vsub4((w[2] >> 4) & 0x0F0F0F0Fu, 0x08080808u), + __vsub4((w[3] >> 4) & 0x0F0F0F0Fu, 0x08080808u)); + } + int8_t* dst = kv == 0 ? &S.k[c][b * QK4_0] : &S.v[c][b * QK4_0]; + reinterpret_cast(dst)[0] = lo; + reinterpret_cast(dst)[1] = hi; + (kv == 0 ? S.ks : S.vs)[c][b] = d; + } + } else { constexpr int KPIECES = HD * (int) sizeof(typename Smem::KElem) / 16; // per K row for (int i = t; i < CH * KPIECES; i += THREADS) { const int c = i / KPIECES, pc = i % KPIECES; @@ -222,17 +258,18 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_kernel(const float* __res } } __syncthreads(); - // scores: warp w takes cells 8w..8w+7 (one n-tile) over all 256 dims, per 64-dim scale group + // scores: warp w takes cells 8w..8w+7 (one n-tile) over all 256 dims, per scale group (64 dims; q4_0's 32) + constexpr int NG = Smem::NG, KPG = HD / 16 / NG; // groups per row, 16-dim MMA steps per group #pragma unroll for (int nt = 0; nt < CH / 32; ++nt) { const int cb = (warp + 4 * nt) * 8; float sc[4] = {0.f, 0.f, 0.f, 0.f}; #pragma unroll - for (int g = 0; g < 4; ++g) { + for (int g = 0; g < NG; ++g) { float tg[4] = {0.f, 0.f, 0.f, 0.f}; #pragma unroll - for (int kk = 0; kk < 4; ++kk) { - const int k0 = (g * 4 + kk) * 16; + for (int kk = 0; kk < KPG; ++kk) { + const int k0 = (g * KPG + kk) * 16; uint32_t ah[4], al[4], b[2]; ah[0] = *reinterpret_cast(&S.qh[gid][k0 + 2 * tig]); ah[1] = *reinterpret_cast(&S.qh[gid + 8][k0 + 2 * tig]); @@ -296,24 +333,31 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_kernel(const float* __res } } __syncthreads(); - // p.v: warp w owns dims [64w, 64w+64), which is int8 scale group w. The scale is folded into p relative to - // the chunk's largest, times 2^14 (p' <= 2^14: its lo half stays out of FP16's subnormal range); the chunk's - // sum is then added to the running one in FP32 with the factor taken back out + // p.v: warp w owns dims [64w, 64w+64), which is int8 scale group w (q4_0: groups 2w and 2w+1, four n-tiles + // each). A group's scale is folded into p relative to the chunk's largest magnitude (q4_0's scales are signed: + // ggml's d = max / -8), times 2^14 (|p'| <= 2^14: inside FP16's range, its lo half out of the subnormals); the + // chunk's sum is then added to the running one in FP32 with the factor taken back out { - float vmax = 0.0f; -#pragma unroll - for (int c = lane; c < CH; c += 32) vmax = fmaxf(vmax, S.vs[c][warp]); -#pragma unroll - for (int o = 16; o > 0; o >>= 1) vmax = fmaxf(vmax, __shfl_xor_sync(0xffffffffu, vmax, o)); - const float vup = vmax > 0.0f ? 16384.0f / vmax : 0.0f, vdown = vmax * (1.0f / 16384.0f); + constexpr int GPW = NG / 4, JPG = 8 / GPW; // scale groups per warp, n-tiles per group + float vdown_g[GPW]; float tmp[8][4]; #pragma unroll for (int j = 0; j < 8; ++j) tmp[j][0] = tmp[j][1] = tmp[j][2] = tmp[j][3] = 0.0f; +#pragma unroll + for (int gi = 0; gi < GPW; ++gi) { + const int vg = warp * GPW + gi; + float vmax = 0.0f; +#pragma unroll + for (int c = lane; c < CH; c += 32) vmax = fmaxf(vmax, fabsf(S.vs[c][vg])); +#pragma unroll + for (int o = 16; o > 0; o >>= 1) vmax = fmaxf(vmax, __shfl_xor_sync(0xffffffffu, vmax, o)); + const float vup = vmax > 0.0f ? 16384.0f / vmax : 0.0f; + vdown_g[gi] = vmax * (1.0f / 16384.0f); #pragma unroll for (int ks = 0; ks < CH / 16; ++ks) { const int cA = ks * 16 + 2 * tig, cB = cA + 8; - const float w0 = S.vs[cA][warp] * vup, w1 = S.vs[cA + 1][warp] * vup, w2 = S.vs[cB][warp] * vup, - w3 = S.vs[cB + 1][warp] * vup; + const float w0 = S.vs[cA][vg] * vup, w1 = S.vs[cA + 1][vg] * vup, w2 = S.vs[cB][vg] * vup, + w3 = S.vs[cB + 1][vg] * vup; const float p00 = S.s[gid][cA] * w0, p01 = S.s[gid][cA + 1] * w1; const float p10 = S.s[gid + 8][cA] * w0, p11 = S.s[gid + 8][cA + 1] * w1; const float p02 = S.s[gid][cB] * w2, p03 = S.s[gid][cB + 1] * w3; @@ -332,10 +376,11 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_kernel(const float* __res f = __half22float2(h[3]); al[3] = pack_h2(p12 - f.x, p13 - f.y); } #pragma unroll - for (int j = 0; j < 8; ++j) { + for (int jj = 0; jj < JPG; ++jj) { + const int j = gi * JPG + jj; const int d = warp * 64 + j * 8 + gid; uint32_t b[2]; - if constexpr (KV_MODE == 1) { + if constexpr (KV_MODE == 1 || KV_MODE == 4) { const uint32_t x0 = (uint8_t) S.v[cA][d] | ((uint32_t) (uint8_t) S.v[cA + 1][d] << 8); const uint32_t x1 = (uint8_t) S.v[cB][d] | ((uint32_t) (uint8_t) S.v[cB + 1][d] << 8); b[0] = i8x2_to_h2(x0); @@ -352,9 +397,11 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_kernel(const float* __res #endif } } + } const float a0 = S.alpha[gid], a1 = S.alpha[gid + 8]; #pragma unroll for (int j = 0; j < 8; ++j) { + const float vdown = vdown_g[j / JPG]; acc[j][0] = fmaf(acc[j][0], a0, tmp[j][0] * vdown); acc[j][1] = fmaf(acc[j][1], a0, tmp[j][1] * vdown); acc[j][2] = fmaf(acc[j][2], a1, tmp[j][2] * vdown); @@ -1008,10 +1055,17 @@ bool qsa_prompt_attn_batch(const float* q, const QsaAttnPools& pools, const int3 return launch_wmma(q, pools, ids, steps, cap, s, attn, n_q, (cudaStream_t) stream); return false; #endif - if (pools.k_q4 != nullptr || s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !ids || - !steps || !pools.page_table) + if (s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !ids || !steps || !pools.page_table) return false; cudaStream_t st = (cudaStream_t) stream; + if (pools.k_q4 != nullptr) { // Q4_0 K and V (--kv q4_0): mode 4. STRATA_PROMPT_ATTN_Q4=0: the old kernel (A/B) + static const bool q4_off = [] { + const char* v = std::getenv("STRATA_PROMPT_ATTN_Q4"); + return v != nullptr && v[0] == '0'; + }(); + if (q4_off || pools.v_q4 == nullptr) return false; + return launch<4>(q, pools, ids, steps, cap, s, attn, n_q, st); + } if (pools.k_q != nullptr && pools.v_q4 != nullptr) { // hybrid K8V4: int8 K + dequantized-q4 V if (!pools.k_scale) return false; return launch<3>(q, pools, ids, steps, cap, s, attn, n_q, st); diff --git a/src/kernels/qsa_prompt_attn_parity.cpp b/src/kernels/qsa_prompt_attn_parity.cpp index c5dad7c9..d7dfda27 100644 --- a/src/kernels/qsa_prompt_attn_parity.cpp +++ b/src/kernels/qsa_prompt_attn_parity.cpp @@ -1,7 +1,7 @@ // src/kernels/qsa_prompt_attn_parity.cpp - perf-review D-1: the tensor-core prompt attention (qsa_prompt_attn.hpp) // against the FP32 kernel it replaces (`qsa_decode_attn_batch`) and an FP64 host reference (GPU, synthetic, no model). // -// Int8 and FP16 pools with random codes, scales and queries; selections shaped like the prompt path's (the 2,051 +// Int8, FP16 and Q4_0 pools with random codes, scales and queries; selections shaped like the prompt path's (the 2,051 // widest, a recent window plus older cells that drift slowly from one query to the next, so neighbours share most // of them as they do in a real prompt; short contexts take every cell). Checks: // 1. against FP64, the new kernel's error is no larger than a small multiple of the old kernel's (both FP32 math); @@ -12,6 +12,7 @@ #include "strata/kernels/qsa.hpp" #include "strata/kernels/qsa_decode_attn.hpp" #include "strata/kernels/qsa_prompt_attn.hpp" +#include "strata/kernels/kv_q4.hpp" #include #include @@ -39,7 +40,7 @@ template T* up(const std::vector& h) { float h2f(uint16_t b) { __half h; *reinterpret_cast(&h) = b; return __half2float(h); } uint16_t f2h(float f) { __half h = __float2half(f); return *reinterpret_cast(&h); } -int run(int fmt, int64_t ctx, int64_t nq, int reps) { // fmt 1 int8, 0 fp16 +int run(int fmt, int64_t ctx, int64_t nq, int reps) { // fmt 1 int8, 0 fp16, 2 q4_0 const k::QsaShapes s = k::qsa_real_shapes(); const int64_t HD = s.head_dim, NKV = s.n_head_kv, NH = s.n_head, PS = s.page_size; const int64_t pages = (ctx + PS - 1) / PS, rows = pages * NKV * PS; @@ -50,7 +51,22 @@ int run(int fmt, int64_t ctx, int64_t nq, int reps) { // fmt 1 int8, 0 fp16 // pools; page table a shuffled permutation (the readers must follow it) std::vector kq, vq; std::vector ks, vs, kh, vh; - if (fmt == 1) { + std::vector k4, v4; // q4_0: 8 blocks of {fp16 d, 16 code bytes} per row (kv_q4.hpp) + constexpr int64_t B4 = 18, ROW4 = 8 * B4; + if (fmt == 2) { + std::uniform_int_distribution byte(0, 255); + // the scales as a q4_0 pool holds them: signed (ggml's d = max / -8) and spread over two decades, so a chunk's + // cells mix signs and magnitudes (a positive-only bound on them overflowed FP16 on real K/V) + std::uniform_real_distribution lg(std::log(0.01f), std::log(1.0f)); + auto sc4 = [&](std::mt19937& r) { return std::exp(lg(r)) * (byte(r) & 1 ? -1.0f : 1.0f); }; + k4.resize(rows * ROW4); v4.resize(rows * ROW4); + for (auto* pool : {&k4, &v4}) + for (int64_t b = 0; b < rows * 8; ++b) { + const uint16_t d = f2h(sc4(rng)); + std::memcpy(pool->data() + b * B4, &d, 2); + for (int j = 0; j < 16; ++j) (*pool)[b * B4 + 2 + j] = (uint8_t) byte(rng); + } + } else if (fmt == 1) { kq.resize(rows * HD); vq.resize(rows * HD); ks.resize(rows * 4); vs.resize(rows * 4); for (auto& x : kq) x = (int8_t) code(rng); for (auto& x : vq) x = (int8_t) code(rng); @@ -98,8 +114,19 @@ int run(int fmt, int64_t ctx, int64_t nq, int reps) { // fmt 1 int8, 0 fp16 std::copy(v.begin(), v.end(), sel); } k::QsaAttnPools pl; - if (fmt == 1) { pl.k_q = up(kq); pl.v_q = up(vq); pl.k_scale = up(ks); pl.v_scale = up(vs); } + if (fmt == 2) { pl.k_q4 = up(k4); pl.v_q4 = up(v4); } + else if (fmt == 1) { pl.k_q = up(kq); pl.v_q = up(vq); pl.k_scale = up(ks); pl.v_scale = up(vs); } else { pl.k_pool = up(kh); pl.v_pool = up(vh); } + // a q4_0 value: block d / 32 of the row, element j = d % 32 in the low nibble of byte j (j < 16), else the high + // nibble of byte j - 16, minus 8, times the block's scale + auto q4v = [&](const std::vector& pool, int64_t row, int64_t d) { + const uint8_t* blk = pool.data() + row * ROW4 + (d / 32) * B4; + uint16_t sc; + std::memcpy(&sc, blk, 2); + const int j = (int) (d % 32); + const int code = j < 16 ? (blk[2 + j] & 0x0F) : (blk[2 + j - 16] >> 4); + return (double) (code - 8) * h2f(sc); + }; pl.page_table = up(table); const int32_t* d_ids = up(ids); const int32_t* d_steps = up(steps); @@ -139,7 +166,8 @@ int run(int fmt, int64_t ctx, int64_t nq, int reps) { // fmt 1 int8, 0 fp16 const int64_t cell = sel[c], row = ((int64_t) table[cell / PS] * NKV + kvh) * PS + cell % PS; double a = 0; for (int64_t d = 0; d < HD; ++d) { - const double kv = fmt == 1 ? (double) kq[row * HD + d] * h2f(ks[row * 4 + d / 64]) : h2f(kh[row * HD + d]); + const double kv = fmt == 2 ? q4v(k4, row, d) + : fmt == 1 ? (double) kq[row * HD + d] * h2f(ks[row * 4 + d / 64]) : h2f(kh[row * HD + d]); a += (double) q[(i * NH + h) * HD + d] * kv; } sco[c] = a / 16.0; @@ -151,7 +179,8 @@ int run(int fmt, int64_t ctx, int64_t nq, int reps) { // fmt 1 int8, 0 fp16 double a = 0; for (int64_t c = 0; c < w; ++c) { const int64_t cell = sel[c], row = ((int64_t) table[cell / PS] * NKV + kvh) * PS + cell % PS; - const double vv = fmt == 1 ? (double) vq[row * HD + d] * h2f(vs[row * 4 + d / 64]) : h2f(vh[row * HD + d]); + const double vv = fmt == 2 ? q4v(v4, row, d) + : fmt == 1 ? (double) vq[row * HD + d] * h2f(vs[row * 4 + d / 64]) : h2f(vh[row * HD + d]); a += sco[c] * vv; } const double r = a / l; @@ -187,12 +216,13 @@ int run(int fmt, int64_t ctx, int64_t nq, int reps) { // fmt 1 int8, 0 fp16 const bool ok2 = diff <= 1e-4 * scale; std::printf("%s %s ctx %lld, %lld queries: vs FP64 old %.3g new %.3g (output scale %.3g); new vs old %.3g (%.2g of " "scale); %.3f -> %.3f ms per chunk (%.2fx)\n", - ok1 && ok2 ? "PASS" : "FAIL", fmt == 1 ? "int8" : "fp16", (long long) ctx, (long long) nq, err_old, + ok1 && ok2 ? "PASS" : "FAIL", fmt == 2 ? "q4_0" : fmt == 1 ? "int8" : "fp16", (long long) ctx, (long long) nq, err_old, err_new, ref_scale, diff, diff / scale, ms_old / reps, ms_new / reps, ms_old / ms_new); cudaFree((void*) d_ids); cudaFree((void*) d_steps); cudaFree((void*) d_q); cudaFree(d_old); cudaFree(d_new); cudaFree(scratch); cudaFree((void*) pl.k_q); cudaFree((void*) pl.v_q); cudaFree((void*) pl.k_scale); cudaFree((void*) pl.v_scale); cudaFree((void*) pl.k_pool); cudaFree((void*) pl.v_pool); cudaFree((void*) pl.page_table); + cudaFree((void*) pl.k_q4); cudaFree((void*) pl.v_q4); return ok1 && ok2 ? 0 : 1; } } // namespace @@ -222,6 +252,8 @@ int main(int argc, char** argv) { fails += run(1, ctx, nq, reps); #if !defined(__HIP_PLATFORM_AMD__) fails += run(0, ctx, nq, reps); // FP16 KV: the RDNA4 kernel takes int8 KV only + fails += run(2, ctx, nq, reps); // Q4_0 KV (mode 4) + fails += run(2, 1500, std::min(nq, 1500), reps); #endif fails += run(1, 1500, std::min(nq, 1500), reps); // short context: the selection is every cell fails += run(1, 2100, std::min(nq, 256), reps); // the identity-to-sparse edge