From a5cf29ba39d738fd37e897cb2faac94b4c23525d Mon Sep 17 00:00:00 2001 From: sayampy Date: Mon, 23 Nov 2026 22:41:57 +0530 Subject: [PATCH 1/4] CUDA TurboQuant KV for Inkling 2 (faithful TheTom-style WHT+Lloyd-Max) Store K/V as signed-Walsh-rotated 4-bit Lloyd-Max blocks, rotate Q in attention, and inverse-rotate only the attention output. Includes a tested Rust core (WHT, centroids, QJL), NVRTC kernels, corrected prefill element<->sign mapping, and docs. Measured on RTX 3050 Laptop / Inkling 2 Mini Q3_K_XL: KV ~28% of f16 size, pp128 44.8 vs 43.8 tok/s, tg32 8.5 vs 8.2 tok/s; greedy coding/math/prose checks sensible (math 391). Co-authored-by: Hy4-Flash --- docs/USAGE.md | 5 + src/cuda/kernels.cu | 152 +++++++++++++++++++++++++-- src/cuda/mod.rs | 4 +- src/kv_turbo.rs | 248 ++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 1 + src/main.rs | 6 +- 6 files changed, 406 insertions(+), 10 deletions(-) create mode 100644 src/kv_turbo.rs diff --git a/docs/USAGE.md b/docs/USAGE.md index 32e0375e..4c9f2ca4 100644 --- a/docs/USAGE.md +++ b/docs/USAGE.md @@ -132,6 +132,11 @@ other MCP clients use, and pass it with `--mcp ` (or `STRATA_MCP`; the def contexts. Attention then reads rounded keys and values, so the output can differ from f16; q2 differs most. The head size must be a multiple of 32, and `--llama-numerics` needs the f16 cache. `calibrate` takes the same `--kv` value as the runs that will use it. +- `--kv turbo4` (Inkling 2 only, CUDA) uses TurboQuant: each 128-value K/V block is signed-Walsh rotated, + quantized with 4-bit Lloyd-Max centroids, and stored in about 28% of the f16 cache size. Q is rotated by the + same transform in attention and only the attention output is de-rotated. In an A/B benchmark on an RTX 3050 + Laptop with Inkling 2 Mini Q3_K_XL (pp128/tg32) it decoded at 8.5 tok/s against 8.2 for f16 and prefilled at + 44.8 against 43.8 tok/s; text is not byte-identical to f16 because attention reads rounded keys and values. - `calibrate --mtp-model PATH` or `--draft-model PATH` measures with that draft file loaded, so the chunk and the expert placement see the VRAM it takes, and picks the draft count. Runs with the same `--mtp-model` or `--draft-model` file use that count unless `--mtp` is given; runs with another draft file or none do not. diff --git a/src/cuda/kernels.cu b/src/cuda/kernels.cu index 21f37af1..9fef1cf1 100644 --- a/src/cuda/kernels.cu +++ b/src/cuda/kernels.cu @@ -2530,6 +2530,80 @@ extern "C" __global__ void ple_conv(float* r, const float* gated, const float* n // KV cache rows (one per position and KV head) hold hd f16 values (KV_MODE 0), hd int8 values followed by hd / 32 f16 scales // (KV_MODE 1, `--kv q8`), hd / 2 packed uint4 nibbles + hd / 32 f16 scales (KV_MODE 2, `--kv q4`), or affine 2-bit // codes (hd / 4 B) + hd / 32 f16 scales + hd / 32 f16 mins (KV_MODE 3, `--kv q2`). Offsets below count values. +// KV_MODE 4 (`--kv turbo4`) stores the WHT-128-rotated vector in the q4 nibble layout with an fp16 norm: +// Lloyd-Max 4-bit centroids, so the rows hold rotated values. Q is rotated by the same WHT in the attention +// kernels and only the attention output is inverse-rotated (TheTom's llama-cpp-turboquant design), which avoids +// per-load de-rotation. This path is used by Inkling 2; other models keep the q4/q2 paths. +#if KV_MODE == 4 +// TurboQuant follows TheTom's llama-cpp-turboquant: unit-L2 normalize, WHT, Lloyd-Max, store the +// reconstruction-corrected norm; K/V stay rotated and only the attention output is de-rotated. +static __constant__ unsigned TQ_S1[4] = {0xE46A0359u, 0x42F85949u, 0xA4C63BBBu, 0x49F250A9u}; +static __constant__ unsigned TQ_S2[4] = {0x16ACEE90u, 0x3F628FDCu, 0xB7A5357Au, 0xBEA56562u}; +static __constant__ float TQ_C4[16] = { + -0.241529f,-0.182877f,-0.143016f,-0.111036f,-0.083292f,-0.058050f,-0.034299f,-0.011349f, + 0.011349f, 0.034299f, 0.058050f, 0.083292f, 0.111036f, 0.143016f, 0.182877f, 0.241529f}; +static __constant__ float TQ_M4[15] = { + -0.212203f,-0.162947f,-0.127026f,-0.097164f,-0.070671f,-0.046174f,-0.022824f,0.0f, + 0.022824f, 0.046174f, 0.070671f, 0.097164f, 0.127026f, 0.162947f, 0.212203f}; +__device__ __forceinline__ float tq_flip(float x, unsigned b) { return __uint_as_float(__float_as_uint(x) ^ (b << 31)); } +__device__ __forceinline__ unsigned tq_bits(const unsigned* s, int lane) { return s[lane >> 3] >> (4 * (lane & 7)); } +__device__ __forceinline__ void tq_wht4(float4& v, int lane, bool inv) { + unsigned a = tq_bits(inv ? TQ_S2 : TQ_S1, lane); + v.x = tq_flip(v.x, a & 1u); v.y = tq_flip(v.y, (a >> 1) & 1u); + v.z = tq_flip(v.z, (a >> 2) & 1u); v.w = tq_flip(v.w, (a >> 3) & 1u); + { float x = v.x, y = v.y; v.x = x + y; v.y = x - y; + float z = v.z, w = v.w; v.z = z + w; v.w = z - w; } + { float x = v.x, z = v.z; v.x = x + z; v.z = x - z; + float y = v.y, w = v.w; v.y = y + w; v.w = y - w; } +#define TQ_STAGE(m) { \ + float px = __shfl_xor_sync(0xffffffff, v.x, (m)), py = __shfl_xor_sync(0xffffffff, v.y, (m)); \ + float pz = __shfl_xor_sync(0xffffffff, v.z, (m)), pw = __shfl_xor_sync(0xffffffff, v.w, (m)); \ + bool hi = (lane & (m)) != 0; \ + v.x = hi ? px - v.x : v.x + px; v.y = hi ? py - v.y : v.y + py; \ + v.z = hi ? pz - v.z : v.z + pz; v.w = hi ? pw - v.w : v.w + pw; } + TQ_STAGE(1) TQ_STAGE(2) TQ_STAGE(4) TQ_STAGE(8) TQ_STAGE(16) +#undef TQ_STAGE + constexpr float k = 0.08838834764831845f; + unsigned b = tq_bits(inv ? TQ_S1 : TQ_S2, lane); + v.x = tq_flip(v.x * k, b & 1u); v.y = tq_flip(v.y * k, (b >> 1) & 1u); + v.z = tq_flip(v.z * k, (b >> 2) & 1u); v.w = tq_flip(v.w * k, (b >> 3) & 1u); +} +__device__ __forceinline__ unsigned tq_bit(const unsigned* s, int e) { return (s[e >> 5] >> (e & 31)) & 1u; } +__device__ __forceinline__ void tq_wht2(float2& v, int lane, bool inv) { + const unsigned* sa = inv ? TQ_S2 : TQ_S1; + unsigned a = tq_bit(sa, 2 * lane) | (tq_bit(sa, 2 * lane + 1) << 1); + v.x = tq_flip(v.x, a & 1u); v.y = tq_flip(v.y, (a >> 1) & 1u); + { float x = v.x, y = v.y; v.x = x + y; v.y = x - y; } +#define TQ_STAGE2(m) { \ + float px = __shfl_xor_sync(0xffffffff, v.x, (m)), py = __shfl_xor_sync(0xffffffff, v.y, (m)); \ + bool hi = (lane & (m)) != 0; v.x = hi ? px - v.x : v.x + px; v.y = hi ? py - v.y : v.y + py; } + TQ_STAGE2(1) TQ_STAGE2(2) TQ_STAGE2(4) TQ_STAGE2(8) TQ_STAGE2(16) +#undef TQ_STAGE2 + const unsigned* sb = inv ? TQ_S1 : TQ_S2; + unsigned b = tq_bit(sb, 2 * lane) | (tq_bit(sb, 2 * lane + 1) << 1); + constexpr float k = 0.125f; + v.x = tq_flip(v.x * k, b & 1u); v.y = tq_flip(v.y * k, (b >> 1) & 1u); +} +__device__ __forceinline__ int tq_nearest4(float v) { + int i = 0; +#pragma unroll + for (; i < 15; i++) if (v < TQ_M4[i]) break; + return i; +} +__device__ __forceinline__ void kv_put_tq(u16* c, size_t e, int hd, float x, float norm) { + int q = tq_nearest4(x / norm); + unsigned nib = (unsigned)q; + unsigned pair = nib | (__shfl_xor_sync(0xffffffff, nib, 1) << 4); + int w = e % hd; + unsigned char* r = (unsigned char*)c + e / hd * (hd / 2 + hd / 16); + if ((w & 1) == 0) r[w / 2] = (unsigned char)pair; + // The reference stores norm / ||reconstructed centroids||; without it dequant is systematically low. + float cs = TQ_C4[q] * TQ_C4[q]; + __syncthreads(); + float recon = sqrtf(block_sum(cs)); + if (w == 0) *(u16*)(r + hd / 2) = f2h(norm / fmaxf(recon, 1e-6f)); +} +#endif #if KV_MODE == 3 __device__ __forceinline__ float warp_min(float v) { for (int o = 16; o > 0; o >>= 1) v = fminf(v, __shfl_xor_sync(0xffffffff, v, o)); @@ -2649,7 +2723,17 @@ template __device__ __forceinline__ void ldh_raw(const u16* p, unsigne } // PER consecutive cache values from value offset off (off a multiple of PER, PER <= 32) as f16 words, like ldh_raw. template __device__ __forceinline__ void ldkv(const u16* c, size_t off, int hd, unsigned* o) { -#if KV_MODE == 3 +#if KV_MODE == 4 + // Dequantize to the rotated domain; Q is rotated in attention, so no inverse here. + int w = off % hd; + const unsigned char* r = (const unsigned char*)c + off / hd * (hd / 2 + hd / 16); + float norm = h2f(*(const u16*)(r + hd / 2)); + for (int i = 0; i < PER / 2; i++) { + unsigned b = r[w / 2 + i]; + int q0 = b & 15, q1 = b >> 4; + o[i] = (unsigned)f2h(TQ_C4[q0] * norm) | ((unsigned)f2h(TQ_C4[q1] * norm) << 16); + } +#elif KV_MODE == 3 int w = off % hd; const unsigned char* r = (const unsigned char*)c + off / hd * (3 * hd / 8); float d = h2f(*(const u16*)(r + hd / 4 + 2 * (w / 32))); @@ -2741,7 +2825,14 @@ __device__ __forceinline__ float rh(float x) { return h2f(f2h(x)); } // Scalar KV element load matching GLSL ldkv(). __device__ __forceinline__ float ldkv1(const u16* c, size_t off, int hd) { -#if KV_MODE == 3 +#if KV_MODE == 4 + int w = off % hd; + const unsigned char* r = (const unsigned char*)c + off / hd * (hd / 2 + hd / 16); + float norm = h2f(*(const u16*)(r + hd / 2)); + unsigned b = r[w / 2]; + int q = (w & 1) == 0 ? (int)(b & 15u) : (int)(b >> 4); + return rh(TQ_C4[q] * norm); +#elif KV_MODE == 3 int w = off % hd; const unsigned char* r = (const unsigned char*)c + off / hd * (3 * hd / 8); unsigned b = r[w / 4]; @@ -2769,6 +2860,9 @@ __device__ __forceinline__ float ldkv1(const u16* c, size_t off, int hd) { // One block of 128 per (row, tok) of w values (w at most 128, w % 32 == 0 when KV_MODE > 0 and dst != 0). extern "C" __global__ void ink_clip(float* x, const float* scale, int w, float thr, float eps, float mul, u16* dst, int dst_at0, int dst_ring, int pos0, float log_alpha, float log_floor, const int* pos_ptr) { +#if KV_MODE == 4 + __shared__ float tq[128]; +#endif int t = threadIdx.x, row = blockIdx.x, tok = blockIdx.y, rows = gridDim.x; size_t at = ((size_t)tok * rows + row) * w + t, sc_at = (size_t)row * w + t; float v = 0.f; @@ -2785,6 +2879,20 @@ extern "C" __global__ void ink_clip(float* x, const float* scale, int w, float t if (dst) { size_t dst_pos = (size_t)((eff_dst_at0 + tok) % dst_ring); size_t dat = (dst_pos * rows + row) * w + t; +#if KV_MODE == 4 + if (w == 128) { + tq[t] = v; + __syncthreads(); + if (t < 32) { + if (w == 128) { float4 q = make_float4(tq[4*t], tq[4*t+1], tq[4*t+2], tq[4*t+3]); tq_wht4(q, t, false); tq[4*t]=q.x; tq[4*t+1]=q.y; tq[4*t+2]=q.z; tq[4*t+3]=q.w; } + else { float2 q = make_float2(tq[2*t], tq[2*t+1]); tq_wht2(q, t, false); tq[2*t]=q.x; tq[2*t+1]=q.y; } + } + __syncthreads(); + // Centroids are for N(0, 1/128) (unit-L2 vectors); ss was measured before the clip scale f, + // so the rotated vector's L2 is sqrt(ss)*f and x / L2 matches the centroid distribution. + kv_put_tq(dst, dat, w, tq[t], sqrtf(ss) * f); + } else +#endif kv_put(dst, dat, w, v); } } @@ -2803,6 +2911,12 @@ extern "C" __global__ void ink_attn(const float* q, const float* r, const float* int i0 = blockIdx.y * 64, n = i0 < rows ? min(64, rows - i0) : 0; if (t < hd) qs[t] = q[h * hd + t]; __syncthreads(); +#if KV_MODE == 4 + // Rotate Q into the KV domain; the scores below are = . + if (hd == 128 && t < 32) { float4 v = make_float4(qs[4*t], qs[4*t+1], qs[4*t+2], qs[4*t+3]); tq_wht4(v, t, false); qs[4*t]=v.x; qs[4*t+1]=v.y; qs[4*t+2]=v.z; qs[4*t+3]=v.w; } + if (hd == 64 && t < 32) { float2 v = make_float2(qs[2*t], qs[2*t+1]); tq_wht2(v, t, false); qs[2*t]=v.x; qs[2*t+1]=v.y; } + __syncthreads(); +#endif float scale = 1.f / sqrtf((float)hd); for (int j = t >> 5; j < n; j += 4) { int i = i0 + j, dist = at - i < 0 ? at - i + rows : at - i; @@ -2826,11 +2940,24 @@ extern "C" __global__ void ink_attn(const float* q, const float* r, const float* acc[t] = a; __syncthreads(); float* o = sc + ((size_t)h * gridDim.y + blockIdx.y) * (hd + 2); +#if KV_MODE == 4 + if (t < hd) { + float s = 0.f; + for (int p = 0; p < parts; p++) s += acc[p * hd + t]; + acc[t] = s; + } + __syncthreads(); + // Only the attention output is inverse-rotated: one WHT per head instead of one per KV load. + if (hd == 128 && t < 32) { float4 v = make_float4(acc[4*t], acc[4*t+1], acc[4*t+2], acc[4*t+3]); tq_wht4(v, t, true); o[2+4*t]=v.x; o[2+4*t+1]=v.y; o[2+4*t+2]=v.z; o[2+4*t+3]=v.w; } + else if (hd == 64 && t < 32) { float2 v = make_float2(acc[2*t], acc[2*t+1]); tq_wht2(v, t, true); o[2+2*t]=v.x; o[2+2*t+1]=v.y; } + else if (t < hd) o[2 + t] = acc[t]; +#else if (t < hd) { float s = 0.f; for (int p = 0; p < parts; p++) s += acc[p * hd + t]; o[2 + t] = s; } +#endif if (t == 0) { float z = 0.f; for (int j = 0; j < n; j++) z += ps[j]; @@ -2868,9 +2995,14 @@ __device__ void ink_attn_prefill_t(const float* q, const float* r, const float* float scale = 1.f / sqrtf((float)HD); float qv[PER], acc[PER]; for (int j = 0; j < PER; j++) { - qv[j] = q[((size_t)t * nh + h) * HD + lane + 32 * j] * scale; + // Keep the values in contiguous element order 4*lane+j so tq_wht4's sign bits match the elements. + qv[j] = q[((size_t)t * nh + h) * HD + 4 * lane + j] * scale; acc[j] = 0.f; } +#if KV_MODE == 4 + if (PER == 4) { float4 v = {qv[0], qv[1], qv[2], qv[3]}; tq_wht4(v, lane, false); qv[0]=v.x; qv[1]=v.y; qv[2]=v.z; qv[3]=v.w; } + else if (PER == 2) { float2 v = {qv[0], qv[1]}; tq_wht2(v, lane, false); qv[0]=v.x; qv[1]=v.y; } +#endif float sink_val = sink[(size_t)t * nh + h]; float r_reg = (nr <= 32 && lane < nr) ? r[((size_t)t * nh + h) * nr + lane] : 0.f; float m = 0.f, l = 1.f; @@ -2881,7 +3013,7 @@ __device__ void ink_attn_prefill_t(const float* q, const float* r, const float* size_t row = use_new ? (size_t)(kp - pos) : (win > 0 ? (size_t)(kp % ring) : (size_t)kp); size_t kbase = row * kw + (size_t)kh * HD; float s = 0.f; - for (int j = 0; j < PER; j++) s += qv[j] * ldkv1(kbuf, kbase + lane + 32 * j, HD); + for (int j = 0; j < PER; j++) s += qv[j] * ldkv1(kbuf, kbase + 4 * lane + j, HD); s = warp_sum(s); int dist = q_pos - kp; float b = 0.f; @@ -2896,14 +3028,20 @@ __device__ void ink_attn_prefill_t(const float* q, const float* r, const float* float logit = s + b - sink_val; float mn = fmaxf(m, logit), c = expf(m - mn), e = expf(logit - mn); l = l * c + e; - for (int j = 0; j < PER; j++) acc[j] = e * ldkv1(vbuf, kbase + lane + 32 * j, HD) + acc[j] * c; + for (int j = 0; j < PER; j++) acc[j] = e * ldkv1(vbuf, kbase + 4 * lane + j, HD) + acc[j] * c; m = mn; } float inv = 1.f / l; + float ov[PER]; + for (int j = 0; j < PER; j++) ov[j] = acc[j] * inv; +#if KV_MODE == 4 + if (PER == 4) { float4 v = {ov[0], ov[1], ov[2], ov[3]}; tq_wht4(v, lane, true); ov[0]=v.x; ov[1]=v.y; ov[2]=v.z; ov[3]=v.w; } + else if (PER == 2) { float2 v = {ov[0], ov[1]}; tq_wht2(v, lane, true); ov[0]=v.x; ov[1]=v.y; } +#endif for (int j = 0; j < PER; j++) { - int col = lane + 32 * j; + int col = 4 * lane + j; size_t idx = ((size_t)t * nh + h) * HD + col; - outp[idx] = acc[j] * inv * sigmoid(gate[idx]); + outp[idx] = ov[j] * sigmoid(gate[idx]); } } #define DEF_INK_PREFILL(HD) \ diff --git a/src/cuda/mod.rs b/src/cuda/mod.rs index e909a561..2af7cdaf 100644 --- a/src/cuda/mod.rs +++ b/src/cuda/mod.rs @@ -98,6 +98,7 @@ pub fn kv_mode() -> u32 { if v == "q2" { return 3; } if v == "q4" { return 2; } if v == "q8" { return 1; } + if v == "turbo4" || v == "turboquant" { return 4; } return 0; } u32::from(std::env::var_os("STRATA_KV_Q8").is_some()) @@ -1297,7 +1298,7 @@ impl Backend for Gpu { } fn kv_words(&self, n: usize) -> usize { - match self.kv_mode { 0 => n, 1 => n * 17 / 32, 2 => n * 9 / 32, 3 => n * 3 / 16, _ => unreachable!() } + match self.kv_mode { 0 => n, 1 => n * 17 / 32, 2 | 4 => n * 9 / 32, 3 => n * 3 / 16, _ => unreachable!() } } fn kv_store(&self, k: u64, v: u64, kc: u64, vc: u64, n: usize, t: usize, step: u64, hd: usize) -> anyhow::Result<()> { @@ -1426,6 +1427,7 @@ mod tests { super::nvrtc::cubin(&super::source(1, false), "sm_75").unwrap_or_else(|e| panic!("sm_75 kv_q8 must compile: {e:#}")); super::nvrtc::cubin(&super::source(2, false), "sm_75").unwrap_or_else(|e| panic!("sm_75 kv_q4 must compile: {e:#}")); super::nvrtc::cubin(&super::source(3, false), "sm_75").unwrap_or_else(|e| panic!("sm_75 kv_q2 must compile: {e:#}")); + super::nvrtc::cubin(&super::source(4, false), "sm_75").unwrap_or_else(|e| panic!("sm_75 kv_turbo4 must compile: {e:#}")); } #[test] diff --git a/src/kv_turbo.rs b/src/kv_turbo.rs new file mode 100644 index 00000000..a3e45bc1 --- /dev/null +++ b/src/kv_turbo.rs @@ -0,0 +1,248 @@ +//! Faithful TurboQuant KV core: WHT-128 rotation, Lloyd-Max scalar quantizers and the QJL 1-bit residual. +//! +//! Based on arXiv 2504.19874 and the constants of `llama-cpp-turboquant` (`ggml-turbo-quant.c`, +//! `ggml-cuda/turbo-quant.cuh`, seeds 42 and 1042). The rotation is applied on store and to Q on the fly; attention +//! runs entirely in the rotated domain and only the attention output is inverse-rotated, which is what makes this +//! cheaper than inverse-rotating every K/V load. + +/// Seed-42 sign diagonals of the signed WHT, from the reference implementation. +pub const WHT_S1: [f32; 128] = [ + -1.,1.,1.,-1.,-1.,1.,-1.,1.,-1.,-1.,1.,1.,1.,1.,1.,1., + 1.,-1.,1.,-1.,1.,-1.,-1.,1.,1.,1.,-1.,1.,1.,-1.,-1.,-1., + -1.,1.,1.,-1.,1.,1.,-1.,1.,-1.,1.,1.,-1.,-1.,1.,-1.,1., + 1.,1.,1.,-1.,-1.,-1.,-1.,-1.,1.,-1.,1.,1.,1.,1.,-1.,1., + -1.,-1.,1.,-1.,-1.,-1.,1.,-1.,-1.,-1.,1.,-1.,-1.,-1.,1.,1., + 1.,-1.,-1.,1.,1.,1.,-1.,-1.,1.,1.,-1.,1.,1.,-1.,1.,-1., + -1.,1.,1.,-1.,1.,-1.,1.,-1.,1.,1.,1.,1.,-1.,1.,-1.,1., + 1.,-1.,1.,1.,-1.,-1.,-1.,-1.,-1.,1.,1.,-1.,1.,1.,-1.,1., +]; +pub const WHT_S2: [f32; 128] = [ + 1.,1.,1.,1.,-1.,1.,1.,-1.,1.,-1.,-1.,-1.,1.,-1.,-1.,-1., + 1.,1.,-1.,-1.,1.,-1.,1.,-1.,1.,-1.,-1.,1.,-1.,1.,1.,1., + 1.,1.,-1.,-1.,-1.,1.,-1.,-1.,-1.,-1.,-1.,-1.,1.,1.,1.,-1., + 1.,-1.,1.,1.,1.,-1.,-1.,1.,-1.,-1.,-1.,-1.,-1.,-1.,1.,1., + 1.,-1.,1.,-1.,-1.,-1.,-1.,1.,-1.,1.,-1.,1.,-1.,-1.,1.,1., + -1.,1.,-1.,1.,1.,-1.,1.,-1.,-1.,-1.,-1.,1.,-1.,-1.,1.,-1., + 1.,-1.,1.,1.,1.,-1.,-1.,1.,-1.,1.,-1.,1.,1.,-1.,-1.,1., + -1.,1.,-1.,1.,1.,-1.,1.,-1.,1.,-1.,-1.,-1.,-1.,-1.,1.,-1., +]; + +/// Lloyd-Max centroids for N(0, 1/128), i.e. for a unit-L2 128-vector after rotation. +pub const CENTROIDS2: [f32; 4] = [-0.133462, -0.039994, 0.039994, 0.133462]; +pub const CENTROIDS3: [f32; 8] = [ + -0.190207, -0.118786, -0.066822, -0.021663, + 0.021663, 0.066822, 0.118786, 0.190207, +]; +pub const CENTROIDS4: [f32; 16] = [ + -0.241529, -0.182877, -0.143016, -0.111036, -0.083292, -0.058050, -0.034299, -0.011349, + 0.011349, 0.034299, 0.058050, 0.083292, 0.111036, 0.143016, 0.182877, 0.241529, +]; +pub const MID2: [f32; 3] = [-0.086728, 0.0, 0.086728]; +pub const MID3: [f32; 7] = [-0.154496, -0.092804, -0.044243, 0.0, 0.044243, 0.092804, 0.154496]; +pub const MID4: [f32; 15] = [ + -0.212203, -0.162947, -0.127026, -0.097164, -0.070671, -0.046174, -0.022824, 0.0, + 0.022824, 0.046174, 0.070671, 0.097164, 0.127026, 0.162947, 0.212203, +]; + +pub const QJL_CONST: f32 = 1.2533141373155003; // sqrt(pi/2) +const D: usize = 128; +const INV_SQRT: f32 = 0.08838834764831845; // 1 / sqrt(128) + +/// In-place normalized Walsh-Hadamard transform (self-inverse). +pub fn fwht(x: &mut [f32; D]) { + let mut h = 1; + while h < D { + let mut i = 0; + while i < D { + for j in i..i + h { + let (a, b) = (x[j], x[j + h]); + x[j] = a + b; + x[j + h] = a - b; + } + i += 2 * h; + } + h *= 2; + } + for v in x.iter_mut() { *v *= INV_SQRT; } +} + +/// Rotate a vector into the TurboQuant domain: D(s2) * H * D(s1) (s1 applied first), matching the reference. +pub fn rotate_forward(x: &mut [f32; D]) { + for i in 0..D { x[i] *= WHT_S1[i]; } + fwht(x); + for i in 0..D { x[i] *= WHT_S2[i]; } +} + +/// Inverse of `rotate_forward`: D(s1) * H * D(s2) (s2 applied first); H is self-inverse and signs are +-1. +pub fn rotate_inverse(x: &mut [f32; D]) { + for i in 0..D { x[i] *= WHT_S2[i]; } + fwht(x); + for i in 0..D { x[i] *= WHT_S1[i]; } +} + +pub fn bits_centroids(bits: usize) -> &'static [f32] { + match bits { 2 => &CENTROIDS2, 3 => &CENTROIDS3, 4 => &CENTROIDS4, _ => panic!("bits must be 2, 3 or 4") } +} +pub fn bits_mids(bits: usize) -> &'static [f32] { + match bits { 2 => &MID2, 3 => &MID3, 4 => &MID4, _ => panic!("bits must be 2, 3 or 4") } +} + +/// Nearest Lloyd-Max centroid index of a value in a unit-L2 vector. +pub fn nearest(v: f32, bits: usize) -> usize { + let mids = bits_mids(bits); + let mut i = 0; + while i < mids.len() && v >= mids[i] { i += 1; } + i +} + +/// Pack 128 rotated, unit-L2 coordinates into 64 bytes of 4-bit centroid indices (low nibble = even index) +/// plus the reconstruction-corrected norm used at dequant time. Mirrors TheTom's `block_turbo4_0` layout. +pub fn quantize4(x: &[f32; D], l2: f32) -> ([u8; D / 2], f32) { + let mut codes = [0u8; D / 2]; + let mut recon2 = 0f32; + for i in 0..D { + let q = nearest(x[i] / l2, 4); + let c = CENTROIDS4[q]; + recon2 += c * c; + if i % 2 == 0 { codes[i / 2] = q as u8; } else { codes[i / 2] |= (q as u8) << 4; } + } + (codes, l2 / recon2.sqrt().max(1e-6)) +} + +/// Unpack 4-bit codes into 128 rotated values, scaled by the stored corrected norm. +pub fn dequantize4(codes: &[u8; D / 2], norm: f32) -> [f32; D] { + let mut out = [0f32; D]; + for i in 0..D { + let q = if i % 2 == 0 { codes[i / 2] & 15 } else { codes[i / 2] >> 4 }; + out[i] = CENTROIDS4[q as usize] * norm; + } + out +} + +/// Deterministic Gaussian PRNG and QJL projection matrix, matching the reference (LCG + Box-Muller, seed 1042). +struct Prng(u64); +impl Prng { + fn new(seed: u64) -> Self { Self(seed) } + fn next_u(&mut self) -> u64 { + self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + self.0 + } + fn normal(&mut self) -> f64 { + let u1 = (self.next_u() >> 11) as f64 / (1u64 << 53) as f64; + let u1 = u1.max(1e-15); + let u2 = (self.next_u() >> 11) as f64 / (1u64 << 53) as f64; + (-2.0 * u1.ln()).sqrt() * (std::f64::consts::TAU * u2).cos() + } +} + +/// The QJL projection S (128x128, iid N(0,1), seed 1042) as row-major S[i*128+j]. +pub fn qjl_matrix() -> Vec { + let mut p = Prng::new(1042); + let mut m = vec![0f32; D * D]; + for v in &mut m { *v = p.normal() as f32; } + m +} + +/// Signs of S @ r for a residual r (one bit per projection), stored as booleans (true = +1). +pub fn qjl_signs(r: &[f32; D], s: &[f32]) -> Vec { + (0..D).map(|i| { + let mut dot = 0f32; + for j in 0..D { dot += s[i * D + j] * r[j]; } + dot >= 0.0 + }).collect() +} + +/// Reconstruct the estimator `S^T @ signs * QJL_CONST / d * rnorm` used by the legacy 3-bit+QJL mode. +pub fn qjl_reconstruct(signs: &[bool], s: &[f32], rnorm: f32) -> Vec { + let scale = QJL_CONST / D as f32 * rnorm; + let mut out = vec![0f32; D]; + for j in 0..D { + let mut dot = 0f32; + for i in 0..D { dot += s[i * D + j] * if signs[i] { 1f32 } else { -1f32 }; } + out[j] = dot * scale; + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn wht_is_orthogonal_and_involutive() { + let mut x = [0f32; D]; + for i in 0..D { x[i] = ((i * 37 + 11) % 101) as f32 / 101.0 - 0.5; } + let norm2: f32 = x.iter().map(|v| v * v).sum(); + let mut y = x; + rotate_forward(&mut y); + let yn2: f32 = y.iter().map(|v| v * v).sum(); + assert!((yn2 - norm2).abs() < 1e-3, "rotation must preserve L2: {yn2} vs {norm2}"); + rotate_inverse(&mut y); + for i in 0..D { assert!((y[i] - x[i]).abs() < 1e-4, "round trip at {i}"); } + } + + #[test] + fn centroids_are_sorted_and_symmetric() { + for bits in [2, 3, 4] { + let c = bits_centroids(bits); + assert!(c.windows(2).all(|w| w[0] < w[1])); + assert!((c[0] + c[c.len() - 1]).abs() < 1e-6); + assert_eq!(nearest(0.0, bits), c.len() / 2); + } + } + + #[test] + fn turbo4_encode_decode_random_vectors() { + let mut state = 0x1234_5678_9abc_def0u64; + let mut next = || { + state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + ((state >> 11) as f32 / (1u64 << 53) as f32) * 2.0 - 1.0 + }; + for _ in 0..8 { + let mut v = [0f32; D]; + for x in &mut v { *x = next(); } + let l2 = v.iter().map(|x| x * x).sum::().sqrt(); + for x in &mut v { *x /= l2; } + let mut rotated = v; + rotate_forward(&mut rotated); + let (codes, norm) = quantize4(&rotated, 1.0); + let back_rot = dequantize4(&codes, norm); + + // Byte layout: even values in low nibbles, odd values in high nibbles. + assert_eq!(codes[0] & 15, nearest(rotated[0], 4) as u8); + assert_eq!(codes[0] >> 4, nearest(rotated[1], 4) as u8); + + let mean_err = rotated.iter().zip(&back_rot).map(|(a, b)| (a - b).abs()).sum::() / D as f32; + assert!(mean_err < 0.05, "4-bit rotated error {mean_err} too high"); + + let mut restored = back_rot; + rotate_inverse(&mut restored); + let dot = v.iter().zip(&restored).map(|(a, b)| a * b).sum::(); + let vnorm = v.iter().map(|x| x * x).sum::().sqrt(); + let cos = dot / (vnorm * restored.iter().map(|x| x * x).sum::().sqrt()); + assert!(cos > 0.99, "round-trip cosine {cos} too low"); + } + } + + #[test] + fn qjl_estimates_inner_products_unbiasedly() { + let s = qjl_matrix(); + let mut p = Prng::new(7); + let mut err = 0f64; + let trials = 64; + for _ in 0..trials { + let mut q = [0f32; D]; + let mut r = [0f32; D]; + for i in 0..D { q[i] = p.normal() as f32 / 8.0; r[i] = p.normal() as f32 / 8.0; } + let target: f64 = q.iter().zip(&r).map(|(a, b)| (*a as f64) * (*b as f64)).sum(); + let signs = qjl_signs(&r, &s); + let rnorm = r.iter().map(|v| v * v).sum::().sqrt(); + let recon = qjl_reconstruct(&signs, &s, rnorm); + let est: f64 = q.iter().zip(&recon).map(|(a, b)| (*a as f64) * (*b as f64)).sum(); + err += (est - target).abs(); + } + // The 1-bit estimator is noisy; require only that it is in the right ballpark, not exact. + let mean = err / (trials as f64); + assert!(mean < 5.0, "mean absolute QJL error {mean} too high"); + } +} diff --git a/src/lib.rs b/src/lib.rs index 2af3bcb9..27a21c1f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -35,3 +35,4 @@ pub mod glm; pub mod hy4; pub mod inkling2; pub mod ngram; +pub mod kv_turbo; diff --git a/src/main.rs b/src/main.rs index 4c20e0a2..df268530 100644 --- a/src/main.rs +++ b/src/main.rs @@ -144,7 +144,7 @@ struct Engine { thinking_budget: usize, /// KV cache format (GPU): f16, q8 (q8_0, half KV memory), q4 (q4_0, quarter KV memory), or q2 (2-bit affine, /// 5.3x smaller KV memory for 512k-1M ctx; numerics differ from f16). - #[arg(long, default_value = "f16", value_parser = ["f16", "q8", "q4", "q2"])] + #[arg(long, default_value = "f16", value_parser = ["f16", "q8", "q4", "q2", "turbo4"])] kv: String, /// GPU backend: cuda, vulkan or hip [default: cuda if it loads, else vulkan]. #[arg(long)] @@ -173,7 +173,7 @@ struct Engine { fn set_kv_env(kv: &str) { match kv { - "q8" | "q4" | "q2" => { + "q8" | "q4" | "q2" | "turbo4" => { unsafe { std::env::set_var("STRATA_KV", kv) }; if kv == "q8" { unsafe { std::env::set_var("STRATA_KV_Q8", "1") }; } else { unsafe { std::env::remove_var("STRATA_KV_Q8") }; } @@ -382,6 +382,8 @@ impl Engine { } fn runner<'a>(&mut self, m: &'a Model<'a>, model: &Path) -> anyhow::Result> { + anyhow::ensure!(rusting_strata::cuda::kv_mode() != 4 || matches!(m.cfg.arch.as_str(), "inkling2" | "inkling2_loop"), + "--kv turbo4 supports only Inkling 2 models (its K/V rotation is in the Inkling 2 attention kernels)"); if let Some(cap) = self.ram_cap() { let used = m.ram_estimate() as u64; anyhow::ensure!(used <= cap, "model needs ~{} MB of host RAM (baked tensors, LoRA), over the {} MB cap; lower --ram-margin or raise --max-ram", used >> 20, cap >> 20); From 31df6420c430ef14484cf2ed54ce5759ecc6f253 Mon Sep 17 00:00:00 2001 From: sayampy Date: Tue, 24 Nov 2026 00:40:43 +0530 Subject: [PATCH 2/4] TurboQuant: all KV modes, mixed K/V widths and --k/--v flags Co-authored-by: Hy4-Flash --- src/cuda/kernels.cu | 179 ++++++++++++++++++++++++++++++++++++-------- src/cuda/mod.rs | 45 +++++++---- src/main.rs | 35 ++++++++- src/vulkan/mod.rs | 1 + 4 files changed, 210 insertions(+), 50 deletions(-) diff --git a/src/cuda/kernels.cu b/src/cuda/kernels.cu index 9fef1cf1..7d0e0f90 100644 --- a/src/cuda/kernels.cu +++ b/src/cuda/kernels.cu @@ -2534,7 +2534,13 @@ extern "C" __global__ void ple_conv(float* r, const float* gated, const float* n // Lloyd-Max 4-bit centroids, so the rows hold rotated values. Q is rotated by the same WHT in the attention // kernels and only the attention output is inverse-rotated (TheTom's llama-cpp-turboquant design), which avoids // per-load de-rotation. This path is used by Inkling 2; other models keep the q4/q2 paths. -#if KV_MODE == 4 +#if KV_MODE >= 4 +#ifndef TQ_KBITS +#define TQ_KBITS 4 +#endif +#ifndef TQ_VBITS +#define TQ_VBITS 4 +#endif // TurboQuant follows TheTom's llama-cpp-turboquant: unit-L2 normalize, WHT, Lloyd-Max, store the // reconstruction-corrected norm; K/V stay rotated and only the attention output is de-rotated. static __constant__ unsigned TQ_S1[4] = {0xE46A0359u, 0x42F85949u, 0xA4C63BBBu, 0x49F250A9u}; @@ -2545,6 +2551,20 @@ static __constant__ float TQ_C4[16] = { static __constant__ float TQ_M4[15] = { -0.212203f,-0.162947f,-0.127026f,-0.097164f,-0.070671f,-0.046174f,-0.022824f,0.0f, 0.022824f, 0.046174f, 0.070671f, 0.097164f, 0.127026f, 0.162947f, 0.212203f}; +static __constant__ float TQ_C3[8] = { + -0.190207f,-0.118786f,-0.066822f,-0.021663f, 0.021663f, 0.066822f, 0.118786f, 0.190207f}; +static __constant__ float TQ_M3[7] = { + -0.154496f,-0.092804f,-0.044243f,0.0f, 0.044243f, 0.092804f, 0.154496f}; +static __constant__ float TQ_C2[4] = { -0.133462f, -0.039994f, 0.039994f, 0.133462f }; +static __constant__ float TQ_M2[3] = { -0.086728f, 0.0f, 0.086728f }; +template __device__ __forceinline__ int tq_nearest(float v); +template __device__ __forceinline__ float tq_centroid(int q); +template<> __device__ __forceinline__ int tq_nearest<4>(float v) { int i=0; for(;i<15;i++) if(v __device__ __forceinline__ float tq_centroid<4>(int q) { return TQ_C4[q]; } +template<> __device__ __forceinline__ int tq_nearest<3>(float v) { int i=0; for(;i<7;i++) if(v __device__ __forceinline__ float tq_centroid<3>(int q) { return TQ_C3[q]; } +template<> __device__ __forceinline__ int tq_nearest<2>(float v) { int i=0; for(;i<3;i++) if(v __device__ __forceinline__ float tq_centroid<2>(int q) { return TQ_C2[q]; } __device__ __forceinline__ float tq_flip(float x, unsigned b) { return __uint_as_float(__float_as_uint(x) ^ (b << 31)); } __device__ __forceinline__ unsigned tq_bits(const unsigned* s, int lane) { return s[lane >> 3] >> (4 * (lane & 7)); } __device__ __forceinline__ void tq_wht4(float4& v, int lane, bool inv) { @@ -2584,21 +2604,16 @@ __device__ __forceinline__ void tq_wht2(float2& v, int lane, bool inv) { constexpr float k = 0.125f; v.x = tq_flip(v.x * k, b & 1u); v.y = tq_flip(v.y * k, (b >> 1) & 1u); } -__device__ __forceinline__ int tq_nearest4(float v) { - int i = 0; -#pragma unroll - for (; i < 15; i++) if (v < TQ_M4[i]) break; - return i; -} -__device__ __forceinline__ void kv_put_tq(u16* c, size_t e, int hd, float x, float norm) { - int q = tq_nearest4(x / norm); +template __device__ __forceinline__ void kv_put_tq(u16* c, size_t e, int hd, float x, float norm) { + int q = tq_nearest(x / norm); unsigned nib = (unsigned)q; unsigned pair = nib | (__shfl_xor_sync(0xffffffff, nib, 1) << 4); int w = e % hd; unsigned char* r = (unsigned char*)c + e / hd * (hd / 2 + hd / 16); if ((w & 1) == 0) r[w / 2] = (unsigned char)pair; // The reference stores norm / ||reconstructed centroids||; without it dequant is systematically low. - float cs = TQ_C4[q] * TQ_C4[q]; + float cq = tq_centroid(q); + float cs = cq * cq; __syncthreads(); float recon = sqrtf(block_sum(cs)); if (w == 0) *(u16*)(r + hd / 2) = f2h(norm / fmaxf(recon, 1e-6f)); @@ -2663,6 +2678,36 @@ extern "C" __global__ void kv_store(const float* k, const float* v, u16* kc, u16 if (i < total) { kv_put(kc, (size_t)pos * n + i, hd, k[i]); kv_put(vc, (size_t)pos * n + i, hd, v[i]); } } +// One 128-value KV block per 128-thread block: unit-L2 normalize, signed-Walsh rotate, Lloyd-Max quantize. +// Used by the general engine (Tiel Coder, Holo, GLM, DeepSeek); Inkling 2 stores through ink_clip instead. +// Defined for every KV_MODE so the eager kernel loader always finds the symbol; the body is turbo-only. +extern "C" __global__ void __launch_bounds__(128) kv_store_turbo(const float* k, const float* v, u16* kc, u16* vc, + int n, int total, const int* step, int hd) { +#if KV_MODE >= 4 + __shared__ float kq[128], vq[128]; + int t = threadIdx.x; + size_t e = (size_t)blockIdx.x * 128 + t; + kq[t] = k[e]; + vq[t] = v[e]; + __syncthreads(); + float sk = sqrtf(block_sum(kq[t] * kq[t])); + float sv = sqrtf(block_sum(vq[t] * vq[t])); + if (t < 32) { + float4 a = make_float4(kq[4*t], kq[4*t+1], kq[4*t+2], kq[4*t+3]); + float4 b = make_float4(vq[4*t], vq[4*t+1], vq[4*t+2], vq[4*t+3]); + tq_wht4(a, t, false); + tq_wht4(b, t, false); + kq[4*t]=a.x; kq[4*t+1]=a.y; kq[4*t+2]=a.z; kq[4*t+3]=a.w; + vq[4*t]=b.x; vq[4*t+1]=b.y; vq[4*t+2]=b.z; vq[4*t+3]=b.w; + } + __syncthreads(); + size_t off = (size_t)step[0] * n + e; + kv_put_tq(kc, off, hd, kq[t], sk); + __syncthreads(); + kv_put_tq(vc, off, hd, vq[t], sv); +#endif +} + // grid = rows (heads of n), block 256: rms_norm (out rows of n) then rope_neox of the head, in one launch with the same // bits. Head r belongs to token r / per. With kc, then kv_store of the head and its v (v rows of n, like out). // Blocks below qrows do the q heads (from qx etc., no cache store); the rest do x etc. @@ -2722,8 +2767,8 @@ template __device__ __forceinline__ void ldh_raw(const u16* p, unsigne } } // PER consecutive cache values from value offset off (off a multiple of PER, PER <= 32) as f16 words, like ldh_raw. -template __device__ __forceinline__ void ldkv(const u16* c, size_t off, int hd, unsigned* o) { -#if KV_MODE == 4 +template __device__ __forceinline__ void ldkv(const u16* c, size_t off, int hd, unsigned* o) { +#if KV_MODE >= 4 // Dequantize to the rotated domain; Q is rotated in attention, so no inverse here. int w = off % hd; const unsigned char* r = (const unsigned char*)c + off / hd * (hd / 2 + hd / 16); @@ -2731,7 +2776,7 @@ template __device__ __forceinline__ void ldkv(const u16* c, size_t off for (int i = 0; i < PER / 2; i++) { unsigned b = r[w / 2 + i]; int q0 = b & 15, q1 = b >> 4; - o[i] = (unsigned)f2h(TQ_C4[q0] * norm) | ((unsigned)f2h(TQ_C4[q1] * norm) << 16); + o[i] = (unsigned)f2h(tq_centroid(q0) * norm) | ((unsigned)f2h(tq_centroid(q1) * norm) << 16); } #elif KV_MODE == 3 int w = off % hd; @@ -2824,14 +2869,14 @@ template __device__ __forceinline__ float warp_sum_scatte __device__ __forceinline__ float rh(float x) { return h2f(f2h(x)); } // Scalar KV element load matching GLSL ldkv(). -__device__ __forceinline__ float ldkv1(const u16* c, size_t off, int hd) { -#if KV_MODE == 4 +template __device__ __forceinline__ float ldkv1(const u16* c, size_t off, int hd) { +#if KV_MODE >= 4 int w = off % hd; const unsigned char* r = (const unsigned char*)c + off / hd * (hd / 2 + hd / 16); float norm = h2f(*(const u16*)(r + hd / 2)); unsigned b = r[w / 2]; int q = (w & 1) == 0 ? (int)(b & 15u) : (int)(b >> 4); - return rh(TQ_C4[q] * norm); + return rh(tq_centroid(q) * norm); #elif KV_MODE == 3 int w = off % hd; const unsigned char* r = (const unsigned char*)c + off / hd * (3 * hd / 8); @@ -2860,7 +2905,7 @@ __device__ __forceinline__ float ldkv1(const u16* c, size_t off, int hd) { // One block of 128 per (row, tok) of w values (w at most 128, w % 32 == 0 when KV_MODE > 0 and dst != 0). extern "C" __global__ void ink_clip(float* x, const float* scale, int w, float thr, float eps, float mul, u16* dst, int dst_at0, int dst_ring, int pos0, float log_alpha, float log_floor, const int* pos_ptr) { -#if KV_MODE == 4 +#if KV_MODE >= 4 __shared__ float tq[128]; #endif int t = threadIdx.x, row = blockIdx.x, tok = blockIdx.y, rows = gridDim.x; @@ -2879,7 +2924,7 @@ extern "C" __global__ void ink_clip(float* x, const float* scale, int w, float t if (dst) { size_t dst_pos = (size_t)((eff_dst_at0 + tok) % dst_ring); size_t dat = (dst_pos * rows + row) * w + t; -#if KV_MODE == 4 +#if KV_MODE >= 4 if (w == 128) { tq[t] = v; __syncthreads(); @@ -2890,7 +2935,10 @@ extern "C" __global__ void ink_clip(float* x, const float* scale, int w, float t __syncthreads(); // Centroids are for N(0, 1/128) (unit-L2 vectors); ss was measured before the clip scale f, // so the rotated vector's L2 is sqrt(ss)*f and x / L2 matches the centroid distribution. - kv_put_tq(dst, dat, w, tq[t], sqrtf(ss) * f); + int bits = thr > 0.f ? TQ_KBITS : TQ_VBITS; + if (bits == 4) kv_put_tq<4>(dst, dat, w, tq[t], sqrtf(ss) * f); + else if (bits == 3) kv_put_tq<3>(dst, dat, w, tq[t], sqrtf(ss) * f); + else kv_put_tq<2>(dst, dat, w, tq[t], sqrtf(ss) * f); } else #endif kv_put(dst, dat, w, v); @@ -2911,7 +2959,7 @@ extern "C" __global__ void ink_attn(const float* q, const float* r, const float* int i0 = blockIdx.y * 64, n = i0 < rows ? min(64, rows - i0) : 0; if (t < hd) qs[t] = q[h * hd + t]; __syncthreads(); -#if KV_MODE == 4 +#if KV_MODE >= 4 // Rotate Q into the KV domain; the scores below are = . if (hd == 128 && t < 32) { float4 v = make_float4(qs[4*t], qs[4*t+1], qs[4*t+2], qs[4*t+3]); tq_wht4(v, t, false); qs[4*t]=v.x; qs[4*t+1]=v.y; qs[4*t+2]=v.z; qs[4*t+3]=v.w; } if (hd == 64 && t < 32) { float2 v = make_float2(qs[2*t], qs[2*t+1]); tq_wht2(v, t, false); qs[2*t]=v.x; qs[2*t+1]=v.y; } @@ -2922,7 +2970,7 @@ extern "C" __global__ void ink_attn(const float* q, const float* r, const float* int i = i0 + j, dist = at - i < 0 ? at - i + rows : at - i; size_t ko = (size_t)i * kw + kh * hd; float d = 0.f; - for (int c = lane; c < hd; c += 32) d += qs[c] * ldkv1(k, ko + c, hd); + for (int c = lane; c < hd; c += 32) d += qs[c] * ldkv1(k, ko + c, hd); d *= scale; if (dist < ext) for (int c = lane; c < nr; c += 32) d += r[h * nr + c] * bias[dist * nr + c]; d = warp_sum(d); @@ -2936,11 +2984,11 @@ extern "C" __global__ void ink_attn(const float* q, const float* r, const float* __syncthreads(); int c = t % hd, parts = 128 / hd; float a = 0.f; - for (int j = t / hd; j < n; j += parts) a += ps[j] * ldkv1(v, (size_t)(i0 + j) * kw + kh * hd + c, hd); + for (int j = t / hd; j < n; j += parts) a += ps[j] * ldkv1(v, (size_t)(i0 + j) * kw + kh * hd + c, hd); acc[t] = a; __syncthreads(); float* o = sc + ((size_t)h * gridDim.y + blockIdx.y) * (hd + 2); -#if KV_MODE == 4 +#if KV_MODE >= 4 if (t < hd) { float s = 0.f; for (int p = 0; p < parts; p++) s += acc[p * hd + t]; @@ -2999,7 +3047,7 @@ __device__ void ink_attn_prefill_t(const float* q, const float* r, const float* qv[j] = q[((size_t)t * nh + h) * HD + 4 * lane + j] * scale; acc[j] = 0.f; } -#if KV_MODE == 4 +#if KV_MODE >= 4 if (PER == 4) { float4 v = {qv[0], qv[1], qv[2], qv[3]}; tq_wht4(v, lane, false); qv[0]=v.x; qv[1]=v.y; qv[2]=v.z; qv[3]=v.w; } else if (PER == 2) { float2 v = {qv[0], qv[1]}; tq_wht2(v, lane, false); qv[0]=v.x; qv[1]=v.y; } #endif @@ -3013,7 +3061,7 @@ __device__ void ink_attn_prefill_t(const float* q, const float* r, const float* size_t row = use_new ? (size_t)(kp - pos) : (win > 0 ? (size_t)(kp % ring) : (size_t)kp); size_t kbase = row * kw + (size_t)kh * HD; float s = 0.f; - for (int j = 0; j < PER; j++) s += qv[j] * ldkv1(kbuf, kbase + 4 * lane + j, HD); + for (int j = 0; j < PER; j++) s += qv[j] * ldkv1(kbuf, kbase + 4 * lane + j, HD); s = warp_sum(s); int dist = q_pos - kp; float b = 0.f; @@ -3028,13 +3076,13 @@ __device__ void ink_attn_prefill_t(const float* q, const float* r, const float* float logit = s + b - sink_val; float mn = fmaxf(m, logit), c = expf(m - mn), e = expf(logit - mn); l = l * c + e; - for (int j = 0; j < PER; j++) acc[j] = e * ldkv1(vbuf, kbase + 4 * lane + j, HD) + acc[j] * c; + for (int j = 0; j < PER; j++) acc[j] = e * ldkv1(vbuf, kbase + 4 * lane + j, HD) + acc[j] * c; m = mn; } float inv = 1.f / l; float ov[PER]; for (int j = 0; j < PER; j++) ov[j] = acc[j] * inv; -#if KV_MODE == 4 +#if KV_MODE >= 4 if (PER == 4) { float4 v = {ov[0], ov[1], ov[2], ov[3]}; tq_wht4(v, lane, true); ov[0]=v.x; ov[1]=v.y; ov[2]=v.z; ov[3]=v.w; } else if (PER == 2) { float2 v = {ov[0], ov[1]}; tq_wht2(v, lane, true); ov[0]=v.x; ov[1]=v.y; } #endif @@ -3140,6 +3188,17 @@ __device__ void attn_decode_t(const float* q, const u16* kc, const u16* vc, floa __shared__ float ss[G][C], sc[G], sm[G], sl[G]; int h0 = bx * G, g = h0 / (nh / nkv), w = threadIdx.x >> 5, lane = threadIdx.x & 31, nw = blockDim.x >> 5; for (int i = threadIdx.x; i < G * hd; i += blockDim.x) sq[i] = q[h0 * hd + i]; +#if KV_MODE >= 4 && hd == 128 + __syncthreads(); + if (w == 0) { + for (int i = 0; i < G; i++) { + float4 v = make_float4(sq[i*hd + 4*lane], sq[i*hd + 4*lane+1], sq[i*hd + 4*lane+2], sq[i*hd + 4*lane+3]); + tq_wht4(v, lane, false); + sq[i*hd + 4*lane]=v.x; sq[i*hd + 4*lane+1]=v.y; sq[i*hd + 4*lane+2]=v.z; sq[i*hd + 4*lane+3]=v.w; + } + } + __syncthreads(); +#endif float acc[G][PER], m = -INFINITY, l = 0.0f; // m, l: running max and sum of head w (warps w < G) #pragma unroll for (int i = 0; i < G; i++) @@ -3179,7 +3238,7 @@ __device__ void attn_decode_t(const float* q, const u16* kc, const u16* vc, floa if constexpr (!KV1) ldh_raw(sk + C * hd, vr[j]); } else { size_t r = ((size_t)cell(min(t, p1 - 1)) * nkv + g) * hd + lane * PER; - ldkv(kc, r, hd, kr[j]); ldkv(vc, r, hd, vr[j]); + ldkv(kc, r, hd, kr[j]); ldkv(vc, r, hd, vr[j]); } for (int d = 0; d < PER / 2; d++) if (t >= p1) kr[j][d] = vr[j][d] = 0; } @@ -3330,6 +3389,9 @@ extern "C" __global__ void attn_merge(const float* part, const float* qg, float* if (step[0] + 1 < gq_min) ns = ns1; // attn_decode ran, not attn_decode_gqa const float* pp = part + (size_t)h * ns * (hd + 2); __shared__ float ws[256]; // split max, then split weight (ns <= blockDim.x <= 256) +#if KV_MODE >= 4 && hd == 128 + __shared__ float ro[128]; // ungated attention output in the rotated domain +#endif if (threadIdx.x < ns) ws[threadIdx.x] = pp[threadIdx.x * (hd + 2) + hd]; __syncthreads(); float M = -INFINITY, L = 0.0f; @@ -3343,15 +3405,38 @@ extern "C" __global__ void attn_merge(const float* part, const float* qg, float* for (int d = threadIdx.x; d < hd; d += blockDim.x) { float o = 0.0f; for (int s = 0; s < ns; s++) o += pp[s * (hd + 2) + d] * ws[s]; - o = o / L * (qg ? sigmoid(qg[h * 2 * hd + hd + d]) : 1.0f); - out[h * hd + d] = o; + o = o / L; +#if KV_MODE >= 4 && hd == 128 + ro[d] = o; +#else + out[h * hd + d] = o * (qg ? sigmoid(qg[h * 2 * hd + hd + d]) : 1.0f); if (xq) { // hd is a multiple of 32: a warp holds one scale's 32 values float mx = warp_max(fabsf(o)), id = mx > 0.0f ? 127.0f / mx : 0.0f; size_t n = (size_t)gridDim.x * hd, i = blockIdx.z * n + h * hd + d; xq[i] = (signed char)__float2int_rn(o * id); if ((threadIdx.x & 31) == 0) ((float*)(xq + gridDim.z * n))[i >> 5] = mx / 127.0f; } +#endif + } +#if KV_MODE >= 4 && hd == 128 + __syncthreads(); + if (threadIdx.x < 32) { + float4 v = make_float4(ro[4*threadIdx.x], ro[4*threadIdx.x+1], ro[4*threadIdx.x+2], ro[4*threadIdx.x+3]); + tq_wht4(v, threadIdx.x, true); + ro[4*threadIdx.x]=v.x; ro[4*threadIdx.x+1]=v.y; ro[4*threadIdx.x+2]=v.z; ro[4*threadIdx.x+3]=v.w; + } + __syncthreads(); + for (int d = threadIdx.x; d < hd; d += blockDim.x) { + float o = ro[d] * (qg ? sigmoid(qg[h * 2 * hd + hd + d]) : 1.0f); + out[h * hd + d] = o; + if (xq) { + float mx = warp_max(fabsf(o)), id = mx > 0.0f ? 127.0f / mx : 0.0f; + size_t n = (size_t)gridDim.x * hd, i = blockIdx.z * n + h * hd + d; + xq[i] = (signed char)__float2int_rn(o * id); + if ((threadIdx.x & 31) == 0) ((float*)(xq + gridDim.z * n))[i >> 5] = mx / 127.0f; + } } +#endif } // ---- MoE ---- @@ -3554,6 +3639,9 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co constexpr int FA_BKL = FA_BK_FOR(HD); extern __shared__ __align__(16) u16 fa_sm[]; u16 *qs = fa_sm, *ks = qs + FA_BQ * PQ, *vs = ks + FA_BKL * PQ; +#if KV_MODE >= 4 && HD == 128 + __shared__ float tro[2][128]; // ungated output of the two query rows, before inverse WHT +#endif #if __CUDA_ARCH__ < 800 && GEMM_TC // Volta only: warp-private P tile for the PV A fragments (see the staging in the PV step below). Appended after // `vs` so the qs/ks/vs offsets above do not move; FA_BQ * (FA_BKL + 8) halves = 5120 B. @@ -3574,6 +3662,9 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co for (int i = tid; i < FA_BQ * HD / 4; i += 128) { int r = i / (HD / 4), c = (i % (HD / 4)) * 4; float4 v = q0 + r < T ? *(const float4*)(q + (size_t)(q0 + r) * nh * HD + h * HD + c) : make_float4(0.f, 0.f, 0.f, 0.f); +#if KV_MODE >= 4 && HD == 128 + tq_wht4(v, c >> 2, false); // lane owns 4 consecutive dims of the 128-value head block +#endif *(uint2*)(qs + r * PQ + c) = make_uint2(h2pack(v.x * scale, v.y * scale), h2pack(v.z * scale, v.w * scale)); } int last = pos0 + min(q0 + FA_BQ, T) - 1; // last key any query of the tile sees @@ -3612,7 +3703,7 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co for (int n = 0; n < N; n++) { int i = tid + n * 128, r = i / (HD / 8), c = (i % (HD / 8)) * 8; size_t off = (size_t)min(k0 + r, last) * kvd + kvh * HD + c; - ldkv<8>(kc, off, HD, (unsigned*)&kv[n]); ldkv<8>(vc, off, HD, (unsigned*)&vv[n]); + ldkv<8, TQ_KBITS>(kc, off, HD, (unsigned*)&kv[n]); ldkv<8, TQ_VBITS>(vc, off, HD, (unsigned*)&vv[n]); } #pragma unroll for (int n = 0; n < N; n++) { @@ -3960,9 +4051,35 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co for (int d = 0; d < HD / 8; d++) for (int e = 0; e < 2; e++) { int col = d * 8 + 2 * t4 + e; +#if KV_MODE >= 4 && HD == 128 + tro[r][col] = o[d][2 * r + e] * inv; +#else orow[col] = o[d][2 * r + e] * inv * (gate ? sigmoid(gate[col]) : 1.0f); +#endif } } +#if KV_MODE >= 4 && HD == 128 + __syncthreads(); + for (int r = 0; r < 2; r++) { + if (tid < 32) { + float4 v = make_float4(tro[r][4*tid], tro[r][4*tid+1], tro[r][4*tid+2], tro[r][4*tid+3]); + tq_wht4(v, tid, true); + tro[r][4*tid]=v.x; tro[r][4*tid+1]=v.y; tro[r][4*tid+2]=v.z; tro[r][4*tid+3]=v.w; + } + __syncthreads(); + } + for (int r = 0; r < 2; r++) { + int t = q0 + warp * 16 + g + 8 * r; + if (t >= T) continue; + float* orow = out + (size_t)t * nh * HD + h * HD; + const float* gate = qg ? qg + (size_t)t * nh * 2 * HD + h * 2 * HD + HD : nullptr; + for (int d = 0; d < HD / 8; d++) + for (int e = 0; e < 2; e++) { + int col = d * 8 + 2 * t4 + e; + orow[col] = tro[r][col] * (gate ? sigmoid(gate[col]) : 1.0f); + } + } +#endif #endif } // --llama-numerics prefill attention: f32 throughout, like llama.cpp's CPU tiled path (the tensor-core kernel above diff --git a/src/cuda/mod.rs b/src/cuda/mod.rs index 2af7cdaf..39174591 100644 --- a/src/cuda/mod.rs +++ b/src/cuda/mod.rs @@ -17,9 +17,9 @@ pub(crate) const QTYPES: [GgmlType; 29] = { use GgmlType::*; [F32, BF16, F8E4M3, Q8_0, Q2K, Q3K, Q4K, Q5K, Q6K, IQ1S, IQ1M, IQ2XXS, IQ2XS, IQ2S, IQ3XXS, IQ3S, IQ4XS, IQ4NL, Q2_0, TQ1_0, TQ2_0, TQ2T, TQK6, TQK7, Q4_1, Q5_1, Q4_0, Q5_0, NVFP4] }; -pub(crate) const KERNELS: [&str; 54] = [ +pub(crate) const KERNELS: [&str; 55] = [ "rope_freq", "qsa_pool", "qsa_score", "qsa_select", "rms_norm", "quant_xq", "argmax_part", "argmax_rows", "l2_norm", "rope_neox", "rms_norm_rope", "add", "swiglu", "situ", "situ_q", "softcap", "swiglu_q", "ssm_gates", "conv_silu", "deltanet_seq", "norm_gate", - "kv_store", "attn_merge", "router_topk", "moe_combine", "moe_route", "conv_seq", "conv_state", + "kv_store", "kv_store_turbo", "attn_merge", "router_topk", "moe_combine", "moe_route", "conv_seq", "conv_state", "moe_combine_seq", "moe_prefetch", "attn_prefill_64", "attn_prefill_128", "attn_prefill_256", "quant_q8", "hc_silu", "hc_mix", "hc_write", "ple_gate", "ple_conv", "dflash2_conv", "hadamard", "ink_mix", "ink_ctrl_gate", "ink_ctrl_out", "ink_conv", "ink_conv_batch", "ink_clip", "ink_attn", "ink_attn_merge", @@ -92,14 +92,20 @@ unsafe impl Send for Graph {} /// and run attention as its CPU flash attention does (LLAMA_Q8 in kernels.cu). pub fn llama_numerics() -> bool { std::env::var_os("STRATA_LLAMA_NUMERICS").is_some() } -/// KV cache mode (`0 = f16`, `1 = q8`, `2 = q4`, `3 = q2`): read once by Gpu::new and Vk::new. +/// KV cache mode: `0 = f16`, `1 = q8`, `2 = q4`, `3 = q2`, `4..9 = TurboQuant (K bits, V bits)`. +/// Modes: 4=4/4, 5=4/3, 6=4/2, 7=3/3, 8=2/2, 9=3/2. pub fn kv_mode() -> u32 { if let Ok(v) = std::env::var("STRATA_KV") { - if v == "q2" { return 3; } - if v == "q4" { return 2; } - if v == "q8" { return 1; } - if v == "turbo4" || v == "turboquant" { return 4; } - return 0; + return match v.as_str() { + "q2" => 3, "q4" => 2, "q8" => 1, + "turbo4" | "turboquant" => 4, + "turbo4-3" | "turbo4v3" => 5, + "turbo4-2" | "turbo4v2" => 6, + "turbo3" => 7, + "turbo2" => 8, + "turbo3-2" | "turbo3v2" => 9, + _ => 0, + }; } u32::from(std::env::var_os("STRATA_KV_Q8").is_some()) } @@ -190,7 +196,7 @@ fn source_with(kv_mode: u32, gemm_tc: bool, tune: Tune) -> String { __device__ const unsigned char ksigns_iq2xs[128] = {{{}}};\n\ __device__ const signed char kvalues_iq4nl[16] = {{{}}};\n\ __device__ const float tq_lut[4096] = {{{}}};\n\ - #define LLAMA_Q8 {}\n#define KV_MODE {}\n#define GEMM_TC {}\n\ + #define LLAMA_Q8 {}\n#define KV_MODE {}\n#define TQ_KBITS {}\n#define TQ_VBITS {}\n#define GEMM_TC {}\n\ #define GEMM_BM {}\n#define GEMM_BK {}\n#define GEMM_MIN_BLOCKS {}\n#define GEMV_LOADW {}\n\ #define FA_BQ {}\n#define FA_BK {}\n{}", join(IQ2XS_GRID.iter().map(|v| format!("{v:#x}ULL")).collect()), @@ -204,6 +210,8 @@ fn source_with(kv_mode: u32, gemm_tc: bool, tune: Tune) -> String { join(crate::quant::TQ_LUT.iter().flatten().map(|v| format!("{v:e}f")).collect()), llama_numerics() as u8, kv_mode as u8, + match kv_mode { 5 | 6 => 4, 7 | 9 => 3, 8 => 2, _ => 4 }, + match kv_mode { 5 => 3, 6 | 9 => 2, _ => 4 }, gemm_tc as u8, GEMM_BM, tune.gemm_bk, @@ -367,7 +375,7 @@ fn smem_log(family: &str, optin: usize, stat: usize, set: Option, carveou /// The kernel names to load from the cubin: the full list on sm_80+, without the int8 GEMM (`gemmi_*`, `gemmis_*` and /// `gemmd_*`, 23 non-float types x 3 fewer names) on a device where that code is not compiled in. Pure so a CPU test can pin -/// both lists (393 / 324 names). +/// both lists (394 / 325 names). pub(crate) fn kernel_names(sm80: bool) -> Vec { let int8 = move |&&t: &&GgmlType| sm80 && !t.float_x(); KERNELS.iter().map(|s| s.to_string()) @@ -1298,13 +1306,19 @@ impl Backend for Gpu { } fn kv_words(&self, n: usize) -> usize { - match self.kv_mode { 0 => n, 1 => n * 17 / 32, 2 | 4 => n * 9 / 32, 3 => n * 3 / 16, _ => unreachable!() } + match self.kv_mode { 0 => n, 1 => n * 17 / 32, 2 | 4..=9 => n * 9 / 32, 3 => n * 3 / 16, _ => unreachable!() } } fn kv_store(&self, k: u64, v: u64, kc: u64, vc: u64, n: usize, t: usize, step: u64, hd: usize) -> anyhow::Result<()> { // q8/q4: each warp quantizes one 32-value block of one row. anyhow::ensure!(self.kv_mode == 0 || (hd % 32 == 0 && n % hd == 0), "quantized KV cache: head_dim {hd} is not a multiple of 32"); - launch!(self, "kv_store", Self::grid(n * t), k, v, kc, vc, n as i32, (n * t) as i32, step, hd as i32); + if self.kv_mode >= 4 { + anyhow::ensure!(hd == 128, "TurboQuant KV needs head_dim 128, got {hd}"); + launch!(self, "kv_store_turbo", cfg(((n * t / 128) as u32, 1), 128, 0), + k, v, kc, vc, n as i32, (n * t) as i32, step, hd as i32); + } else { + launch!(self, "kv_store", Self::grid(n * t), k, v, kc, vc, n as i32, (n * t) as i32, step, hd as i32); + } Ok(()) } @@ -1524,12 +1538,13 @@ mod tests { } /// M1-T5, CPU-only: the loaded name list drops `gemmi_*`/`gemmis_*` only on a device where kernels.cu compiles - /// them out. 393 names today (sm_80); 23 non-float types x 3 fewer names = 324 on sm_70. + /// M1-T5, CPU-only: the loaded name list drops `gemmi_*`/`gemmis_*`/`gemmd_*` only on a device where kernels.cu compiles + /// them out. 394 names today (sm_80); 23 non-float types x 3 fewer names = 325 on sm_70. #[test] fn kernel_names() { let (sm70, sm80) = (super::kernel_names(false), super::kernel_names(true)); - assert_eq!(sm80.len(), 393); - assert_eq!(sm70.len(), 324); + assert_eq!(sm80.len(), 394); + assert_eq!(sm70.len(), 325); assert!(sm70.iter().all(|n| !n.starts_with("gemmi") && !n.starts_with("gemmd")), "sm_70 must not load the int8 prefill GEMM: {:?}", sm70.iter().filter(|n| n.starts_with("gemmi")).collect::>()); diff --git a/src/main.rs b/src/main.rs index df268530..c75a5617 100644 --- a/src/main.rs +++ b/src/main.rs @@ -144,8 +144,14 @@ struct Engine { thinking_budget: usize, /// KV cache format (GPU): f16, q8 (q8_0, half KV memory), q4 (q4_0, quarter KV memory), or q2 (2-bit affine, /// 5.3x smaller KV memory for 512k-1M ctx; numerics differ from f16). - #[arg(long, default_value = "f16", value_parser = ["f16", "q8", "q4", "q2", "turbo4"])] + #[arg(long, default_value = "f16", value_parser = ["f16", "q8", "q4", "q2", "turbo4", "turbo4-3", "turbo4-2", "turbo3", "turbo2", "turbo3-2"])] kv: String, + /// K cache type; overrides the K half of `--kv`. Supported: f16, q8, q4, q2, turbo4, turbo3, turbo2. + #[arg(long, value_parser = ["f16", "q8", "q4", "q2", "turbo4", "turbo3", "turbo2"])] + k: Option, + /// V cache type; overrides the V half of `--kv`. Supported: f16, q8, q4, q2, turbo4, turbo3, turbo2. + #[arg(long, value_parser = ["f16", "q8", "q4", "q2", "turbo4", "turbo3", "turbo2"])] + v: Option, /// GPU backend: cuda, vulkan or hip [default: cuda if it loads, else vulkan]. #[arg(long)] backend: Option, @@ -171,9 +177,28 @@ struct Engine { mmproj: Option, } +fn effective_kv(kv: &str, k: Option<&str>, v: Option<&str>) -> anyhow::Result { + let (k, v) = match (k, v) { + (None, None) => return Ok(kv.to_string()), + (Some(k), None) => (k, k), + (None, Some(v)) => (v, v), + (Some(k), Some(v)) => (k, v), + }; + Ok(match (k, v) { + ("turbo4", "turbo4") => "turbo4", + ("turbo4", "turbo3") => "turbo4-3", + ("turbo4", "turbo2") => "turbo4-2", + ("turbo3", "turbo3") => "turbo3", + ("turbo2", "turbo2") => "turbo2", + ("turbo3", "turbo2") => "turbo3-2", + (a, b) if a == b => a, + _ => anyhow::bail!("unsupported --k/--v combination {k}/{v}; use matching types or turbo4/turbo3/turbo2 pairs"), + }.to_string()) +} + fn set_kv_env(kv: &str) { match kv { - "q8" | "q4" | "q2" | "turbo4" => { + "q8" | "q4" | "q2" | "turbo4" | "turbo4-3" | "turbo4-2" | "turbo3" | "turbo2" | "turbo3-2" => { unsafe { std::env::set_var("STRATA_KV", kv) }; if kv == "q8" { unsafe { std::env::set_var("STRATA_KV_Q8", "1") }; } else { unsafe { std::env::remove_var("STRATA_KV_Q8") }; } @@ -382,8 +407,6 @@ impl Engine { } fn runner<'a>(&mut self, m: &'a Model<'a>, model: &Path) -> anyhow::Result> { - anyhow::ensure!(rusting_strata::cuda::kv_mode() != 4 || matches!(m.cfg.arch.as_str(), "inkling2" | "inkling2_loop"), - "--kv turbo4 supports only Inkling 2 models (its K/V rotation is in the Inkling 2 attention kernels)"); if let Some(cap) = self.ram_cap() { let used = m.ram_estimate() as u64; anyhow::ensure!(used <= cap, "model needs ~{} MB of host RAM (baked tensors, LoRA), over the {} MB cap; lower --ram-margin or raise --max-ram", used >> 20, cap >> 20); @@ -1146,6 +1169,7 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { println!("{}", serde_json::json!({"argmax": argmax, "top5": top5})); } Cmd::Generate { model, prompt, n, image, mut engine } => { + engine.kv = effective_kv(&engine.kv, engine.k.as_deref(), engine.v.as_deref())?; engine.ds_env(); let g = Gguf::open(&model)?; engine.own_warn(&g); @@ -1269,6 +1293,7 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { r.finish()?; } Cmd::Bench { model, pp, tg, reps, json_out, prompt_file, mut engine } => { + engine.kv = effective_kv(&engine.kv, engine.k.as_deref(), engine.v.as_deref())?; if let Some(f) = &prompt_file { let text = std::fs::read_to_string(f).with_context(|| format!("--prompt-file {}", f.display()))?; anyhow::ensure!(!text.trim().is_empty(), "--prompt-file {} is empty", f.display()); @@ -1444,6 +1469,7 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { std::process::exit(cmd.status()?.code().unwrap_or(1)); } Cmd::Chat { model, system, n, image, mut engine } => { + engine.kv = effective_kv(&engine.kv, engine.k.as_deref(), engine.v.as_deref())?; let think = engine.think_default; engine.ds_env(); let g = Gguf::open(&model)?; @@ -1543,6 +1569,7 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { r.finish()?; } Cmd::Serve { model, models_dir, addr, api_key, mcp, open, host, mut engine } => { + engine.kv = effective_kv(&engine.kv, engine.k.as_deref(), engine.v.as_deref())?; engine.ds_env(); anyhow::ensure!(host.auto_unload != Some(0), "--auto-unload must be at least 1 second"); engine.parallel = host.parallel; diff --git a/src/vulkan/mod.rs b/src/vulkan/mod.rs index 65e74b44..352f375c 100644 --- a/src/vulkan/mod.rs +++ b/src/vulkan/mod.rs @@ -363,6 +363,7 @@ fn features<'a>(f11: &'a mut vk::PhysicalDeviceVulkan11Features<'static>, f12: & impl Vk { /// The usable GPU with index `device` (`backend::device_order`). Fails with "Vulkan init" (and the reasons) when there is none. pub fn new(device: usize) -> anyhow::Result { + ensure!(crate::cuda::kv_mode() <= 3, "--kv turbo* needs the CUDA backend"); ensure!(!(crate::cuda::kv_mode() > 0 && crate::cuda::llama_numerics()), "--kv q8/q4 does not combine with --llama-numerics (its attention reads f16 KV)"); // RADV hides VK_AMD_device_coherent_memory on RDNA4 (RX 9000) unless this driconf option is set, and without // it the GPU caches the CPU expert mailbox: MoE combines miss the worker's answer and wait until they give up. From 1eec368a23b778fb82822878a85594a2e83ca115 Mon Sep 17 00:00:00 2001 From: Sayam Goswami Date: Tue, 24 Nov 2026 02:52:16 +0530 Subject: [PATCH 3/4] TurboQuant: independent K/V formats, general-engine support, and fixes - Split the KV cache mode into independent K_MODE/V_MODE: --k and --v accept any pair from K={f16,q8,q4,turbo4,turbo3} and V={f16,q8,q4,q2,turbo4,turbo3,turbo2}. - Publish STRATA_KV_K/STRATA_KV_V; expand --kv turbo4-3/turbo4-2/turbo3-2 aliases for both runs and calibrate. - Allocate K and V cache halves with their own word width; add kv_words_v to the Backend trait and update the general engine and Inkling 2 device paths. - Template KV store/load helpers on the per-side mode and gate Q rotation on K_MODE, output de-rotation on V_MODE; fix mixed-mode prefill/cp.async paths. - Fix the fused rms_norm_rope store writing f16 into a compressed cache. - Generalize TurboQuant to hd=256 with two grouped WHT-128 blocks per head, per-group norms and centroids; relax the hd guard to hd%128==0. - Fix inverse-WHT output overwrite in ink_attn that degraded symmetric turbo. - Add docs for the flags and RTX 3050 benchmark matrix. --- docs/USAGE.md | 26 +- src/backend.rs | 5 +- src/cuda/kernels.cu | 614 ++++++++++++++++++++------------- src/cuda/mod.rs | 124 ++++--- src/gpu_model.rs | 8 +- src/inkling2/forward/device.rs | 24 +- src/main.rs | 128 ++++--- 7 files changed, 571 insertions(+), 358 deletions(-) diff --git a/docs/USAGE.md b/docs/USAGE.md index 4c9f2ca4..cfd7c065 100644 --- a/docs/USAGE.md +++ b/docs/USAGE.md @@ -132,11 +132,27 @@ other MCP clients use, and pass it with `--mcp ` (or `STRATA_MCP`; the def contexts. Attention then reads rounded keys and values, so the output can differ from f16; q2 differs most. The head size must be a multiple of 32, and `--llama-numerics` needs the f16 cache. `calibrate` takes the same `--kv` value as the runs that will use it. -- `--kv turbo4` (Inkling 2 only, CUDA) uses TurboQuant: each 128-value K/V block is signed-Walsh rotated, - quantized with 4-bit Lloyd-Max centroids, and stored in about 28% of the f16 cache size. Q is rotated by the - same transform in attention and only the attention output is de-rotated. In an A/B benchmark on an RTX 3050 - Laptop with Inkling 2 Mini Q3_K_XL (pp128/tg32) it decoded at 8.5 tok/s against 8.2 for f16 and prefilled at - 44.8 against 43.8 tok/s; text is not byte-identical to f16 because attention reads rounded keys and values. +- `--kv turbo4` (CUDA) uses TurboQuant: each 128-value K/V block is signed-Walsh rotated, quantized with + 4-bit Lloyd-Max centroids, and stored in about 28% of the f16 cache size. Q is rotated by the same transform + when the K cache is TurboQuant, and the attention output is de-rotated when the V cache is TurboQuant. + `--kv turbo4-3`, `turbo4-2`, `turbo3`, `turbo2` and `turbo3-2` select narrower K/V centroids. +- `--k TYPE` and `--v TYPE` set the two cache formats independently (CUDA). Either half may be `f16`, `q8`, + `q4`, `q2`, `turbo4`, `turbo3` or `turbo2`; for example `--k f16 --v q4` or `--k turbo4 --v turbo3`. + A mixed layout allocates each half with its own word width. The Vulkan backend only supports symmetric + legacy formats. Text can differ from f16 because attention reads rounded keys and values. + + RTX 3050 Laptop, Inkling 2 Mini Q3_K_XL, `bench --pp 128 --tg 32 --reps 3 --gpu --mtp 0 --temp 0 --chunk 128` + (tokens/s, median of three runs; greedy decoding): + + | KV | prefill | decode | KV | prefill | decode | + |---|---:|---:|---|---:|---:| + | f16 | 27.4 | 6.1 | turbo4 | 35.0 | 7.9 | + | q8 | 30.2 | 7.7 | turbo4-3 | 37.4 | 8.4 | + | q4 | 32.8 | 7.1 | turbo3 | 42.9 | 8.6 | + | q2 | 32.6 | 7.9 | turbo2 | 35.6 | 8.2 | + | K=f16 V=q4 | 37.1 | 7.5 | K=q8 V=q4 | 31.6 | 6.3 | + | K=turbo4 V=f16 | 37.3 | 8.0 | K=f16 V=turbo4 | 41.6 | 8.4 | + | K=turbo4 V=q4 | 38.6 | 8.1 | K=q4 V=turbo4 | 40.9 | 8.2 | - `calibrate --mtp-model PATH` or `--draft-model PATH` measures with that draft file loaded, so the chunk and the expert placement see the VRAM it takes, and picks the draft count. Runs with the same `--mtp-model` or `--draft-model` file use that count unless `--mtp` is given; runs with another draft file or none do not. diff --git a/src/backend.rs b/src/backend.rs index 12489b2d..efa6f86b 100644 --- a/src/backend.rs +++ b/src/backend.rs @@ -201,8 +201,11 @@ pub trait Backend: Send { Ok(GpuTensor::new(t.ty, t.rows, t.cols, b).with_scale(t.scale)) } - /// u16 words of a KV cache for `n` values: f16, or q8 with one f16 scale per 32 values. + /// u16 words of a KV cache row for `n` values in the K format (and, separately, the V format). + /// `kv_row_words` is the size of one K row plus one V row. fn kv_words(&self, n: usize) -> usize; + fn kv_words_v(&self, n: usize) -> usize { self.kv_words(n) } + fn kv_row_words(&self, n: usize) -> usize { self.kv_words(n) + self.kv_words_v(n) } /// GEMM over a tile list: for each tile, positions m0 .. m0 + cnt get y[m, 0..rows] = W_tile x[xrow[m]] (x row m /// when `xrow` is 0). `tiles` is a device array of [w, m0 | cnt << 32]. `act`: 0 stores, 1 computes /// y = silu(y) * result (SwiGLU with the gate already in y), 2 adds to y; `| SAME_X` as below. `n_x`: rows of x diff --git a/src/cuda/kernels.cu b/src/cuda/kernels.cu index 7d0e0f90..76562a44 100644 --- a/src/cuda/kernels.cu +++ b/src/cuda/kernels.cu @@ -2527,14 +2527,17 @@ extern "C" __global__ void ple_conv(float* r, const float* gated, const float* n // ---- attention ---- -// KV cache rows (one per position and KV head) hold hd f16 values (KV_MODE 0), hd int8 values followed by hd / 32 f16 scales -// (KV_MODE 1, `--kv q8`), hd / 2 packed uint4 nibbles + hd / 32 f16 scales (KV_MODE 2, `--kv q4`), or affine 2-bit -// codes (hd / 4 B) + hd / 32 f16 scales + hd / 32 f16 mins (KV_MODE 3, `--kv q2`). Offsets below count values. -// KV_MODE 4 (`--kv turbo4`) stores the WHT-128-rotated vector in the q4 nibble layout with an fp16 norm: -// Lloyd-Max 4-bit centroids, so the rows hold rotated values. Q is rotated by the same WHT in the attention -// kernels and only the attention output is inverse-rotated (TheTom's llama-cpp-turboquant design), which avoids -// per-load de-rotation. This path is used by Inkling 2; other models keep the q4/q2 paths. -#if KV_MODE >= 4 +// KV cache rows (one per position and KV head) hold hd f16 values (mode 0), hd int8 values followed by hd / 32 f16 +// scales (mode 1, `--kv q8`), hd / 2 packed nibbles + hd / 32 f16 scales (mode 2, `--kv q4`), or affine 2-bit codes +// (hd / 4 B) + hd / 32 f16 scales + hd / 32 f16 mins (mode 3, `--kv q2`). Offsets below count values. Turbo modes +// (4/5/6) store the WHT-128-rotated vector in the nibble layout with one fp16 norm per 128-value group; Q is rotated +// by the same WHT in attention and only the output is inverse-rotated (TheTom's llama-cpp-turboquant design). +// K_MODE and V_MODE are independent: each half picks its own quantizer and bit width. +// Forward declarations so the mode-dispatched templates below parse even when neither side is turbo. +template __device__ __forceinline__ int tq_nearest(float v); +template __device__ __forceinline__ float tq_centroid(int q); +#if K_MODE >= 4 || V_MODE >= 4 +template __device__ __forceinline__ void kv_put_tq(u16* c, size_t e, int hd, float x, float norm); #ifndef TQ_KBITS #define TQ_KBITS 4 #endif @@ -2557,8 +2560,6 @@ static __constant__ float TQ_M3[7] = { -0.154496f,-0.092804f,-0.044243f,0.0f, 0.044243f, 0.092804f, 0.154496f}; static __constant__ float TQ_C2[4] = { -0.133462f, -0.039994f, 0.039994f, 0.133462f }; static __constant__ float TQ_M2[3] = { -0.086728f, 0.0f, 0.086728f }; -template __device__ __forceinline__ int tq_nearest(float v); -template __device__ __forceinline__ float tq_centroid(int q); template<> __device__ __forceinline__ int tq_nearest<4>(float v) { int i=0; for(;i<15;i++) if(v __device__ __forceinline__ float tq_centroid<4>(int q) { return TQ_C4[q]; } template<> __device__ __forceinline__ int tq_nearest<3>(float v) { int i=0; for(;i<7;i++) if(v> 1) & 1u); } +// Sum cs over the 128 threads that own one WHT group. All 128 threads of the group call this with the same g. +// A 256-thread caller with hd=128 sends its upper 128 threads through group 0 with identical cs; the duplicate +// shared writes carry the same value, so the result and the single norm slot are unchanged. +__device__ __forceinline__ float tq_group_sum(float cs, int g) { + float v = warp_sum(cs); + __shared__ float s[16]; // at most 4 groups per head, 4 warps each + int lane = threadIdx.x & 31, w = (threadIdx.x & 127) >> 5; + if (lane == 0) s[4 * g + w] = v; + __syncthreads(); + float t = lane < 4 ? s[4 * g + lane] : 0.0f; + __syncthreads(); // every thread has read the partials before a later call reuses s + return warp_sum(t); +} template __device__ __forceinline__ void kv_put_tq(u16* c, size_t e, int hd, float x, float norm) { int q = tq_nearest(x / norm); unsigned nib = (unsigned)q; unsigned pair = nib | (__shfl_xor_sync(0xffffffff, nib, 1) << 4); - int w = e % hd; + int we = e % hd; + int w = we & 127; // value within this 128-wide WHT group + int g = we >> 7; // WHT group within the head (0 when hd <= 128) unsigned char* r = (unsigned char*)c + e / hd * (hd / 2 + hd / 16); - if ((w & 1) == 0) r[w / 2] = (unsigned char)pair; + if ((we & 1) == 0) r[we / 2] = (unsigned char)pair; // The reference stores norm / ||reconstructed centroids||; without it dequant is systematically low. - float cq = tq_centroid(q); - float cs = cq * cq; - __syncthreads(); - float recon = sqrtf(block_sum(cs)); - if (w == 0) *(u16*)(r + hd / 2) = f2h(norm / fmaxf(recon, 1e-6f)); + float recon = sqrtf(tq_group_sum(tq_centroid(q) * tq_centroid(q), g)); + if (w == 0) *(u16*)(r + hd / 2 + 2 * g) = f2h(norm / fmaxf(recon, 1e-6f)); } #endif -#if KV_MODE == 3 __device__ __forceinline__ float warp_min(float v) { for (int o = 16; o > 0; o >>= 1) v = fminf(v, __shfl_xor_sync(0xffffffff, v, o)); return v; } +// One value into the cache at value offset e. M is this half's cache mode; BITS matters only for turbo modes. +template __device__ __forceinline__ void kv_put(u16* c, size_t e, int hd, float x) { - u16 mn_h = f2h(warp_min(x)); - float mn = h2f(mn_h), mx = warp_max(x), dr = fmaxf(0.0f, mx - mn) / 3.0f; - u16 d_h = f2h(dr); - float d = h2f(d_h), y = d == 0.0f ? 0.0f : (x - mn) / d; - int q = (int)roundf(y); - q = q < 0 ? 0 : (q > 3 ? 3 : q); - unsigned uq = (unsigned)q; - unsigned packed = uq - | (__shfl_xor_sync(0xffffffff, uq, 1) << 2) - | (__shfl_xor_sync(0xffffffff, uq, 2) << 4) - | (__shfl_xor_sync(0xffffffff, uq, 3) << 6); - int w = e % hd; - unsigned char* r = (unsigned char*)c + e / hd * (3 * hd / 8); - if ((w & 3) == 0) r[w / 4] = (unsigned char)packed; - if ((w & 31) == 0) { - *(u16*)(r + hd / 4 + 2 * (w / 32)) = d_h; - *(u16*)(r + hd / 4 + hd / 16 + 2 * (w / 32)) = mn_h; - } -} -#elif KV_MODE == 2 -// Quantize x into the cache at value offset e; the 32 lanes of the warp hold one 32-value block. -__device__ __forceinline__ void kv_put(u16* c, size_t e, int hd, float x) { - float d = warp_max(fabsf(x)) / 7.0f; - float y = d == 0.0f ? 0.0f : x / d; - int q = (int)roundf(y); - q = q < -7 ? -7 : (q > 7 ? 7 : q); - unsigned nib = (unsigned)(q + 8); - unsigned pair = nib | (__shfl_xor_sync(0xffffffff, nib, 1) << 4); - int w = e % hd; - unsigned char* r = (unsigned char*)c + e / hd * (hd / 2 + hd / 16); - if ((w & 1) == 0) r[w / 2] = (unsigned char)pair; - if ((w & 31) == 0) *(u16*)(r + hd / 2 + 2 * (w / 32)) = f2h(d); -} -#elif KV_MODE == 1 -// Quantize x into the cache at value offset e; the 32 lanes of the warp hold one 32-value block. -__device__ __forceinline__ void kv_put(u16* c, size_t e, int hd, float x) { - float d = warp_max(fabsf(x)) / 127.0f; - int w = e % hd; - char* r = (char*)c + e / hd * (hd + hd / 16); - r[w] = (signed char)(d == 0.0f ? 0.0f : roundf(x / d)); - if ((w & 31) == 0) *(u16*)(r + hd + 2 * (w / 32)) = f2h(d); + if constexpr (M == 3) { + u16 mn_h = f2h(warp_min(x)); + float mn = h2f(mn_h), mx = warp_max(x), dr = fmaxf(0.0f, mx - mn) / 3.0f; + u16 d_h = f2h(dr); + float d = h2f(d_h), y = d == 0.0f ? 0.0f : (x - mn) / d; + int q = (int)roundf(y); + q = q < 0 ? 0 : (q > 3 ? 3 : q); + unsigned uq = (unsigned)q; + unsigned packed = uq + | (__shfl_xor_sync(0xffffffff, uq, 1) << 2) + | (__shfl_xor_sync(0xffffffff, uq, 2) << 4) + | (__shfl_xor_sync(0xffffffff, uq, 3) << 6); + int w = e % hd; + unsigned char* r = (unsigned char*)c + e / hd * (3 * hd / 8); + if ((w & 3) == 0) r[w / 4] = (unsigned char)packed; + if ((w & 31) == 0) { + *(u16*)(r + hd / 4 + 2 * (w / 32)) = d_h; + *(u16*)(r + hd / 4 + hd / 16 + 2 * (w / 32)) = mn_h; + } + } else if constexpr (M == 2) { + // The 32 lanes of the warp hold one 32-value block. + float d = warp_max(fabsf(x)) / 7.0f; + float y = d == 0.0f ? 0.0f : x / d; + int q = (int)roundf(y); + q = q < -7 ? -7 : (q > 7 ? 7 : q); + unsigned nib = (unsigned)(q + 8); + unsigned pair = nib | (__shfl_xor_sync(0xffffffff, nib, 1) << 4); + int w = e % hd; + unsigned char* r = (unsigned char*)c + e / hd * (hd / 2 + hd / 16); + if ((w & 1) == 0) r[w / 2] = (unsigned char)pair; + if ((w & 31) == 0) *(u16*)(r + hd / 2 + 2 * (w / 32)) = f2h(d); + } else if constexpr (M == 1) { + // The 32 lanes of the warp hold one 32-value block. + float d = warp_max(fabsf(x)) / 127.0f; + int w = e % hd; + char* r = (char*)c + e / hd * (hd + hd / 16); + r[w] = (signed char)(d == 0.0f ? 0.0f : roundf(x / d)); + if ((w & 31) == 0) *(u16*)(r + hd + 2 * (w / 32)) = f2h(d); + } else { + c[e] = f2h(x); + } } + +// Single store entry for both halves: `norm` is each group's L2 norm under turbo modes, ignored otherwise. +template +__device__ __forceinline__ void kv_store_one(u16* c, size_t e, int hd, float x, float norm) { +#if K_MODE >= 4 || V_MODE >= 4 + if constexpr (M >= 4) kv_put_tq(c, e, hd, x, norm); + else kv_put(c, e, hd, x); #else -__device__ __forceinline__ void kv_put(u16* c, size_t e, int, float x) { c[e] = f2h(x); } + kv_put(c, e, hd, x); #endif +} // Store `total` values (consecutive tokens of n each, n a multiple of 32) starting at position step[0]. extern "C" __global__ void kv_store(const float* k, const float* v, u16* kc, u16* vc, int n, int total, const int* step, - int hd) { + int hd) { int i = blockIdx.x * blockDim.x + threadIdx.x, pos = step[0]; - if (i < total) { kv_put(kc, (size_t)pos * n + i, hd, k[i]); kv_put(vc, (size_t)pos * n + i, hd, v[i]); } + if (i < total) { + kv_store_one(kc, (size_t)pos * n + i, hd, k[i], 1.0f); + kv_store_one(vc, (size_t)pos * n + i, hd, v[i], 1.0f); + } } -// One 128-value KV block per 128-thread block: unit-L2 normalize, signed-Walsh rotate, Lloyd-Max quantize. -// Used by the general engine (Tiel Coder, Holo, GLM, DeepSeek); Inkling 2 stores through ink_clip instead. -// Defined for every KV_MODE so the eager kernel loader always finds the symbol; the body is turbo-only. +// One 128-value KV block per 128-thread block (2 blocks per 256-wide row): unit-L2 normalize, signed-Walsh +// rotate, Lloyd-Max quantize. Each half uses its own mode and bit width; a non-turbo half stores its raw value. +// Defined for every mode combination so the eager kernel loader always finds the symbol. extern "C" __global__ void __launch_bounds__(128) kv_store_turbo(const float* k, const float* v, u16* kc, u16* vc, - int n, int total, const int* step, int hd) { -#if KV_MODE >= 4 + int n, int total, const int* step, int hd) { +#if K_MODE >= 4 || V_MODE >= 4 __shared__ float kq[128], vq[128]; int t = threadIdx.x; size_t e = (size_t)blockIdx.x * 128 + t; - kq[t] = k[e]; - vq[t] = v[e]; + float kv = k[e], vv = v[e]; + kq[t] = kv; vq[t] = vv; __syncthreads(); - float sk = sqrtf(block_sum(kq[t] * kq[t])); - float sv = sqrtf(block_sum(vq[t] * vq[t])); - if (t < 32) { - float4 a = make_float4(kq[4*t], kq[4*t+1], kq[4*t+2], kq[4*t+3]); - float4 b = make_float4(vq[4*t], vq[4*t+1], vq[4*t+2], vq[4*t+3]); - tq_wht4(a, t, false); - tq_wht4(b, t, false); - kq[4*t]=a.x; kq[4*t+1]=a.y; kq[4*t+2]=a.z; kq[4*t+3]=a.w; - vq[4*t]=b.x; vq[4*t+1]=b.y; vq[4*t+2]=b.z; vq[4*t+3]=b.w; + float sk = 1.0f, sv = 1.0f; + if constexpr (K_MODE >= 4) sk = sqrtf(block_sum(kq[t] * kq[t])); + if constexpr (V_MODE >= 4) sv = sqrtf(block_sum(vq[t] * vq[t])); + if constexpr (K_MODE >= 4 || V_MODE >= 4) { + if (t < 32) { + float4 a = make_float4(kq[4*t], kq[4*t+1], kq[4*t+2], kq[4*t+3]); + float4 b = make_float4(vq[4*t], vq[4*t+1], vq[4*t+2], vq[4*t+3]); + if constexpr (K_MODE >= 4) tq_wht4(a, t, false); + if constexpr (V_MODE >= 4) tq_wht4(b, t, false); + kq[4*t]=a.x; kq[4*t+1]=a.y; kq[4*t+2]=a.z; kq[4*t+3]=a.w; + vq[4*t]=b.x; vq[4*t+1]=b.y; vq[4*t+2]=b.z; vq[4*t+3]=b.w; + } + __syncthreads(); } - __syncthreads(); size_t off = (size_t)step[0] * n + e; - kv_put_tq(kc, off, hd, kq[t], sk); + if constexpr (K_MODE >= 4) kv_put_tq(kc, off, hd, kq[t], sk); + else kv_store_one(kc, off, hd, kv, sk); __syncthreads(); - kv_put_tq(vc, off, hd, vq[t], sv); + if constexpr (V_MODE >= 4) kv_put_tq(vc, off, hd, vq[t], sv); + else kv_store_one(vc, off, hd, vv, sv); #endif } @@ -2748,7 +2778,50 @@ extern "C" __global__ void rms_norm_rope(const float* x, int x_stride, const flo if (kvt) { kc = (u16*)kvt[2 * tok]; vc = (u16*)kvt[2 * tok + 1]; } const float* vr = v + (size_t)b * n; size_t e = ((size_t)pos * per + b % per) * n; - for (int j = threadIdx.x; j < n; j += 256) { kv_put(kc, e + j, n, o[j]); kv_put(vc, e + j, n, vr[j]); } +#if K_MODE >= 4 || V_MODE >= 4 + // The general-engine attention kernels rotate Q with the same WHT, so the cached K/V must be rotated too. + // Stage one head in shared memory, rotate each 128-value group with one warp, then quantize with a norm + // per group. All 256 threads take part in the reductions: at n = 128 the upper half wraps onto the same + // values, and n = 512 is handled as two full 256-thread chunks. + __shared__ float tqk[512], tqv[512]; + for (int j = threadIdx.x; j < n; j += 256) { tqk[j] = o[j]; tqv[j] = vr[j]; } + __syncthreads(); + if (threadIdx.x < 32) { + for (int gi = 0; gi < n / 128; gi++) { + int base = gi * 128 + 4 * threadIdx.x; + if constexpr (K_MODE >= 4) { + float4 q = make_float4(tqk[base], tqk[base + 1], tqk[base + 2], tqk[base + 3]); + tq_wht4(q, threadIdx.x, false); + tqk[base] = q.x; tqk[base + 1] = q.y; tqk[base + 2] = q.z; tqk[base + 3] = q.w; + } + if constexpr (V_MODE >= 4) { + float4 q = make_float4(tqv[base], tqv[base + 1], tqv[base + 2], tqv[base + 3]); + tq_wht4(q, threadIdx.x, false); + tqv[base] = q.x; tqv[base + 1] = q.y; tqv[base + 2] = q.z; tqv[base + 3] = q.w; + } + } + } + __syncthreads(); + { + int chunks = n <= 256 ? 1 : n / 256; + for (int ch = 0; ch < chunks; ch++) { + int j = ch * 256 + threadIdx.x; + if (n == 128) j &= 127; + int g = j >> 7; + float xk = tqk[j], xv = tqv[j]; + float nk = 1.0f, nv = 1.0f; + if constexpr (K_MODE >= 4) nk = sqrtf(tq_group_sum(xk * xk, g)); + if constexpr (V_MODE >= 4) nv = sqrtf(tq_group_sum(xv * xv, g)); + kv_store_one(kc, e + j, n, xk, nk); + kv_store_one(vc, e + j, n, xv, nv); + } + } +#else + for (int j = threadIdx.x; j < n; j += 256) { + kv_store_one(kc, e + j, n, o[j], 1.0f); + kv_store_one(vc, e + j, n, vr[j], 1.0f); + } +#endif } #define INFINITY __int_as_float(0x7f800000) @@ -2767,76 +2840,76 @@ template __device__ __forceinline__ void ldh_raw(const u16* p, unsigne } } // PER consecutive cache values from value offset off (off a multiple of PER, PER <= 32) as f16 words, like ldh_raw. -template __device__ __forceinline__ void ldkv(const u16* c, size_t off, int hd, unsigned* o) { -#if KV_MODE >= 4 - // Dequantize to the rotated domain; Q is rotated in attention, so no inverse here. - int w = off % hd; - const unsigned char* r = (const unsigned char*)c + off / hd * (hd / 2 + hd / 16); - float norm = h2f(*(const u16*)(r + hd / 2)); - for (int i = 0; i < PER / 2; i++) { - unsigned b = r[w / 2 + i]; - int q0 = b & 15, q1 = b >> 4; - o[i] = (unsigned)f2h(tq_centroid(q0) * norm) | ((unsigned)f2h(tq_centroid(q1) * norm) << 16); - } -#elif KV_MODE == 3 - int w = off % hd; - const unsigned char* r = (const unsigned char*)c + off / hd * (3 * hd / 8); - float d = h2f(*(const u16*)(r + hd / 4 + 2 * (w / 32))); - float mn = h2f(*(const u16*)(r + hd / 4 + hd / 16 + 2 * (w / 32))); - for (int i = 0; i < PER / 2; i++) { - int wi = w + 2 * i; - unsigned b = r[wi / 4]; - int s = (b >> (2 * (wi & 2))) & 15; - int q0 = s & 3, q1 = s >> 2; - o[i] = (unsigned)f2h(fmaf((float)q0, d, mn)) | ((unsigned)f2h(fmaf((float)q1, d, mn)) << 16); - } -#elif KV_MODE == 2 - int w = off % hd; - const unsigned char* r = (const unsigned char*)c + off / hd * (hd / 2 + hd / 16); - float d = h2f(*(const u16*)(r + hd / 2 + 2 * (w / 32))); - for (int i = 0; i < PER / 2; i++) { - unsigned b = r[w / 2 + i]; - int q0 = (int)(b & 15u) - 8, q1 = (int)(b >> 4) - 8; - o[i] = (unsigned)f2h((float)q0 * d) | ((unsigned)f2h((float)q1 * d) << 16); - } -#elif KV_MODE == 1 - int w = off % hd; - const char* r = (const char*)c + off / hd * (hd + hd / 16); - unsigned d = *(const u16*)(r + hd + 2 * (w / 32)) * 0x10001u; // scale in both halves - // Byte q (flipped to q + 128) under exponent byte 0x64 is the f16 1024 + q + 128; minus 1152 gives q exactly, and - // q * d rounded once to f16 equals f2h((float)q * d). - auto deq = [&](unsigned x, unsigned sel) { - unsigned h = __byte_perm(x ^ 0x80808080u, 0x64646464u, sel), r; +template __device__ __forceinline__ void ldkv(const u16* c, size_t off, int hd, unsigned* o) { + if constexpr (M >= 4) { + // Dequantize to the rotated domain; Q is rotated in attention, so no inverse here. + int we = off % hd; + const unsigned char* r = (const unsigned char*)c + off / hd * (hd / 2 + hd / 16); + float norm = h2f(*(const u16*)(r + hd / 2 + 2 * (we >> 7))); + for (int i = 0; i < PER / 2; i++) { + unsigned b = r[we / 2 + i]; + int q0 = b & 15, q1 = b >> 4; + o[i] = (unsigned)f2h(tq_centroid(q0) * norm) | ((unsigned)f2h(tq_centroid(q1) * norm) << 16); + } + } else if constexpr (M == 3) { + int w = off % hd; + const unsigned char* r = (const unsigned char*)c + off / hd * (3 * hd / 8); + float d = h2f(*(const u16*)(r + hd / 4 + 2 * (w / 32))); + float mn = h2f(*(const u16*)(r + hd / 4 + hd / 16 + 2 * (w / 32))); + for (int i = 0; i < PER / 2; i++) { + int wi = w + 2 * i; + unsigned b = r[wi / 4]; + int s = (b >> (2 * (wi & 2))) & 15; + int q0 = s & 3, q1 = s >> 2; + o[i] = (unsigned)f2h(fmaf((float)q0, d, mn)) | ((unsigned)f2h(fmaf((float)q1, d, mn)) << 16); + } + } else if constexpr (M == 2) { + int w = off % hd; + const unsigned char* r = (const unsigned char*)c + off / hd * (hd / 2 + hd / 16); + float d = h2f(*(const u16*)(r + hd / 2 + 2 * (w / 32))); + for (int i = 0; i < PER / 2; i++) { + unsigned b = r[w / 2 + i]; + int q0 = (int)(b & 15u) - 8, q1 = (int)(b >> 4) - 8; + o[i] = (unsigned)f2h((float)q0 * d) | ((unsigned)f2h((float)q1 * d) << 16); + } + } else if constexpr (M == 1) { + int w = off % hd; + const char* r = (const char*)c + off / hd * (hd + hd / 16); + unsigned d = *(const u16*)(r + hd + 2 * (w / 32)) * 0x10001u; // scale in both halves + // Byte q (flipped to q + 128) under exponent byte 0x64 is the f16 1024 + q + 128; minus 1152 gives q exactly, and + // q * d rounded once to f16 equals f2h((float)q * d). + auto deq = [&](unsigned x, unsigned sel) { + unsigned h = __byte_perm(x ^ 0x80808080u, 0x64646464u, sel), r; #if STRATA_HIP - // Same two f16 lanes without : a 2-element _Float16 vector (the ISA's packed f16 sub/mul). - typedef _Float16 f16x2 __attribute__((ext_vector_type(2))); - unsigned c64 = 0x64806480u; - f16x2 hh = *(f16x2*)&h, cc = *(f16x2*)&c64, dd = *(f16x2*)&d, rr; - rr[0] = (hh[0] - cc[0]) * dd[0]; - rr[1] = (hh[1] - cc[1]) * dd[1]; - r = *(unsigned*)&rr; + // Same two f16 lanes without : a 2-element _Float16 vector (the ISA's packed f16 sub/mul). + typedef _Float16 f16x2 __attribute__((ext_vector_type(2))); + unsigned c64 = 0x64806480u; + f16x2 hh = *(f16x2*)&h, cc = *(f16x2*)&c64, dd = *(f16x2*)&d, rr; + rr[0] = (hh[0] - cc[0]) * dd[0]; + rr[1] = (hh[1] - cc[1]) * dd[1]; + r = *(unsigned*)&rr; #else - asm("sub.rn.f16x2 %0, %1, %2;" : "=r"(h) : "r"(h), "r"(0x64806480u)); - asm("mul.rn.f16x2 %0, %1, %2;" : "=r"(r) : "r"(h), "r"(d)); + asm("sub.rn.f16x2 %0, %1, %2;" : "=r"(h) : "r"(h), "r"(0x64806480u)); + asm("mul.rn.f16x2 %0, %1, %2;" : "=r"(r) : "r"(h), "r"(d)); #endif - return r; - }; - if (PER % 8 == 0 && hd % 128 == 0) { // rows 8-byte aligned - for (int i = 0; i < PER / 8; i++) { - uint2 x = ((const uint2*)(r + w))[i]; - o[4 * i] = deq(x.x, 0x4140); o[4 * i + 1] = deq(x.x, 0x4342); o[4 * i + 2] = deq(x.y, 0x4140); o[4 * i + 3] = deq(x.y, 0x4342); - } - } else if constexpr (PER % 4 == 0) { - for (int i = 0; i < PER / 4; i++) { - unsigned x = ((const unsigned*)(r + w))[i]; - o[2 * i] = deq(x, 0x4140); o[2 * i + 1] = deq(x, 0x4342); + return r; + }; + if (PER % 8 == 0 && hd % 128 == 0) { // rows 8-byte aligned + for (int i = 0; i < PER / 8; i++) { + uint2 x = ((const uint2*)(r + w))[i]; + o[4 * i] = deq(x.x, 0x4140); o[4 * i + 1] = deq(x.x, 0x4342); o[4 * i + 2] = deq(x.y, 0x4140); o[4 * i + 3] = deq(x.y, 0x4342); + } + } else if constexpr (PER % 4 == 0) { + for (int i = 0; i < PER / 4; i++) { + unsigned x = ((const unsigned*)(r + w))[i]; + o[2 * i] = deq(x, 0x4140); o[2 * i + 1] = deq(x, 0x4342); + } + } else { + for (int i = 0; i < PER / 2; i++) o[i] = deq(*(const u16*)(r + w + 2 * i), 0x4140); } } else { - for (int i = 0; i < PER / 2; i++) o[i] = deq(*(const u16*)(r + w + 2 * i), 0x4140); + ldh_raw(c + off, o); } -#else - ldh_raw(c + off, o); -#endif } // f16 value d of words loaded by ldh_raw. __device__ __forceinline__ float hraw(const unsigned* r, int d) { return h2f((u16)(r[d >> 1] >> (16 * (d & 1)))); } @@ -2869,43 +2942,56 @@ template __device__ __forceinline__ float warp_sum_scatte __device__ __forceinline__ float rh(float x) { return h2f(f2h(x)); } // Scalar KV element load matching GLSL ldkv(). -template __device__ __forceinline__ float ldkv1(const u16* c, size_t off, int hd) { -#if KV_MODE >= 4 - int w = off % hd; - const unsigned char* r = (const unsigned char*)c + off / hd * (hd / 2 + hd / 16); - float norm = h2f(*(const u16*)(r + hd / 2)); - unsigned b = r[w / 2]; - int q = (w & 1) == 0 ? (int)(b & 15u) : (int)(b >> 4); - return rh(tq_centroid(q) * norm); -#elif KV_MODE == 3 - int w = off % hd; - const unsigned char* r = (const unsigned char*)c + off / hd * (3 * hd / 8); - unsigned b = r[w / 4]; - float d = h2f(*(const u16*)(r + hd / 4 + 2 * (w / 32))); - float mn = h2f(*(const u16*)(r + hd / 4 + hd / 16 + 2 * (w / 32))); - int q = (b >> (2 * (w & 3))) & 3; - return rh(fmaf((float)q, d, mn)); -#elif KV_MODE == 2 - int w = off % hd; - const unsigned char* r = (const unsigned char*)c + off / hd * (hd / 2 + hd / 16); - unsigned b = r[w / 2]; - float d = h2f(*(const u16*)(r + hd / 2 + 2 * (w / 32))); - int q = (int)((w & 1) == 0 ? (b & 15u) : (b >> 4)) - 8; - return rh((float)q * d); -#elif KV_MODE == 1 - int w = off % hd; - const signed char* r = (const signed char*)c + off / hd * (hd + hd / 16); - float d = h2f(*(const u16*)(r + hd + 2 * (w / 32))); - return rh((float)r[w] * d); -#else - return h2f(c[off]); -#endif +template __device__ __forceinline__ float ldkv1(const u16* c, size_t off, int hd) { + if constexpr (M >= 4) { + int we = off % hd; + const unsigned char* r = (const unsigned char*)c + off / hd * (hd / 2 + hd / 16); + float norm = h2f(*(const u16*)(r + hd / 2 + 2 * (we >> 7))); + unsigned b = r[we / 2]; + int q = (we & 1) == 0 ? (int)(b & 15u) : (int)(b >> 4); + return rh(tq_centroid(q) * norm); + } else if constexpr (M == 3) { + int w = off % hd; + const unsigned char* r = (const unsigned char*)c + off / hd * (3 * hd / 8); + unsigned b = r[w / 4]; + float d = h2f(*(const u16*)(r + hd / 4 + 2 * (w / 32))); + float mn = h2f(*(const u16*)(r + hd / 4 + hd / 16 + 2 * (w / 32))); + int q = (b >> (2 * (w & 3))) & 3; + return rh(fmaf((float)q, d, mn)); + } else if constexpr (M == 2) { + int w = off % hd; + const unsigned char* r = (const unsigned char*)c + off / hd * (hd / 2 + hd / 16); + unsigned b = r[w / 2]; + float d = h2f(*(const u16*)(r + hd / 2 + 2 * (w / 32))); + int q = (int)((w & 1) == 0 ? (b & 15u) : (b >> 4)) - 8; + return rh((float)q * d); + } else if constexpr (M == 1) { + int w = off % hd; + const signed char* r = (const signed char*)c + off / hd * (hd + hd / 16); + float d = h2f(*(const u16*)(r + hd + 2 * (w / 32))); + return rh((float)r[w] * d); + } else { + return h2f(c[off]); + } } -// One block of 128 per (row, tok) of w values (w at most 128, w % 32 == 0 when KV_MODE > 0 and dst != 0). +// One block of 128 per (row, tok) of w values (w at most 128, w % 32 == 0 when a side is quantized and dst != 0). +#if K_MODE >= 4 || V_MODE >= 4 +template __device__ __forceinline__ void ink_tq_store(u16* dst, size_t dat, int t, int w, float v, float* tq, float norm) { + tq[t] = v; + __syncthreads(); + if (t < 32) { + float4 q = make_float4(tq[4*t], tq[4*t+1], tq[4*t+2], tq[4*t+3]); + tq_wht4(q, t, false); + tq[4*t]=q.x; tq[4*t+1]=q.y; tq[4*t+2]=q.z; tq[4*t+3]=q.w; + } + __syncthreads(); + kv_put_tq(dst, dat, w, tq[t], norm); +} +#endif extern "C" __global__ void ink_clip(float* x, const float* scale, int w, float thr, float eps, float mul, u16* dst, - int dst_at0, int dst_ring, int pos0, float log_alpha, float log_floor, const int* pos_ptr) { -#if KV_MODE >= 4 + int dst_at0, int dst_ring, int pos0, float log_alpha, float log_floor, const int* pos_ptr) { +#if K_MODE >= 4 || V_MODE >= 4 __shared__ float tq[128]; #endif int t = threadIdx.x, row = blockIdx.x, tok = blockIdx.y, rows = gridDim.x; @@ -2924,24 +3010,20 @@ extern "C" __global__ void ink_clip(float* x, const float* scale, int w, float t if (dst) { size_t dst_pos = (size_t)((eff_dst_at0 + tok) % dst_ring); size_t dat = (dst_pos * rows + row) * w + t; -#if KV_MODE >= 4 - if (w == 128) { - tq[t] = v; - __syncthreads(); - if (t < 32) { - if (w == 128) { float4 q = make_float4(tq[4*t], tq[4*t+1], tq[4*t+2], tq[4*t+3]); tq_wht4(q, t, false); tq[4*t]=q.x; tq[4*t+1]=q.y; tq[4*t+2]=q.z; tq[4*t+3]=q.w; } - else { float2 q = make_float2(tq[2*t], tq[2*t+1]); tq_wht2(q, t, false); tq[2*t]=q.x; tq[2*t+1]=q.y; } - } - __syncthreads(); - // Centroids are for N(0, 1/128) (unit-L2 vectors); ss was measured before the clip scale f, - // so the rotated vector's L2 is sqrt(ss)*f and x / L2 matches the centroid distribution. - int bits = thr > 0.f ? TQ_KBITS : TQ_VBITS; - if (bits == 4) kv_put_tq<4>(dst, dat, w, tq[t], sqrtf(ss) * f); - else if (bits == 3) kv_put_tq<3>(dst, dat, w, tq[t], sqrtf(ss) * f); - else kv_put_tq<2>(dst, dat, w, tq[t], sqrtf(ss) * f); - } else + // thr > 0 selects the K clip, otherwise the V clip; each half has its own cache mode. + if (thr > 0.f) { +#if K_MODE >= 4 + if (w == 128) ink_tq_store(dst, dat, t, w, v, tq, sqrtf(ss) * f); + else +#endif + kv_store_one(dst, dat, w, v, 1.0f); + } else { +#if V_MODE >= 4 + if (w == 128) ink_tq_store(dst, dat, t, w, v, tq, sqrtf(ss) * f); + else #endif - kv_put(dst, dat, w, v); + kv_store_one(dst, dat, w, v, 1.0f); + } } } } @@ -2959,9 +3041,16 @@ extern "C" __global__ void ink_attn(const float* q, const float* r, const float* int i0 = blockIdx.y * 64, n = i0 < rows ? min(64, rows - i0) : 0; if (t < hd) qs[t] = q[h * hd + t]; __syncthreads(); -#if KV_MODE >= 4 +#if K_MODE >= 4 // Rotate Q into the KV domain; the scores below are = . - if (hd == 128 && t < 32) { float4 v = make_float4(qs[4*t], qs[4*t+1], qs[4*t+2], qs[4*t+3]); tq_wht4(v, t, false); qs[4*t]=v.x; qs[4*t+1]=v.y; qs[4*t+2]=v.z; qs[4*t+3]=v.w; } + for (int g = 0; g < hd / 128; g++) { + int base = g * 128 + 4 * t; + if (t < 32) { + float4 v = make_float4(qs[base], qs[base+1], qs[base+2], qs[base+3]); + tq_wht4(v, t, false); + qs[base]=v.x; qs[base+1]=v.y; qs[base+2]=v.z; qs[base+3]=v.w; + } + } if (hd == 64 && t < 32) { float2 v = make_float2(qs[2*t], qs[2*t+1]); tq_wht2(v, t, false); qs[2*t]=v.x; qs[2*t+1]=v.y; } __syncthreads(); #endif @@ -2970,7 +3059,7 @@ extern "C" __global__ void ink_attn(const float* q, const float* r, const float* int i = i0 + j, dist = at - i < 0 ? at - i + rows : at - i; size_t ko = (size_t)i * kw + kh * hd; float d = 0.f; - for (int c = lane; c < hd; c += 32) d += qs[c] * ldkv1(k, ko + c, hd); + for (int c = lane; c < hd; c += 32) d += qs[c] * ldkv1(k, ko + c, hd); d *= scale; if (dist < ext) for (int c = lane; c < nr; c += 32) d += r[h * nr + c] * bias[dist * nr + c]; d = warp_sum(d); @@ -2984,20 +3073,29 @@ extern "C" __global__ void ink_attn(const float* q, const float* r, const float* __syncthreads(); int c = t % hd, parts = 128 / hd; float a = 0.f; - for (int j = t / hd; j < n; j += parts) a += ps[j] * ldkv1(v, (size_t)(i0 + j) * kw + kh * hd + c, hd); + for (int j = t / hd; j < n; j += parts) a += ps[j] * ldkv1(v, (size_t)(i0 + j) * kw + kh * hd + c, hd); acc[t] = a; __syncthreads(); float* o = sc + ((size_t)h * gridDim.y + blockIdx.y) * (hd + 2); -#if KV_MODE >= 4 +#if V_MODE >= 4 if (t < hd) { float s = 0.f; for (int p = 0; p < parts; p++) s += acc[p * hd + t]; acc[t] = s; } __syncthreads(); - // Only the attention output is inverse-rotated: one WHT per head instead of one per KV load. - if (hd == 128 && t < 32) { float4 v = make_float4(acc[4*t], acc[4*t+1], acc[4*t+2], acc[4*t+3]); tq_wht4(v, t, true); o[2+4*t]=v.x; o[2+4*t+1]=v.y; o[2+4*t+2]=v.z; o[2+4*t+3]=v.w; } - else if (hd == 64 && t < 32) { float2 v = make_float2(acc[2*t], acc[2*t+1]); tq_wht2(v, t, true); o[2+2*t]=v.x; o[2+2*t+1]=v.y; } + // Only the attention output is inverse-rotated: one WHT per 128-value group instead of one per KV load. + // The unrotated copy must not overwrite the rotated output for lanes that did not take part in the WHT. + if (hd >= 128) { + for (int g = 0; g < hd / 128; g++) { + int base = g * 128 + 4 * t; + if (t < 32) { + float4 v = make_float4(acc[base], acc[base+1], acc[base+2], acc[base+3]); + tq_wht4(v, t, true); + o[2+base]=v.x; o[2+base+1]=v.y; o[2+base+2]=v.z; o[2+base+3]=v.w; + } + } + } else if (hd == 64 && t < 32) { float2 v = make_float2(acc[2*t], acc[2*t+1]); tq_wht2(v, t, true); o[2+2*t]=v.x; o[2+2*t+1]=v.y; } else if (t < hd) o[2 + t] = acc[t]; #else if (t < hd) { @@ -3042,14 +3140,19 @@ __device__ void ink_attn_prefill_t(const float* q, const float* r, const float* int start = (win > 0 && q_pos + 1 > win) ? (q_pos + 1 - win) : 0; float scale = 1.f / sqrtf((float)HD); float qv[PER], acc[PER]; + // Four consecutive dims per lane, repeated once per 128-wide WHT group (one group at HD=128, two at 256). + auto dim = [&](int j) { return PER >= 4 ? (j >> 2) * 128 + 4 * lane + (j & 3) : 4 * lane + j; }; for (int j = 0; j < PER; j++) { - // Keep the values in contiguous element order 4*lane+j so tq_wht4's sign bits match the elements. - qv[j] = q[((size_t)t * nh + h) * HD + 4 * lane + j] * scale; + qv[j] = q[((size_t)t * nh + h) * HD + dim(j)] * scale; acc[j] = 0.f; } -#if KV_MODE >= 4 - if (PER == 4) { float4 v = {qv[0], qv[1], qv[2], qv[3]}; tq_wht4(v, lane, false); qv[0]=v.x; qv[1]=v.y; qv[2]=v.z; qv[3]=v.w; } - else if (PER == 2) { float2 v = {qv[0], qv[1]}; tq_wht2(v, lane, false); qv[0]=v.x; qv[1]=v.y; } +#if K_MODE >= 4 + for (int g = 0; g < PER / 4; g++) { + float4 v = {qv[4*g], qv[4*g+1], qv[4*g+2], qv[4*g+3]}; + tq_wht4(v, lane, false); + qv[4*g]=v.x; qv[4*g+1]=v.y; qv[4*g+2]=v.z; qv[4*g+3]=v.w; + } + if (PER == 2) { float2 v = {qv[0], qv[1]}; tq_wht2(v, lane, false); qv[0]=v.x; qv[1]=v.y; } #endif float sink_val = sink[(size_t)t * nh + h]; float r_reg = (nr <= 32 && lane < nr) ? r[((size_t)t * nh + h) * nr + lane] : 0.f; @@ -3061,7 +3164,7 @@ __device__ void ink_attn_prefill_t(const float* q, const float* r, const float* size_t row = use_new ? (size_t)(kp - pos) : (win > 0 ? (size_t)(kp % ring) : (size_t)kp); size_t kbase = row * kw + (size_t)kh * HD; float s = 0.f; - for (int j = 0; j < PER; j++) s += qv[j] * ldkv1(kbuf, kbase + 4 * lane + j, HD); + for (int j = 0; j < PER; j++) s += qv[j] * ldkv1(kbuf, kbase + dim(j), HD); s = warp_sum(s); int dist = q_pos - kp; float b = 0.f; @@ -3076,18 +3179,22 @@ __device__ void ink_attn_prefill_t(const float* q, const float* r, const float* float logit = s + b - sink_val; float mn = fmaxf(m, logit), c = expf(m - mn), e = expf(logit - mn); l = l * c + e; - for (int j = 0; j < PER; j++) acc[j] = e * ldkv1(vbuf, kbase + 4 * lane + j, HD) + acc[j] * c; + for (int j = 0; j < PER; j++) acc[j] = e * ldkv1(vbuf, kbase + dim(j), HD) + acc[j] * c; m = mn; } float inv = 1.f / l; float ov[PER]; for (int j = 0; j < PER; j++) ov[j] = acc[j] * inv; -#if KV_MODE >= 4 - if (PER == 4) { float4 v = {ov[0], ov[1], ov[2], ov[3]}; tq_wht4(v, lane, true); ov[0]=v.x; ov[1]=v.y; ov[2]=v.z; ov[3]=v.w; } - else if (PER == 2) { float2 v = {ov[0], ov[1]}; tq_wht2(v, lane, true); ov[0]=v.x; ov[1]=v.y; } +#if V_MODE >= 4 + for (int g = 0; g < PER / 4; g++) { + float4 v = {ov[4*g], ov[4*g+1], ov[4*g+2], ov[4*g+3]}; + tq_wht4(v, lane, true); + ov[4*g]=v.x; ov[4*g+1]=v.y; ov[4*g+2]=v.z; ov[4*g+3]=v.w; + } + if (PER == 2) { float2 v = {ov[0], ov[1]}; tq_wht2(v, lane, true); ov[0]=v.x; ov[1]=v.y; } #endif for (int j = 0; j < PER; j++) { - int col = 4 * lane + j; + int col = dim(j); size_t idx = ((size_t)t * nh + h) * HD + col; outp[idx] = ov[j] * sigmoid(gate[idx]); } @@ -3188,13 +3295,16 @@ __device__ void attn_decode_t(const float* q, const u16* kc, const u16* vc, floa __shared__ float ss[G][C], sc[G], sm[G], sl[G]; int h0 = bx * G, g = h0 / (nh / nkv), w = threadIdx.x >> 5, lane = threadIdx.x & 31, nw = blockDim.x >> 5; for (int i = threadIdx.x; i < G * hd; i += blockDim.x) sq[i] = q[h0 * hd + i]; -#if KV_MODE >= 4 && hd == 128 +#if K_MODE >= 4 __syncthreads(); if (w == 0) { for (int i = 0; i < G; i++) { - float4 v = make_float4(sq[i*hd + 4*lane], sq[i*hd + 4*lane+1], sq[i*hd + 4*lane+2], sq[i*hd + 4*lane+3]); - tq_wht4(v, lane, false); - sq[i*hd + 4*lane]=v.x; sq[i*hd + 4*lane+1]=v.y; sq[i*hd + 4*lane+2]=v.z; sq[i*hd + 4*lane+3]=v.w; + for (int gg = 0; gg < hd / 128; gg++) { + int base = i * hd + gg * 128 + 4 * lane; + float4 v = make_float4(sq[base], sq[base+1], sq[base+2], sq[base+3]); + tq_wht4(v, lane, false); + sq[base]=v.x; sq[base+1]=v.y; sq[base+2]=v.z; sq[base+3]=v.w; + } } } __syncthreads(); @@ -3238,7 +3348,7 @@ __device__ void attn_decode_t(const float* q, const u16* kc, const u16* vc, floa if constexpr (!KV1) ldh_raw(sk + C * hd, vr[j]); } else { size_t r = ((size_t)cell(min(t, p1 - 1)) * nkv + g) * hd + lane * PER; - ldkv(kc, r, hd, kr[j]); ldkv(vc, r, hd, vr[j]); + ldkv(kc, r, hd, kr[j]); ldkv(vc, r, hd, vr[j]); } for (int d = 0; d < PER / 2; d++) if (t >= p1) kr[j][d] = vr[j][d] = 0; } @@ -3351,7 +3461,7 @@ __device__ void attn_decode_t(const float* q, const u16* kc, const u16* vc, floa #define ATT_TOK int t = blockIdx.x % nt; q += (size_t)t * nh * hd; part += (size_t)t * pz; step += 2 * t; if (sel) sel += (size_t)t * sst; \ if (kvt) { kc = (const u16*)kvt[2 * t]; vc = (const u16*)kvt[2 * t + 1]; } #define ATT_RUN(G) attn_decode_t(q, kc, vc, part, step, sel, nh, nkv, scale, blockIdx.x / nt, win) -#define ATT_RUN_CP(G) attn_decode_t= 800))>(q, kc, vc, part, step, sel, nh, nkv, scale, blockIdx.x / nt, win) +#define ATT_RUN_CP(G) attn_decode_t= 800))>(q, kc, vc, part, step, sel, nh, nkv, scale, blockIdx.x / nt, win) #define DEF_ATT(HD) \ extern "C" __global__ void attn_decode_##HD(ATT_ARGS) { \ constexpr int PER = HD / 32; ATT_TOK \ @@ -3375,7 +3485,7 @@ DEF_ATT(64) DEF_ATT(128) DEF_ATT(256) DEF_ATT(512) extern "C" __global__ void __launch_bounds__(256, 3) attn_decode_gqa4_128(ATT_ARGS) { constexpr int PER = 4; ATT_TOK if (step[0] + 1 < gq_min) return; - if constexpr (KV_MODE == 0) attn_decode_t(q, kc, vc, part, step, sel, nh, nkv, scale, blockIdx.x / nt, win); + if constexpr (K_MODE == 0 && V_MODE == 0) attn_decode_t(q, kc, vc, part, step, sel, nh, nkv, scale, blockIdx.x / nt, win); } // grid = query heads: out = (sum of split partials) / (sum of split sums) * sigmoid(gate), gate skipped when qg is null. Split 0 is never empty. @@ -3389,8 +3499,8 @@ extern "C" __global__ void attn_merge(const float* part, const float* qg, float* if (step[0] + 1 < gq_min) ns = ns1; // attn_decode ran, not attn_decode_gqa const float* pp = part + (size_t)h * ns * (hd + 2); __shared__ float ws[256]; // split max, then split weight (ns <= blockDim.x <= 256) -#if KV_MODE >= 4 && hd == 128 - __shared__ float ro[128]; // ungated attention output in the rotated domain +#if V_MODE >= 4 + __shared__ float ro[512]; // ungated attention output in the rotated domain (hd <= 512) #endif if (threadIdx.x < ns) ws[threadIdx.x] = pp[threadIdx.x * (hd + 2) + hd]; __syncthreads(); @@ -3406,7 +3516,7 @@ extern "C" __global__ void attn_merge(const float* part, const float* qg, float* float o = 0.0f; for (int s = 0; s < ns; s++) o += pp[s * (hd + 2) + d] * ws[s]; o = o / L; -#if KV_MODE >= 4 && hd == 128 +#if V_MODE >= 4 ro[d] = o; #else out[h * hd + d] = o * (qg ? sigmoid(qg[h * 2 * hd + hd + d]) : 1.0f); @@ -3418,12 +3528,15 @@ extern "C" __global__ void attn_merge(const float* part, const float* qg, float* } #endif } -#if KV_MODE >= 4 && hd == 128 +#if V_MODE >= 4 __syncthreads(); - if (threadIdx.x < 32) { - float4 v = make_float4(ro[4*threadIdx.x], ro[4*threadIdx.x+1], ro[4*threadIdx.x+2], ro[4*threadIdx.x+3]); - tq_wht4(v, threadIdx.x, true); - ro[4*threadIdx.x]=v.x; ro[4*threadIdx.x+1]=v.y; ro[4*threadIdx.x+2]=v.z; ro[4*threadIdx.x+3]=v.w; + for (int g = 0; g < hd / 128; g++) { + int base = g * 128 + 4 * threadIdx.x; + if (threadIdx.x < 32) { + float4 v = make_float4(ro[base], ro[base+1], ro[base+2], ro[base+3]); + tq_wht4(v, threadIdx.x, true); + ro[base]=v.x; ro[base+1]=v.y; ro[base+2]=v.z; ro[base+3]=v.w; + } } __syncthreads(); for (int d = threadIdx.x; d < hd; d += blockDim.x) { @@ -3639,8 +3752,8 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co constexpr int FA_BKL = FA_BK_FOR(HD); extern __shared__ __align__(16) u16 fa_sm[]; u16 *qs = fa_sm, *ks = qs + FA_BQ * PQ, *vs = ks + FA_BKL * PQ; -#if KV_MODE >= 4 && HD == 128 - __shared__ float tro[2][128]; // ungated output of the two query rows, before inverse WHT +#if V_MODE >= 4 + __shared__ float tro[2][HD]; // ungated output of the two query rows, before inverse WHT #endif #if __CUDA_ARCH__ < 800 && GEMM_TC // Volta only: warp-private P tile for the PV A fragments (see the staging in the PV step below). Appended after @@ -3662,8 +3775,8 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co for (int i = tid; i < FA_BQ * HD / 4; i += 128) { int r = i / (HD / 4), c = (i % (HD / 4)) * 4; float4 v = q0 + r < T ? *(const float4*)(q + (size_t)(q0 + r) * nh * HD + h * HD + c) : make_float4(0.f, 0.f, 0.f, 0.f); -#if KV_MODE >= 4 && HD == 128 - tq_wht4(v, c >> 2, false); // lane owns 4 consecutive dims of the 128-value head block +#if K_MODE >= 4 + tq_wht4(v, (c >> 2) & 31, false); // lane owns 4 dims of one 128-value WHT group (group = (c >> 2) >> 5) #endif *(uint2*)(qs + r * PQ + c) = make_uint2(h2pack(v.x * scale, v.y * scale), h2pack(v.z * scale, v.w * scale)); } @@ -3678,7 +3791,7 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co float mT[2][2] = {{-INFINITY, -INFINITY}, {-INFINITY, -INFINITY}}, lT[2][2] = {}; #endif constexpr int N = FA_BKL * HD / 8 / 128; -#if KV_MODE == 0 +#if K_MODE == 0 && V_MODE == 0 // f16: copy the V tile while the scores use K, and the next K tile while the sums use V (one block per SM, // so nothing else hides the loads); cp.async on sm_80+, a blocking copy at the same program point on sm_70. // Rows past `last` are zero-filled (synchronous path: the source is not read at all). @@ -3694,7 +3807,7 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co ld(0, vs, vc); #endif for (int k0 = 0; k0 <= last; k0 += FA_BKL) { -#if KV_MODE > 0 +#if K_MODE > 0 || V_MODE > 0 __syncthreads(); // All of a thread's loads, then its stores: with q8 the dequant between them kept the compiler from // overlapping the loads. Rows past `last` load the row `last` and store zeros. @@ -3703,7 +3816,7 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co for (int n = 0; n < N; n++) { int i = tid + n * 128, r = i / (HD / 8), c = (i % (HD / 8)) * 8; size_t off = (size_t)min(k0 + r, last) * kvd + kvh * HD + c; - ldkv<8, TQ_KBITS>(kc, off, HD, (unsigned*)&kv[n]); ldkv<8, TQ_VBITS>(vc, off, HD, (unsigned*)&vv[n]); + ldkv(kc, off, HD, (unsigned*)&kv[n]); ldkv(vc, off, HD, (unsigned*)&vv[n]); } #pragma unroll for (int n = 0; n < N; n++) { @@ -3805,7 +3918,7 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co } } #endif -#if KV_MODE == 0 +#if K_MODE == 0 && V_MODE == 0 __syncthreads(); if (k0 + FA_BKL <= last) ld(k0 + FA_BKL, ks, kc); else cp_async_commit(); // keep one group per tile for the waits (sm_80+; nothing to commit on sm_70) @@ -3893,7 +4006,7 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co for (int d = 0; d < HD / 8; d++) { o[d][0] *= c[0]; o[d][1] *= c[0]; o[d][2] *= c[1]; o[d][3] *= c[1]; } } #endif -#if KV_MODE == 0 +#if K_MODE == 0 && V_MODE == 0 cp_async_wait<1>(); // sm_80+: this V tile, the next K tile may still be in flight; sm_70: already copied here __syncthreads(); #endif @@ -3989,7 +4102,7 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co } } #endif -#if KV_MODE == 0 +#if K_MODE == 0 && V_MODE == 0 __syncthreads(); if (k0 + FA_BKL <= last) ld(k0 + FA_BKL, vs, vc); else cp_async_commit(); // keep one group per tile for the waits (sm_80+; nothing to commit on sm_70) @@ -4051,22 +4164,25 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co for (int d = 0; d < HD / 8; d++) for (int e = 0; e < 2; e++) { int col = d * 8 + 2 * t4 + e; -#if KV_MODE >= 4 && HD == 128 +#if V_MODE >= 4 tro[r][col] = o[d][2 * r + e] * inv; #else orow[col] = o[d][2 * r + e] * inv * (gate ? sigmoid(gate[col]) : 1.0f); #endif } } -#if KV_MODE >= 4 && HD == 128 +#if V_MODE >= 4 __syncthreads(); - for (int r = 0; r < 2; r++) { - if (tid < 32) { - float4 v = make_float4(tro[r][4*tid], tro[r][4*tid+1], tro[r][4*tid+2], tro[r][4*tid+3]); - tq_wht4(v, tid, true); - tro[r][4*tid]=v.x; tro[r][4*tid+1]=v.y; tro[r][4*tid+2]=v.z; tro[r][4*tid+3]=v.w; + for (int gg = 0; gg < HD / 128; gg++) { + int base = gg * 128 + 4 * tid; + for (int r = 0; r < 2; r++) { + if (tid < 32) { + float4 v = make_float4(tro[r][base], tro[r][base+1], tro[r][base+2], tro[r][base+3]); + tq_wht4(v, tid, true); + tro[r][base]=v.x; tro[r][base+1]=v.y; tro[r][base+2]=v.z; tro[r][base+3]=v.w; + } + __syncthreads(); } - __syncthreads(); } for (int r = 0; r < 2; r++) { int t = q0 + warp * 16 + g + 8 * r; diff --git a/src/cuda/mod.rs b/src/cuda/mod.rs index 39174591..37f17498 100644 --- a/src/cuda/mod.rs +++ b/src/cuda/mod.rs @@ -45,8 +45,9 @@ pub struct Gpu { /// `gemmd_*` scratch for a GEMM that two blocks share the columns of: a slot per stream (see `GEMMD_SLOT`), /// allocated by the first such GEMM. gd: std::sync::OnceLock>, - /// The kernels were compiled for KV cache mode (0 = f16, 1 = q8, 2 = q4). - pub kv_mode: u32, + /// The kernels were compiled for these independent K and V cache modes. + pub kv_k_mode: u32, + pub kv_v_mode: u32, /// The GPU has int8 tensor-core mma (sm_80+). Turing runs the prefill GEMM on the f16 path instead. pub int8_mma: bool, /// sm_75: m16n8k8 mma, 64 KB of shared memory a block (no int8 mma, unlike sm_80+; unlike sm_70 it has no m8n8k4). @@ -92,24 +93,54 @@ unsafe impl Send for Graph {} /// and run attention as its CPU flash attention does (LLAMA_Q8 in kernels.cu). pub fn llama_numerics() -> bool { std::env::var_os("STRATA_LLAMA_NUMERICS").is_some() } -/// KV cache mode: `0 = f16`, `1 = q8`, `2 = q4`, `3 = q2`, `4..9 = TurboQuant (K bits, V bits)`. -/// Modes: 4=4/4, 5=4/3, 6=4/2, 7=3/3, 8=2/2, 9=3/2. -pub fn kv_mode() -> u32 { - if let Ok(v) = std::env::var("STRATA_KV") { - return match v.as_str() { - "q2" => 3, "q4" => 2, "q8" => 1, - "turbo4" | "turboquant" => 4, - "turbo4-3" | "turbo4v3" => 5, - "turbo4-2" | "turbo4v2" => 6, - "turbo3" => 7, - "turbo2" => 8, - "turbo3-2" | "turbo3v2" => 9, - _ => 0, +/// Independent per-side cache modes: `0 = f16`, `1 = q8`, `2 = q4`, `3 = q2`, +/// `4 = turbo4`, `5 = turbo3`, `6 = turbo2`. The K and V halves may differ. +fn parse_kv_mode(s: &str) -> u32 { + match s { + "q2" => 3, "q4" => 2, "q8" => 1, + "turbo4" | "turboquant" => 4, + "turbo3" => 5, + "turbo2" => 6, + _ => 0, + } +} + +pub fn kv_k_mode() -> u32 { + if let Ok(s) = std::env::var("STRATA_KV_K") { return parse_kv_mode(&s); } + if let Ok(s) = std::env::var("STRATA_KV") { + return match s.as_str() { + "turbo4-3" | "turbo4v3" => 4, "turbo4-2" | "turbo4v2" => 4, + "turbo3-2" | "turbo3v2" => 5, + other => parse_kv_mode(other), }; } u32::from(std::env::var_os("STRATA_KV_Q8").is_some()) } +pub fn kv_v_mode() -> u32 { + if let Ok(s) = std::env::var("STRATA_KV_V") { return parse_kv_mode(&s); } + if let Ok(s) = std::env::var("STRATA_KV") { + return match s.as_str() { + "turbo4-3" | "turbo4v3" => 5, "turbo4-2" | "turbo4v2" => 6, + "turbo3-2" | "turbo3v2" => 6, + other => parse_kv_mode(other), + }; + } + u32::from(std::env::var_os("STRATA_KV_Q8").is_some()) +} + +/// Legacy symmetric view: the shared mode when K and V match, 10 for a mixed layout. +/// Callers that only care about "is the cache quantized at all" keep working. +pub fn kv_mode() -> u32 { + let (k, v) = (kv_k_mode(), kv_v_mode()); + if k == v { k } else { 10 } +} + +/// u16 words a cache row of `n` values occupies in mode `m`. +fn kv_mode_words(m: u32, n: usize) -> usize { + match m { 1 => n * 17 / 32, 2 | 4..=6 => n * 9 / 32, 3 => n * 3 / 16, _ => n } +} + /// `--kv q8`: KV cache rows in ggml q8_0 form (`kv_mode() == 1`). pub fn kv_q8() -> bool { kv_mode() == 1 } @@ -182,9 +213,10 @@ pub(crate) fn gemv_block_from(global: Option<&str>, family: Option<&str>) -> u32 .unwrap_or(256) } -fn source(kv_mode: u32, gemm_tc: bool) -> String { source_with(kv_mode, gemm_tc, Tune::from_env()) } +fn source(k_mode: u32, v_mode: u32, gemm_tc: bool) -> String { source_with(k_mode, v_mode, gemm_tc, Tune::from_env()) } -fn source_with(kv_mode: u32, gemm_tc: bool, tune: Tune) -> String { +fn source_with(k_mode: u32, v_mode: u32, gemm_tc: bool, tune: Tune) -> String { + let tq_bits = |m: u32| match m { 5 => 3, 6 => 2, _ => 4 }; let join = |v: Vec| v.join(","); format!( "__device__ const unsigned long long iq2xs_grid[512] = {{{}}};\n\ @@ -196,7 +228,7 @@ fn source_with(kv_mode: u32, gemm_tc: bool, tune: Tune) -> String { __device__ const unsigned char ksigns_iq2xs[128] = {{{}}};\n\ __device__ const signed char kvalues_iq4nl[16] = {{{}}};\n\ __device__ const float tq_lut[4096] = {{{}}};\n\ - #define LLAMA_Q8 {}\n#define KV_MODE {}\n#define TQ_KBITS {}\n#define TQ_VBITS {}\n#define GEMM_TC {}\n\ + #define LLAMA_Q8 {}\n#define KV_MODE {}\n#define K_MODE {}\n#define V_MODE {}\n#define TQ_KBITS {}\n#define TQ_VBITS {}\n#define GEMM_TC {}\n\ #define GEMM_BM {}\n#define GEMM_BK {}\n#define GEMM_MIN_BLOCKS {}\n#define GEMV_LOADW {}\n\ #define FA_BQ {}\n#define FA_BK {}\n{}", join(IQ2XS_GRID.iter().map(|v| format!("{v:#x}ULL")).collect()), @@ -209,9 +241,11 @@ fn source_with(kv_mode: u32, gemm_tc: bool, tune: Tune) -> String { join(KVALUES_IQ4NL.iter().map(|v| v.to_string()).collect()), join(crate::quant::TQ_LUT.iter().flatten().map(|v| format!("{v:e}f")).collect()), llama_numerics() as u8, - kv_mode as u8, - match kv_mode { 5 | 6 => 4, 7 | 9 => 3, 8 => 2, _ => 4 }, - match kv_mode { 5 => 3, 6 | 9 => 2, _ => 4 }, + k_mode as u8, // legacy KV_MODE alias: the K half, for code not yet split + k_mode as u8, + v_mode as u8, + tq_bits(k_mode), + tq_bits(v_mode), gemm_tc as u8, GEMM_BM, tune.gemm_bk, @@ -481,8 +515,8 @@ pub fn device_uuids() -> Vec> { impl Gpu { pub fn new(device: usize) -> anyhow::Result { - let kv_mode = kv_mode(); - anyhow::ensure!(!(kv_mode > 0 && llama_numerics()), "--kv q8/q4 does not combine with --llama-numerics (its attention reads f16 KV)"); + let (kv_k_mode, kv_v_mode) = (kv_k_mode(), kv_v_mode()); + anyhow::ensure!(!((kv_k_mode > 0 || kv_v_mode > 0) && llama_numerics()), "--kv q8/q4 does not combine with --llama-numerics (its attention reads f16 KV)"); if !unsafe { sys::is_culib_present() } { return Err(anyhow::anyhow!(if cfg!(windows) { "no NVIDIA driver (nvcuda.dll)" } else { "no NVIDIA driver (libcuda.so)" })).context("CUDA init"); } @@ -500,7 +534,7 @@ impl Gpu { let gemm_fma = gemm_fma(); crate::say!("{}", device_log(device, &ctx.name().unwrap_or_default(), arch, (maj, min), gemm_fma)); let stream = ctx.new_stream()?; - let module = ctx.load_module(ptx(&source(kv_mode, !gemm_fma && (maj, min) < (7, 5)), arch, (maj, min))?).context("load cubin")?; + let module = ctx.load_module(ptx(&source(kv_k_mode, kv_v_mode, !gemm_fma && (maj, min) < (7, 5)), arch, (maj, min))?).context("load cubin")?; let i8_gemm = int8_gemm_arch((maj, min)); let turing = !int8_mma && (maj, min) >= (7, 5); // The per-block dynamic shared memory ceiling the driver reports: 96 KiB on Volta per the roadmap, but @@ -541,7 +575,7 @@ impl Gpu { let am = stream.alloc_zeros(64 * AMAX_PARTS)?; let ring = std::sync::Mutex::new((unsafe { ctx.alloc_pinned::(RING)? }, 0, VecDeque::new())); let done = ctx.new_event(None)?; - Ok(Gpu { ctx, side: stream.fork()?, stream, nb: AtomicUsize::new(usize::MAX), fns, i8_gemm, q8, gd: Default::default(), kv_mode, int8_mma, turing, max_smem: max_optin, am, graphs: Default::default(), ring, done, lag: Default::default(), fr: Default::default() }) + Ok(Gpu { ctx, side: stream.fork()?, stream, nb: AtomicUsize::new(usize::MAX), fns, i8_gemm, q8, gd: Default::default(), kv_k_mode, kv_v_mode, int8_mma, turing, max_smem: max_optin, am, graphs: Default::default(), ring, done, lag: Default::default(), fr: Default::default() }) } fn f(&self, name: &str) -> &CudaFunction { &self.fns[name] } @@ -769,7 +803,7 @@ impl Gpu { // attn_decode_gqa with the f16 cache at head_dim 128 or 256 also holds 2 chunks of K and V for its cp.async, // attn_decode_gqa4_128 one. Turing (sm_75) has 64 KB of shared memory a block: the head_dim 256 chunks do // not fit, so it loads them through registers instead (kernels.cu ATT_RUN_CP). - let cp = self.kv_mode == 0 && (hd == 128 || (hd == 256 && self.int8_mma)); + let cp = self.kv_k_mode == 0 && self.kv_v_mode == 0 && (hd == 128 || (hd == 256 && self.int8_mma)); let g4 = cp && g == 4 && hd == 128; let (name, cp) = if g4 { ("attn_decode_gqa4_128".to_string(), 2 * 32 * hd * 2) } else { (format!("attn_decode_gqa_{hd}"), if cp { 2 * 2 * 32 * hd * 2 } else { 0 }) }; if gq_min != i32::MAX { launch!(self, &name, cfg(((nh / g * nt) as u32, ns as u32), 256, (8 * hd * 4 + cp) as u32), q, kc, vc, part, step, nh as i32, nkv as i32, hd as i32, scale, gq_min, pz, nt as i32, sel, sst as i32, sink, win as i32, kvt); } @@ -807,7 +841,8 @@ impl Backend for Gpu { i8_gemm: self.i8_gemm, q8, gd: Default::default(), - kv_mode: self.kv_mode, + kv_k_mode: self.kv_k_mode, + kv_v_mode: self.kv_v_mode, int8_mma: self.int8_mma, turing: self.turing, max_smem: self.max_smem, @@ -1305,15 +1340,14 @@ impl Backend for Gpu { Ok(()) } - fn kv_words(&self, n: usize) -> usize { - match self.kv_mode { 0 => n, 1 => n * 17 / 32, 2 | 4..=9 => n * 9 / 32, 3 => n * 3 / 16, _ => unreachable!() } - } + fn kv_words(&self, n: usize) -> usize { kv_mode_words(self.kv_k_mode, n) } + fn kv_words_v(&self, n: usize) -> usize { kv_mode_words(self.kv_v_mode, n) } fn kv_store(&self, k: u64, v: u64, kc: u64, vc: u64, n: usize, t: usize, step: u64, hd: usize) -> anyhow::Result<()> { // q8/q4: each warp quantizes one 32-value block of one row. - anyhow::ensure!(self.kv_mode == 0 || (hd % 32 == 0 && n % hd == 0), "quantized KV cache: head_dim {hd} is not a multiple of 32"); - if self.kv_mode >= 4 { - anyhow::ensure!(hd == 128, "TurboQuant KV needs head_dim 128, got {hd}"); + anyhow::ensure!((self.kv_k_mode == 0 && self.kv_v_mode == 0) || (hd % 32 == 0 && n % hd == 0), "quantized KV cache: head_dim {hd} is not a multiple of 32"); + if self.kv_k_mode >= 4 || self.kv_v_mode >= 4 { + anyhow::ensure!(hd % 128 == 0, "TurboQuant KV needs head_dim divisible by 128, got {hd}"); launch!(self, "kv_store_turbo", cfg(((n * t / 128) as u32, 1), 128, 0), k, v, kc, vc, n as i32, (n * t) as i32, step, hd as i32); } else { @@ -1419,16 +1453,16 @@ mod tests { return; } } - let src = super::source(0, true); + let src = super::source(0, 0, true); super::nvrtc::cubin(&src, "sm_70").unwrap_or_else(|e| panic!("sm_70 must compile: M1-T4 removed the last blocker: {e:#}")); super::nvrtc::cubin(&src, "sm_80").expect("the sm_80 path must keep compiling (cubin for sm_80)"); // Same sm_70 source with the FMA fallback selected: both variants must produce a cubin (M2-T1). - super::nvrtc::cubin(&super::source(0, false), "sm_70").expect("the STRATA_GEMM_FMA sm_70 source must compile"); + super::nvrtc::cubin(&super::source(0, 0, false), "sm_70").expect("the STRATA_GEMM_FMA sm_70 source must compile"); // M2-T3 candidates C2 (`__launch_bounds__(·, 2)`) and C3 (`GEMM_BK = 32`) must compile before the window. - let c23 = super::source_with(0, true, super::Tune { gemm_bk: 32, gemm_min_blocks: 2, ..super::Tune::def() }); + let c23 = super::source_with(0, 0, true, super::Tune { gemm_bk: 32, gemm_min_blocks: 2, ..super::Tune::def() }); super::nvrtc::cubin(&c23, "sm_70").expect("the C2/C3 candidate tiles must compile for sm_70"); // M2-T5 load-width candidate: one 16-byte Q4_K header load in the GEMV path must compile for both arches. - let lw = super::source_with(0, true, super::Tune { gemv_loadw: 1, ..super::Tune::def() }); + let lw = super::source_with(0, 0, true, super::Tune { gemv_loadw: 1, ..super::Tune::def() }); super::nvrtc::cubin(&lw, "sm_70").expect("the GEMV_LOADW candidate must compile for sm_70"); super::nvrtc::cubin(&lw, "sm_80").expect("the GEMV_LOADW candidate must compile for sm_80"); } @@ -1437,11 +1471,11 @@ mod tests { #[test] fn nvrtc_compiles_full_source_for_sm75() { if !super::nvrtc::present() { return; } - super::nvrtc::cubin(&super::source(0, false), "sm_75").unwrap_or_else(|e| panic!("sm_75 must compile: {e:#}")); - super::nvrtc::cubin(&super::source(1, false), "sm_75").unwrap_or_else(|e| panic!("sm_75 kv_q8 must compile: {e:#}")); - super::nvrtc::cubin(&super::source(2, false), "sm_75").unwrap_or_else(|e| panic!("sm_75 kv_q4 must compile: {e:#}")); - super::nvrtc::cubin(&super::source(3, false), "sm_75").unwrap_or_else(|e| panic!("sm_75 kv_q2 must compile: {e:#}")); - super::nvrtc::cubin(&super::source(4, false), "sm_75").unwrap_or_else(|e| panic!("sm_75 kv_turbo4 must compile: {e:#}")); + super::nvrtc::cubin(&super::source(0, 0, false), "sm_75").unwrap_or_else(|e| panic!("sm_75 must compile: {e:#}")); + super::nvrtc::cubin(&super::source(1, 1, false), "sm_75").unwrap_or_else(|e| panic!("sm_75 kv_q8 must compile: {e:#}")); + super::nvrtc::cubin(&super::source(2, 2, false), "sm_75").unwrap_or_else(|e| panic!("sm_75 kv_q4 must compile: {e:#}")); + super::nvrtc::cubin(&super::source(3, 3, false), "sm_75").unwrap_or_else(|e| panic!("sm_75 kv_q2 must compile: {e:#}")); + super::nvrtc::cubin(&super::source(4, 4, false), "sm_75").unwrap_or_else(|e| panic!("sm_75 kv_turbo4 must compile: {e:#}")); } #[test] @@ -1616,17 +1650,17 @@ mod tests { /// kernel; the C2/C3 window candidates only change the injected values. #[test] fn source_injects_tiles() { - let src = super::source_with(0, true, super::Tune::def()); + let src = super::source_with(0, 0, true, super::Tune::def()); for define in [ "#define GEMM_BM 128", "#define GEMM_BK 64", "#define GEMM_MIN_BLOCKS 1", "#define GEMV_LOADW 0", "#define FA_BQ 64", "#define FA_BK 32", ] { assert!(src.contains(define), "source is missing `{define}`"); } - let c23 = super::source_with(0, true, super::Tune { gemm_bk: 32, gemm_min_blocks: 2, ..super::Tune::def() }); + let c23 = super::source_with(0, 0, true, super::Tune { gemm_bk: 32, gemm_min_blocks: 2, ..super::Tune::def() }); assert!(c23.contains("#define GEMM_BK 32")); assert!(c23.contains("#define GEMM_MIN_BLOCKS 2")); - let lw = super::source_with(0, true, super::Tune { gemv_loadw: 1, ..super::Tune::def() }); + let lw = super::source_with(0, 0, true, super::Tune { gemv_loadw: 1, ..super::Tune::def() }); assert!(lw.contains("#define GEMV_LOADW 1")); } diff --git a/src/gpu_model.rs b/src/gpu_model.rs index 846b48ae..e0817358 100644 --- a/src/gpu_model.rs +++ b/src/gpu_model.rs @@ -743,7 +743,7 @@ impl<'a> GpuModel<'a> { qn: lt(il, "attn_q_norm.weight")?, kn: lt(il, "attn_k_norm.weight")?, o: lt(il, "attn_output.weight")?, sink: if c.attn_sinks { Some(lt(il, "attn_sinks.weight")?) } else { None }, kc: (0..ns).map(|_| gpu.zeros::(gpu.kv_words(ctx * kv))).collect::>()?, - vc: (0..ns).map(|_| gpu.zeros::(gpu.kv_words(ctx * kv))).collect::>()?, + vc: (0..ns).map(|_| gpu.zeros::(gpu.kv_words_v(ctx * kv))).collect::>()?, qsa: if qsa_on && il < c.n_layer && m.w.layer(il, "indexer.k_proj.weight").is_ok() { Some(Qsa { kp: lt(il, "indexer.k_proj.weight")?, qp: lt(il, "indexer.q_proj.weight")?, @@ -820,7 +820,7 @@ impl<'a> GpuModel<'a> { Some(DFlashConv { base: df_lt("mlp_conv_base")?, proj: df_lt("mlp_conv_proj")? }) } else { None }, kc: (0..ns).map(|_| gpu.zeros::(gpu.kv_words(ctx * df_kv))).collect::>()?, - vc: (0..ns).map(|_| gpu.zeros::(gpu.kv_words(ctx * df_kv))).collect::>()?, + vc: (0..ns).map(|_| gpu.zeros::(gpu.kv_words_v(ctx * df_kv))).collect::>()?, is_swa: dc.layer_swa.get(il).copied().unwrap_or(false), }); } @@ -905,7 +905,7 @@ impl<'a> GpuModel<'a> { kn: lt(il, "nextn.hnorm.weight")?, o: lt(il, "attn_output.weight")?, kc: (0..ns).map(|_| gpu.zeros::(gpu.kv_words(ctx * eg_kv))).collect::>()?, - vc: (0..ns).map(|_| gpu.zeros::(gpu.kv_words(ctx * eg_kv))).collect::>()?, + vc: (0..ns).map(|_| gpu.zeros::(gpu.kv_words_v(ctx * eg_kv))).collect::>()?, qsa: None, sink: None, }, @@ -1109,7 +1109,7 @@ impl<'a> GpuModel<'a> { let mb = |b: usize| b as f64 / 1048576.0; crate::say!( "plan: weights+state+scratch {:.0} MB (KV {:.0} MB for {ctx} tokens{}, prefill {:.0} MB), expert slots {:.0} MB, resident experts {}/{}", - mb(free0.saturating_sub(free1)), mb(2 * 2 * gpu.kv_words(ctx * kv) * c.layers[range.clone()].iter().filter(|&&k| k == LayerKind::Attn).count()), + mb(free0.saturating_sub(free1)), mb((gpu.kv_words(ctx * kv) + gpu.kv_words_v(ctx * kv)) * 2 * c.layers[range.clone()].iter().filter(|&&k| k == LayerKind::Attn).count()), if ns > 1 { format!(" in each of {ns} slots") } else { String::new() }, mb(pf.as_ref().map_or(0, |p| p.bytes())), mb(cache.as_ref().map_or(0, |x| x.slot_bytes_total())), cache.as_ref().map_or(0, |x| x.resident_count()), cache.as_ref().map_or(0, |x| x.total_experts()), diff --git a/src/inkling2/forward/device.rs b/src/inkling2/forward/device.rs index 8aa879e9..c769ee3c 100644 --- a/src/inkling2/forward/device.rs +++ b/src/inkling2/forward/device.rs @@ -122,7 +122,7 @@ impl PrefillScratch { let p = PrefillLayout::at(buf.addr(), c, rank, max_nt); let acc_buf = be.alloc(4 * max_nt * c.n_embd)?; let kw = c.n_head_kv * c.head_dim; - let rb = 2 * be.kv_words(kw); + let rb = be.kv_row_words(kw); let kv_bytes = max_nt * rb; let (kc_tmp, vc_tmp) = (be.alloc(kv_bytes)?, be.alloc(kv_bytes)?); let max_np = max_nt * c.n_used; @@ -254,8 +254,8 @@ impl Device { [l.wq, l.wk, l.wv, l.wo, l.gate, l.rel, l.sink].iter().chain(l.conv_proj.iter().flatten()).all(dense) }) { return None; } let rows: usize = (0..c.n_slot()).map(|il| if c.swa[layer_of(c, il)] { c.n_swa } else { full }).sum(); - let row_words = d.parts[0].be.kv_words(kw); - room(&mut d, 4 * rows * row_words + sc_bytes(c, full) + Scratch::at(0, c, rank, m.output.rows).end as usize + (512 << 20)); + let kv_bytes = 2 * rows * d.parts[0].be.kv_row_words(kw); + room(&mut d, kv_bytes + sc_bytes(c, full) + Scratch::at(0, c, rank, m.output.rows).end as usize + (512 << 20)); } let made = (|| -> Result { let (mut layers, loops, slots, out_query, out_norm, scr, sc_buf) = { @@ -277,10 +277,10 @@ impl Device { let loops = m.loops.iter().map(|l| { Ok(DLoop { msg_query: up(be, &l.msg_query)?, down: half(&l.down)?, gain: half(&l.gain)?, forget: half(&l.forget)? }) }).collect::>>()?; - let row_words = be.kv_words(kw); + let (kwk, kwv) = (be.kv_words(kw), be.kv_words_v(kw)); let slots = (0..c.n_slot()).map(|il| { let rows = if c.swa[layer_of(c, il)] { c.n_swa } else { full }; - Ok(DSlot { k: be.alloc(2 * rows * row_words)?, v: be.alloc(2 * rows * row_words)?, hist: be.zeros::(hists(c).1)?, cap: rows }) + Ok(DSlot { k: be.alloc(2 * rows * kwk)?, v: be.alloc(2 * rows * kwv)?, hist: be.zeros::(hists(c).1)?, cap: rows }) }).collect::>>()?; let sc_buf = be.alloc(sc_bytes(c, (pos + 1).max(64)))?; let (out_query, out_norm, scr) = (up(be, &m.out_query)?, up(be, &m.out_norm)?, be.alloc(Scratch::at(0, c, rank, m.output.rows).end as usize)?); @@ -354,14 +354,14 @@ impl Device { let be = &*d.parts[0].be; let len = hists(c).1; let kw = c.n_head_kv * c.head_dim; - let swa_words = c.n_swa * be.kv_words(kw); + let (swa_k, swa_v) = (c.n_swa * be.kv_words(kw), c.n_swa * be.kv_words_v(kw)); let mut dev_hist = Vec::with_capacity(self.slots.len()); let mut dev_swa = Vec::with_capacity(self.slots.len()); for (il, ds) in self.slots.iter().enumerate() { dev_hist.push(be.get(&ds.hist, 0, len).expect("inkling2 save_checkpoint hist")); if c.swa[layer_of(c, il)] { - let k: Vec = be.get(&ds.k, 0, swa_words).expect("inkling2 save_checkpoint swa k"); - let v: Vec = be.get(&ds.v, 0, swa_words).expect("inkling2 save_checkpoint swa v"); + let k: Vec = be.get(&ds.k, 0, swa_k).expect("inkling2 save_checkpoint swa k"); + let v: Vec = be.get(&ds.v, 0, swa_v).expect("inkling2 save_checkpoint swa v"); dev_swa.push(Some((k, v))); } else { dev_swa.push(None); @@ -397,13 +397,13 @@ impl Device { let need = need_pos + 1; ensure!(need <= m.max_ctx, "context is limited to {} tokens", m.max_ctx); let mut d = dev::get().unwrap().lock().unwrap(); - let row_words = d.parts[0].be.kv_words(kw); + let row_words = d.parts[0].be.kv_row_words(kw); let full_cap = self.slots.iter().enumerate().find(|&(il, _)| !c.swa[layer_of(c, il)]).map(|(_, s)| s.cap); if let Some(cap) = full_cap && need > cap { let mut new_cap = cap; while new_cap < need { new_cap = (new_cap * 2).min(m.max_ctx); } let n = (0..c.n_slot()).filter(|&il| !c.swa[layer_of(c, il)]).count(); - room(&mut d, 4 * n * new_cap * row_words + sc_bytes(c, new_cap) + (128 << 20)); + room(&mut d, 2 * n * new_cap * row_words + sc_bytes(c, new_cap) + (128 << 20)); } let be = &*d.parts[0].be; let need_sc = sc_bytes(c, need); @@ -977,7 +977,7 @@ impl Device { let d = dev::get().unwrap().lock().unwrap(); let be = &*d.parts[0].be; let pf = self.pf.as_ref().unwrap(); - let rb = 2 * be.kv_words(kw); + let rb = be.kv_row_words(kw); for (il, ds) in self.slots.iter().enumerate() { let ip = layer_of(c, il); if m.layers[ip].swa { @@ -1089,7 +1089,7 @@ impl Device { be.ink_conv_batch(p.k, l.convs[0].addr(), taps[0], hist(0), p.k2, kw, nc, hd, nt)?; be.ink_conv_batch(p.v, l.convs[1].addr(), taps[1], hist(1), p.v2, kw, nc, hd, nt)?; let log_alpha = if ml.swa { 0.0 } else { c.log_alpha }; - let rb = 2 * be.kv_words(kw); + let rb = be.kv_row_words(kw); be.ink_clip_n(p.q, l.q_clip.addr(), hd, nh, nt, c.qk_clip, 0.0, 1.0, 0, 0, 1, pos0, log_alpha, c.log_floor)?; be.ink_clip_n(p.r, l.rel_clip.addr(), nr, nh, nt, c.rel_clip, 0.0, 1.0, 0, 0, 1, pos0, log_alpha, c.log_floor)?; if verify_mode { diff --git a/src/main.rs b/src/main.rs index c75a5617..9438710d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -177,39 +177,44 @@ struct Engine { mmproj: Option, } -fn effective_kv(kv: &str, k: Option<&str>, v: Option<&str>) -> anyhow::Result { +/// Resolve the independent K and V cache types. `--kv` supplies both unless `--k`/`--v` override a half. +fn effective_kv(kv: &str, k: Option<&str>, v: Option<&str>) -> anyhow::Result<(String, String)> { + let valid = |s: &str| matches!(s, "f16" | "q8" | "q4" | "q2" | "turbo4" | "turbo3" | "turbo2"); + let base = match kv { + "turbo4-3" => ("turbo4", "turbo3"), + "turbo4-2" => ("turbo4", "turbo2"), + "turbo3-2" => ("turbo3", "turbo2"), + other => (other, other), + }; let (k, v) = match (k, v) { - (None, None) => return Ok(kv.to_string()), - (Some(k), None) => (k, k), - (None, Some(v)) => (v, v), + (None, None) => base, + (Some(k), None) => (k, base.1), + (None, Some(v)) => (base.0, v), (Some(k), Some(v)) => (k, v), }; - Ok(match (k, v) { - ("turbo4", "turbo4") => "turbo4", - ("turbo4", "turbo3") => "turbo4-3", - ("turbo4", "turbo2") => "turbo4-2", - ("turbo3", "turbo3") => "turbo3", - ("turbo2", "turbo2") => "turbo2", - ("turbo3", "turbo2") => "turbo3-2", - (a, b) if a == b => a, - _ => anyhow::bail!("unsupported --k/--v combination {k}/{v}; use matching types or turbo4/turbo3/turbo2 pairs"), - }.to_string()) -} - -fn set_kv_env(kv: &str) { - match kv { - "q8" | "q4" | "q2" | "turbo4" | "turbo4-3" | "turbo4-2" | "turbo3" | "turbo2" | "turbo3-2" => { - unsafe { std::env::set_var("STRATA_KV", kv) }; - if kv == "q8" { unsafe { std::env::set_var("STRATA_KV_Q8", "1") }; } - else { unsafe { std::env::remove_var("STRATA_KV_Q8") }; } - } - _ => { - unsafe { std::env::remove_var("STRATA_KV") }; - unsafe { std::env::remove_var("STRATA_KV_Q8") }; - } + anyhow::ensure!(valid(k) && valid(v), "unsupported KV combination K={k}, V={v}"); + Ok((k.to_string(), v.to_string())) +} + +/// Publish the resolved types to both backends. `STRATA_KV_K`/`STRATA_KV_V` are independent; `STRATA_KV` is +/// kept as a symmetric-only alias for code paths that have not been split yet (serve/Vulkan). +fn set_kv_env(k: &str, v: &str) { + unsafe { + std::env::set_var("STRATA_KV_K", k); + std::env::set_var("STRATA_KV_V", v); + if k == v { std::env::set_var("STRATA_KV", k); } + else { std::env::remove_var("STRATA_KV"); } + if k == "q8" || v == "q8" { std::env::set_var("STRATA_KV_Q8", "1"); } + else { std::env::remove_var("STRATA_KV_Q8"); } } } +fn set_kv_env_for(kv: &str, k: Option<&str>, v: Option<&str>) -> anyhow::Result<()> { + let (k, v) = effective_kv(kv, k, v)?; + set_kv_env(&k, &v); + Ok(()) +} + /// `serve` options for a server that other people use (docs/HOSTING.md). #[derive(clap::Args, Clone, Debug)] struct Hosting { @@ -378,12 +383,13 @@ impl Runner<'_> { impl Engine { /// Hand `--backend`, `--device`, and `--kv` to the DeepSeek, GLM, Gemma 4 and Inkling 2 paths. - fn ds_env(&self) { + fn ds_env(&self) -> anyhow::Result<()> { // SAFETY: called at the start of a command, before any thread reads these variables. if let Some(b) = &self.backend { unsafe { std::env::set_var("STRATA_DS_BACKEND", b) } } if self.device != [0] { unsafe { std::env::set_var("STRATA_DS_DEVICES", self.device.iter().map(|d| d.to_string()).collect::>().join(",")) } } if self.fixed_experts { unsafe { std::env::set_var("STRATA_FIXED_EXPERTS", "1") } } // Hy4: every expert on the GPU - if self.kv != "f16" && std::env::var_os("STRATA_KV").is_none() { set_kv_env(&self.kv); } + if self.kv != "f16" && std::env::var_os("STRATA_KV_K").is_none() { set_kv_env_for(&self.kv, self.k.as_deref(), self.v.as_deref())?; } + Ok(()) } /// Fills settings not given on the command line from the model's calibration file, else built-in defaults. @@ -418,7 +424,7 @@ impl Engine { } } if self.llama_numerics { unsafe { std::env::set_var("STRATA_LLAMA_NUMERICS", "1") } } // read by Gpu::new - set_kv_env(&self.kv); // read by Gpu::new and Vk::new + set_kv_env_for(&self.kv, self.k.as_deref(), self.v.as_deref())?; // read by Gpu::new and Vk::new let open = || backend::open_all(self.backend.as_deref(), &self.device); let bk = match self.gpu.then(open).transpose() { Err(e) if self.cpu_fallback => { say!("no GPU backend ({e:#}), running on the CPU"); None } @@ -1169,8 +1175,8 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { println!("{}", serde_json::json!({"argmax": argmax, "top5": top5})); } Cmd::Generate { model, prompt, n, image, mut engine } => { - engine.kv = effective_kv(&engine.kv, engine.k.as_deref(), engine.v.as_deref())?; - engine.ds_env(); + let _ = effective_kv(&engine.kv, engine.k.as_deref(), engine.v.as_deref())?; + engine.ds_env()?; let g = Gguf::open(&model)?; engine.own_warn(&g); if g.get("general.architecture").ok().and_then(|v| v.as_str()) == Some("gemma4") { @@ -1293,7 +1299,7 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { r.finish()?; } Cmd::Bench { model, pp, tg, reps, json_out, prompt_file, mut engine } => { - engine.kv = effective_kv(&engine.kv, engine.k.as_deref(), engine.v.as_deref())?; + let _ = effective_kv(&engine.kv, engine.k.as_deref(), engine.v.as_deref())?; if let Some(f) = &prompt_file { let text = std::fs::read_to_string(f).with_context(|| format!("--prompt-file {}", f.display()))?; anyhow::ensure!(!text.trim().is_empty(), "--prompt-file {} is empty", f.display()); @@ -1304,7 +1310,7 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { engine.ctx = engine.ctx.max(pp.iter().max().unwrap_or(&0) + tg); if let Some(arch) = g.get("general.architecture").ok().and_then(|v| v.as_str()) { if arch == "deepseek41" || arch == "glm5-next" || arch == rusting_strata::hy4::ARCH || rusting_strata::inkling2::is_arch(arch) { - engine.ds_env(); + engine.ds_env()?; // A --ctx below the test grows to fit it, as on the main engine. if rusting_strata::CTX.load(std::sync::atomic::Ordering::Relaxed) != 0 { rusting_strata::CTX.store(engine.ctx, std::sync::atomic::Ordering::Relaxed); } return if arch == "deepseek41" { @@ -1374,7 +1380,7 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { } } Cmd::Calibrate { model, ctx, vram_margin, backend, device, split, kv, lora, gpu: _, mtp_model, draft_model } => { - set_kv_env(&kv); // read by Gpu::new and Vk::new + set_kv_env_for(&kv, None, None)?; // read by Gpu::new and Vk::new; expands turbo pair aliases if !lora.is_empty() { say!("note: --lora is ignored by calibrate; calibration uses the base model"); } let margins = vram_margins(&vram_margin, &device)?.into_iter().map(|mb| mb << 20).collect::>(); let split = split_arg(split.as_deref(), device.len())?; @@ -1469,9 +1475,9 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { std::process::exit(cmd.status()?.code().unwrap_or(1)); } Cmd::Chat { model, system, n, image, mut engine } => { - engine.kv = effective_kv(&engine.kv, engine.k.as_deref(), engine.v.as_deref())?; + let _ = effective_kv(&engine.kv, engine.k.as_deref(), engine.v.as_deref())?; let think = engine.think_default; - engine.ds_env(); + engine.ds_env()?; let g = Gguf::open(&model)?; engine.own_warn(&g); if g.get("general.architecture").ok().and_then(|v| v.as_str()) == Some("gemma4") { @@ -1569,8 +1575,8 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { r.finish()?; } Cmd::Serve { model, models_dir, addr, api_key, mcp, open, host, mut engine } => { - engine.kv = effective_kv(&engine.kv, engine.k.as_deref(), engine.v.as_deref())?; - engine.ds_env(); + let _ = effective_kv(&engine.kv, engine.k.as_deref(), engine.v.as_deref())?; + engine.ds_env()?; anyhow::ensure!(host.auto_unload != Some(0), "--auto-unload must be at least 1 second"); engine.parallel = host.parallel; // Before the model is loaded: a slot count outside 1..=255 is an invalid request, not a downgrade. @@ -1802,13 +1808,13 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { // The models outside the main engine read their limit here (`ctx_limit`). if !o["ctx"].is_null() { rusting_strata::CTX.store(engine.ctx, Relaxed); } // `runner` also sets it, and calibrate runs before `runner`. - set_kv_env(&engine.kv); + set_kv_env_for(&engine.kv, engine.k.as_deref(), engine.v.as_deref())?; } // The page's calibrate button: measure with no model loaded, then load with the measured chunk and MTP // (they replace `--chunk`/`--mtp` and the page's earlier values). let cal = if o["calibrate"] == true && engine.gpu { (engine.chunk, engine.mtp) = (None, None); - set_kv_env(&engine.kv); + set_kv_env_for(&engine.kv, engine.k.as_deref(), engine.v.as_deref())?; s.stats.lock().unwrap().unload(Some(s.name(&p))); vram_margins(&engine.vram_margin, &engine.device) .and_then(|mb| calibrate(&p, engine.aux_model_path(), engine.ctx, &mb.into_iter().map(|mb| mb << 20).collect::>(), engine.backend.as_deref(), &engine.device, @@ -1841,7 +1847,7 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { Err(e) => { engine = old; rusting_strata::CTX.store(old_ctx, Relaxed); - set_kv_env(&engine.kv); + set_kv_env_for(&engine.kv, engine.k.as_deref(), engine.v.as_deref())?; s.stats.lock().unwrap().unload(None); say!("loading {}: {e:#}", p.display()); let b = json!({"error": {"message": format!("{e:#}"), "type": "server_error"}}).to_string(); @@ -3722,3 +3728,41 @@ mod bench_tests { assert!(Cli::try_parse_from(["rustingstrata", "bench", "--model", "m.gguf", "--json-out", "/tmp/x.json"]).is_ok()); } } + +#[cfg(test)] +mod kv_type_tests { + use super::effective_kv; + + fn pair(kv: &str, k: Option<&str>, v: Option<&str>) -> (String, String) { + effective_kv(kv, k, v).unwrap() + } + + #[test] + fn symmetric_flag_and_overrides() { + assert_eq!(pair("f16", None, None), ("f16".into(), "f16".into())); + assert_eq!(pair("turbo4", None, None), ("turbo4".into(), "turbo4".into())); + assert_eq!(pair("f16", Some("turbo4"), None), ("turbo4".into(), "f16".into())); + assert_eq!(pair("f16", None, Some("q8")), ("f16".into(), "q8".into())); + } + + #[test] + fn turbo_aliases_expand_to_independent_types() { + assert_eq!(pair("turbo4-3", None, None), ("turbo4".into(), "turbo3".into())); + assert_eq!(pair("turbo4-2", None, None), ("turbo4".into(), "turbo2".into())); + assert_eq!(pair("turbo3-2", None, None), ("turbo3".into(), "turbo2".into())); + } + + #[test] + fn arbitrary_kv_pairs_are_allowed() { + assert_eq!(pair("f16", Some("f16"), Some("q4")), ("f16".into(), "q4".into())); + assert_eq!(pair("f16", Some("q8"), Some("turbo4")), ("q8".into(), "turbo4".into())); + assert_eq!(pair("f16", Some("turbo3"), Some("turbo2")), ("turbo3".into(), "turbo2".into())); + assert_eq!(pair("f16", Some("turbo4"), Some("turbo3")), ("turbo4".into(), "turbo3".into())); + } + + #[test] + fn invalid_types_are_rejected() { + assert!(effective_kv("f16", Some("bogus"), None).is_err()); + assert!(effective_kv("f16", None, Some("turbo9")).is_err()); + } +} From 9cbd332325ac123f669c971c5e2fb49ca38a0c44 Mon Sep 17 00:00:00 2001 From: Sayam Goswami Date: Wed, 25 Nov 2026 00:57:28 +0530 Subject: [PATCH 4/4] TurboQuant: address review (gate order, KV indexing, grow sizing, ds_env) and add regression test --- docs/USAGE.md | 13 ---- src/cuda/kernels.cu | 109 +++++++++++++++++---------- src/inkling2/forward/device.rs | 9 ++- src/main.rs | 6 +- tests/kv_turbo.rs | 134 +++++++++++++++++++++++++++++++++ 5 files changed, 215 insertions(+), 56 deletions(-) create mode 100644 tests/kv_turbo.rs diff --git a/docs/USAGE.md b/docs/USAGE.md index cfd7c065..a26ad5bc 100644 --- a/docs/USAGE.md +++ b/docs/USAGE.md @@ -140,19 +140,6 @@ other MCP clients use, and pass it with `--mcp ` (or `STRATA_MCP`; the def `q4`, `q2`, `turbo4`, `turbo3` or `turbo2`; for example `--k f16 --v q4` or `--k turbo4 --v turbo3`. A mixed layout allocates each half with its own word width. The Vulkan backend only supports symmetric legacy formats. Text can differ from f16 because attention reads rounded keys and values. - - RTX 3050 Laptop, Inkling 2 Mini Q3_K_XL, `bench --pp 128 --tg 32 --reps 3 --gpu --mtp 0 --temp 0 --chunk 128` - (tokens/s, median of three runs; greedy decoding): - - | KV | prefill | decode | KV | prefill | decode | - |---|---:|---:|---|---:|---:| - | f16 | 27.4 | 6.1 | turbo4 | 35.0 | 7.9 | - | q8 | 30.2 | 7.7 | turbo4-3 | 37.4 | 8.4 | - | q4 | 32.8 | 7.1 | turbo3 | 42.9 | 8.6 | - | q2 | 32.6 | 7.9 | turbo2 | 35.6 | 8.2 | - | K=f16 V=q4 | 37.1 | 7.5 | K=q8 V=q4 | 31.6 | 6.3 | - | K=turbo4 V=f16 | 37.3 | 8.0 | K=f16 V=turbo4 | 41.6 | 8.4 | - | K=turbo4 V=q4 | 38.6 | 8.1 | K=q4 V=turbo4 | 40.9 | 8.2 | - `calibrate --mtp-model PATH` or `--draft-model PATH` measures with that draft file loaded, so the chunk and the expert placement see the VRAM it takes, and picks the draft count. Runs with the same `--mtp-model` or `--draft-model` file use that count unless `--mtp` is given; runs with another draft file or none do not. diff --git a/src/cuda/kernels.cu b/src/cuda/kernels.cu index 76562a44..131c9d32 100644 --- a/src/cuda/kernels.cu +++ b/src/cuda/kernels.cu @@ -3140,10 +3140,21 @@ __device__ void ink_attn_prefill_t(const float* q, const float* r, const float* int start = (win > 0 && q_pos + 1 > win) ? (q_pos + 1 - win) : 0; float scale = 1.f / sqrtf((float)HD); float qv[PER], acc[PER]; - // Four consecutive dims per lane, repeated once per 128-wide WHT group (one group at HD=128, two at 256). - auto dim = [&](int j) { return PER >= 4 ? (j >> 2) * 128 + 4 * lane + (j & 3) : 4 * lane + j; }; + // The legacy cache uses main's strided lane + 32*j layout for every head size. Only a TurboQuant half uses the + // contiguous four-dims-per-lane layout its WHT sign diagonals are defined on (one group per 128 dims). + // K and V are indexed independently so a mixed cache keeps the f16 half bit-identical to main. +#if K_MODE >= 4 + auto kidx = [&](int j) { return (j >> 2) * 128 + 4 * lane + (j & 3); }; +#else + auto kidx = [&](int j) { return lane + 32 * j; }; +#endif +#if V_MODE >= 4 + auto vidx = [&](int j) { return (j >> 2) * 128 + 4 * lane + (j & 3); }; +#else + auto vidx = [&](int j) { return lane + 32 * j; }; +#endif for (int j = 0; j < PER; j++) { - qv[j] = q[((size_t)t * nh + h) * HD + dim(j)] * scale; + qv[j] = q[((size_t)t * nh + h) * HD + kidx(j)] * scale; acc[j] = 0.f; } #if K_MODE >= 4 @@ -3164,7 +3175,7 @@ __device__ void ink_attn_prefill_t(const float* q, const float* r, const float* size_t row = use_new ? (size_t)(kp - pos) : (win > 0 ? (size_t)(kp % ring) : (size_t)kp); size_t kbase = row * kw + (size_t)kh * HD; float s = 0.f; - for (int j = 0; j < PER; j++) s += qv[j] * ldkv1(kbuf, kbase + dim(j), HD); + for (int j = 0; j < PER; j++) s += qv[j] * ldkv1(kbuf, kbase + kidx(j), HD); s = warp_sum(s); int dist = q_pos - kp; float b = 0.f; @@ -3179,7 +3190,7 @@ __device__ void ink_attn_prefill_t(const float* q, const float* r, const float* float logit = s + b - sink_val; float mn = fmaxf(m, logit), c = expf(m - mn), e = expf(logit - mn); l = l * c + e; - for (int j = 0; j < PER; j++) acc[j] = e * ldkv1(vbuf, kbase + dim(j), HD) + acc[j] * c; + for (int j = 0; j < PER; j++) acc[j] = e * ldkv1(vbuf, kbase + vidx(j), HD) + acc[j] * c; m = mn; } float inv = 1.f / l; @@ -3194,7 +3205,7 @@ __device__ void ink_attn_prefill_t(const float* q, const float* r, const float* if (PER == 2) { float2 v = {ov[0], ov[1]}; tq_wht2(v, lane, true); ov[0]=v.x; ov[1]=v.y; } #endif for (int j = 0; j < PER; j++) { - int col = dim(j); + int col = vidx(j); size_t idx = ((size_t)t * nh + h) * HD + col; outp[idx] = ov[j] * sigmoid(gate[idx]); } @@ -3517,9 +3528,11 @@ extern "C" __global__ void attn_merge(const float* part, const float* qg, float* for (int s = 0; s < ns; s++) o += pp[s * (hd + 2) + d] * ws[s]; o = o / L; #if V_MODE >= 4 - ro[d] = o; + ro[d] = o; // keep the ungated value: inverse WHT must run before the Q gate #else - out[h * hd + d] = o * (qg ? sigmoid(qg[h * 2 * hd + hd + d]) : 1.0f); + // Match main exactly: apply the Q gate before both the output write and the int8 copy. + o = o * (qg ? sigmoid(qg[h * 2 * hd + hd + d]) : 1.0f); + out[h * hd + d] = o; if (xq) { // hd is a multiple of 32: a warp holds one scale's 32 values float mx = warp_max(fabsf(o)), id = mx > 0.0f ? 127.0f / mx : 0.0f; size_t n = (size_t)gridDim.x * hd, i = blockIdx.z * n + h * hd + d; @@ -3750,11 +3763,12 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co const float* sink, int win) { constexpr int PQ = HD + 8; constexpr int FA_BKL = FA_BK_FOR(HD); - extern __shared__ __align__(16) u16 fa_sm[]; - u16 *qs = fa_sm, *ks = qs + FA_BQ * PQ, *vs = ks + FA_BKL * PQ; #if V_MODE >= 4 - __shared__ float tro[2][HD]; // ungated output of the two query rows, before inverse WHT + // warp x query half x 8 query rows x 128 dims: a unique cell for every (query row, dim, WHT group half). + __shared__ float tro[2][8][128]; // reused by the four warps in turn #endif + extern __shared__ __align__(16) u16 fa_sm[]; + u16 *qs = fa_sm, *ks = qs + FA_BQ * PQ, *vs = ks + FA_BKL * PQ; #if __CUDA_ARCH__ < 800 && GEMM_TC // Volta only: warp-private P tile for the PV A fragments (see the staging in the PV step below). Appended after // `vs` so the qs/ks/vs offsets above do not move; FA_BQ * (FA_BKL + 8) halves = 5120 B. @@ -3783,6 +3797,9 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co int last = pos0 + min(q0 + FA_BQ, T) - 1; // last key any query of the tile sees int qp[2] = {pos0 + q0 + warp * 16 + g, pos0 + q0 + warp * 16 + g + 8}; float o[HD / 8][4] = {}, m[2] = {-INFINITY, -INFINITY}, l[2] = {0.0f, 0.0f}; +#if V_MODE >= 4 + float invr[2] = {1.f, 1.f}; +#endif #if __CUDA_ARCH__ < 800 && GEMM_TC // Same storage as o / extra softmax state for the m8n8k4 layout (PTX ISA 8.5 §9.7.13.4.1). o2[j][grp][i] == // &o[0][0][j * HD / 4 + grp * 8 + i]: the lane owns 4 rows (query half j, p2), so m and l need four entries each; @@ -4160,41 +4177,53 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co float sc = m[r] == -INFINITY ? 0.0f : expf(m[r] - M); float den = l[r] * sc + (sk == -INFINITY ? 0.0f : expf(sk - M)); float inv = den > 0.0f ? sc / den : 0.0f; +#if V_MODE >= 4 + invr[r] = inv; // store after each 128-value group is rotated below +#else #pragma unroll for (int d = 0; d < HD / 8; d++) for (int e = 0; e < 2; e++) { int col = d * 8 + 2 * t4 + e; -#if V_MODE >= 4 - tro[r][col] = o[d][2 * r + e] * inv; -#else orow[col] = o[d][2 * r + e] * inv * (gate ? sigmoid(gate[col]) : 1.0f); -#endif } +#endif } #if V_MODE >= 4 - __syncthreads(); - for (int gg = 0; gg < HD / 128; gg++) { - int base = gg * 128 + 4 * tid; - for (int r = 0; r < 2; r++) { - if (tid < 32) { - float4 v = make_float4(tro[r][base], tro[r][base+1], tro[r][base+2], tro[r][base+3]); - tq_wht4(v, tid, true); - tro[r][base]=v.x; tro[r][base+1]=v.y; tro[r][base+2]=v.z; tro[r][base+3]=v.w; - } - __syncthreads(); - } - } - for (int r = 0; r < 2; r++) { - int t = q0 + warp * 16 + g + 8 * r; - if (t >= T) continue; - float* orow = out + (size_t)t * nh * HD + h * HD; - const float* gate = qg ? qg + (size_t)t * nh * 2 * HD + h * 2 * HD + HD : nullptr; - for (int d = 0; d < HD / 8; d++) - for (int e = 0; e < 2; e++) { - int col = d * 8 + 2 * t4 + e; - orow[col] = tro[r][col] * (gate ? sigmoid(gate[col]) : 1.0f); - } - } + // One warp stages and rotates one query row at a time. tro is indexed by (r, query-row gi, dim), + // never by the dim owner: a thread with g == gi owns all 128 dims of row gi through its four lanes. + for (int wi = 0; wi < 4; wi++) + for (int gi = 0; gi < 8; gi++) + for (int gg = 0; gg < HD / 128; gg++) + for (int r = 0; r < 2; r++) { + if (warp == wi && g == gi) + for (int d = 16 * gg; d < 16 * gg + 16; d++) + for (int e = 0; e < 2; e++) { + int col = d * 8 + 2 * t4 + e; + tro[r][gi][col & 127] = o[d][2 * r + e] * invr[r]; + } + __syncthreads(); + if (warp == wi && lane < 32) { + float4 v = make_float4(tro[r][gi][4*lane], tro[r][gi][4*lane+1], + tro[r][gi][4*lane+2], tro[r][gi][4*lane+3]); + tq_wht4(v, lane, true); + tro[r][gi][4*lane]=v.x; tro[r][gi][4*lane+1]=v.y; + tro[r][gi][4*lane+2]=v.z; tro[r][gi][4*lane+3]=v.w; + } + __syncthreads(); + if (warp == wi && g == gi) { + int t = q0 + warp * 16 + g + 8 * r; + if (t < T) { + float* orow = out + (size_t)t * nh * HD + h * HD; + const float* gate = qg ? qg + (size_t)t * nh * 2 * HD + h * 2 * HD + HD : nullptr; + for (int d = 16 * gg; d < 16 * gg + 16; d++) + for (int e = 0; e < 2; e++) { + int col = d * 8 + 2 * t4 + e; + orow[col] = tro[r][gi][col & 127] * (gate ? sigmoid(gate[col]) : 1.0f); + } + } + } + __syncthreads(); + } #endif #endif } @@ -4205,6 +4234,10 @@ __device__ void attn_prefill_llama(const float* q, const u16* kc, const u16* vc, const int* step, int T, int nh, int nkv, float scale, const unsigned* qm, int mw, const float* sink, int win) { constexpr int R = (HD + 127) / 128; +#if V_MODE >= 4 + // warp x query half x 8 query rows x 128 dims: a unique cell for every (query row, dim, WHT group half). + __shared__ float tro[2][8][128]; // reused by the four warps in turn +#endif extern __shared__ __align__(16) u16 fa_sm[]; float *sq = (float*)fa_sm, *sc = sq + HD; int h = blockIdx.y, kvh = h / (nh / nkv), tid = threadIdx.x, w = tid >> 5, lane = tid & 31; diff --git a/src/inkling2/forward/device.rs b/src/inkling2/forward/device.rs index c769ee3c..4a3c30dd 100644 --- a/src/inkling2/forward/device.rs +++ b/src/inkling2/forward/device.rs @@ -397,13 +397,13 @@ impl Device { let need = need_pos + 1; ensure!(need <= m.max_ctx, "context is limited to {} tokens", m.max_ctx); let mut d = dev::get().unwrap().lock().unwrap(); - let row_words = d.parts[0].be.kv_row_words(kw); + let (kwk, kwv) = (d.parts[0].be.kv_words(kw), d.parts[0].be.kv_words_v(kw)); let full_cap = self.slots.iter().enumerate().find(|&(il, _)| !c.swa[layer_of(c, il)]).map(|(_, s)| s.cap); if let Some(cap) = full_cap && need > cap { let mut new_cap = cap; while new_cap < need { new_cap = (new_cap * 2).min(m.max_ctx); } let n = (0..c.n_slot()).filter(|&il| !c.swa[layer_of(c, il)]).count(); - room(&mut d, 2 * n * new_cap * row_words + sc_bytes(c, new_cap) + (128 << 20)); + room(&mut d, 2 * n * new_cap * (kwk + kwv) + sc_bytes(c, new_cap) + (128 << 20)); } let be = &*d.parts[0].be; let need_sc = sc_bytes(c, need); @@ -415,8 +415,9 @@ impl Device { if c.swa[layer_of(c, il)] || need <= s.cap { continue; } let mut new_cap = s.cap; while new_cap < need { new_cap = (new_cap * 2).min(m.max_ctx); } - for b in [&mut s.k, &mut s.v] { - let new = be.alloc(2 * new_cap * row_words)?; + // K and V are separate buffers with their own word width; sizing both with their sum doubles f16. + for (b, words) in [(&mut s.k, kwk), (&mut s.v, kwv)] { + let new = be.alloc(2 * new_cap * words)?; be.dtod(b, 0, &new, 0, b.len())?; be.sync()?; // the copy reads the buffer that `*b = new` frees *b = new; diff --git a/src/main.rs b/src/main.rs index 9438710d..3b7e52d7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -388,7 +388,11 @@ impl Engine { if let Some(b) = &self.backend { unsafe { std::env::set_var("STRATA_DS_BACKEND", b) } } if self.device != [0] { unsafe { std::env::set_var("STRATA_DS_DEVICES", self.device.iter().map(|d| d.to_string()).collect::>().join(",")) } } if self.fixed_experts { unsafe { std::env::set_var("STRATA_FIXED_EXPERTS", "1") } } // Hy4: every expert on the GPU - if self.kv != "f16" && std::env::var_os("STRATA_KV_K").is_none() { set_kv_env_for(&self.kv, self.k.as_deref(), self.v.as_deref())?; } + // `--k`/`--v` must take effect even when `--kv` is left at its f16 default; otherwise an Inkling 2 + // mixed layout silently degrades to plain f16. + if (self.kv != "f16" || self.k.is_some() || self.v.is_some()) && std::env::var_os("STRATA_KV_K").is_none() { + set_kv_env_for(&self.kv, self.k.as_deref(), self.v.as_deref())?; + } Ok(()) } diff --git a/tests/kv_turbo.rs b/tests/kv_turbo.rs new file mode 100644 index 00000000..ba612e27 --- /dev/null +++ b/tests/kv_turbo.rs @@ -0,0 +1,134 @@ +//! TurboQuant KV on CUDA. Its own process: the kernel module is compiled per KV format. +//! +//! The first test pins the legacy symmetric modes to the exact cache bytes, prefill and decode +//! produced by main at bbd57c2 (FNV-1a over little-endian u16/f32). Every legacy path touched by +//! this PR must stay bit-identical; the TurboQuant and mixed K/V paths are separate opt-in modes. +mod common; +use common::{down, up}; +use rusting_strata::backend::Backend; +use rusting_strata::cuda::{ATT_GQA_MIN, ATT_SPLITS, Gpu}; + +fn xs(n: usize) -> Vec { + (0..n).map(|i| ((i as f32 * 0.7548777).fract() - 0.5) * 2.0).collect() +} +fn rel_l2(a: &[f32], b: &[f32]) -> f32 { + let num: f32 = a.iter().zip(b).map(|(x, y)| (x - y) * (x - y)).sum(); + let den: f32 = b.iter().map(|y| y * y).sum(); + (num / den.max(1e-30)).sqrt() +} +fn hash32(v: &[f32]) -> u64 { + let mut h = 0xcbf29ce484222325u64; + for x in v { for b in x.to_bits().to_le_bytes() { h ^= b as u64; h = h.wrapping_mul(0x100000001b3); } } + h +} +fn hash16(v: &[u16]) -> u64 { + let mut h = 0xcbf29ce484222325u64; + for x in v { for b in x.to_le_bytes() { h ^= b as u64; h = h.wrapping_mul(0x100000001b3); } } + h +} +fn set_kv(k: &str, v: &str) { + unsafe { + std::env::set_var("STRATA_KV_K", k); + std::env::set_var("STRATA_KV_V", v); + std::env::set_var("STRATA_KV", if k == v { k } else { "q4" }); + if k == "q8" || v == "q8" { std::env::set_var("STRATA_KV_Q8", "1"); } + else { std::env::remove_var("STRATA_KV_Q8"); } + } +} + +/// Cache bytes, prefill output and decode output of f16/q8/q4/q2 for four (nh, nkv, hd) shapes. +/// Each line is `mode nh nkv hd k_hash v_hash prefill_hash decode_hash` from main @ bbd57c2. +const MAIN_REFERENCE: &str = " +f16 4 2 64 78caa2a80cfa10a7 3bcfc21757d78a23 a57ee46c4c639bd3 d4f04a7b0c6df80e +f16 4 2 128 dfe2171c148e789d 72fae506d01ba632 033f81eeb95d8145 86d7f667d304a145 +f16 16 2 256 68d7d4e7121fbe38 b3e45897fef7ff50 7911ff6714a6dab2 a6f0fb3a2221aeb1 +f16 8 8 128 67e29b12aaed3c94 b9f0dc213da4b775 93f3d16615408ac7 10be884b38eb6e74 +q8 4 2 64 07c54db5ed94d112 c0a2ed71a66247cc bae90aa5312fc525 49849c15dfae5f13 +q8 4 2 128 80fdcbf78047e4ec df3442477362b960 2e97b83efe2ffa6f f43403b2a477cb12 +q8 16 2 256 ff33d70bf833ee97 edb6be75ad286544 03bf49248f78af9c d2eb1f691c815c94 +q8 8 8 128 15a5ccf186cb82d9 5c11745ba63b4da5 55d3c2630b1a09ed 7e04804514989de6 +q4 4 2 64 447ab262ea711901 febb164977c324d8 25e651f5f048a76d 2d4375e1dc829176 +q4 4 2 128 a6b6fcf0e15d57a8 ba27be594dc54f3e 5978942beda784e1 6d2c4003a55f8a07 +q4 16 2 256 3dbc191cad296f5f 600b6004f27b4e30 c3f89deea836e994 bf88f3f3afdd6624 +q4 8 8 128 9571d3e72332fff4 ee12b4710fa007d3 81309dc3d750f1f6 df16ce6d0771100a +q2 4 2 64 bd0f840e53ce64de c8e5ccef19e480df 417fe5dd5658e90d c2c8598377d823c2 +q2 4 2 128 03eb270888f1d205 bcd33f0e028c0824 867f0f6b1e0e8ab6 3ce515d6cf41f37a +q2 16 2 256 36a62ff1eb5ea0bb 2035cf12e1db2f42 e6f84b45cd7effa1 7520251b958cdb93 +q2 8 8 128 f1030ecd713b642f 6e9a5fca2f6bd630 88fed7b50798c9ee 8be7f5e03672026e +"; + +fn open(k: &str, v: &str) -> Option { + set_kv(k, v); + match Gpu::new(0) { + Ok(g) => Some(g), + Err(e) if format!("{e}") == "CUDA init" => { eprintln!("SKIP: no CUDA device: {e:#}"); None } + Err(e) => panic!("{e:#}"), + } +} + +/// One deterministic workload shared by the bit-identity and the TurboQuant checks. +fn run(g: &Gpu, nh: usize, nkv: usize, hd: usize, t: usize, pos0: usize) -> (Vec, Vec, Vec, Vec) { + let n = (pos0 + t) * nkv * hd; + let k = xs(n); + let v = xs(n + 5)[5..].iter().map(|x| 3.0 * x).collect::>(); + let q: Vec = xs(t * nh * hd + 3)[3..].iter().map(|x| 4.0 * x).collect(); + let qg = xs(t * nh * 2 * hd); + let scale = 1.0 / (hd as f32).sqrt(); + let g: &dyn Backend = g; + let (kc_n, vc_n) = (g.kv_words(n), g.kv_words_v(n)); + let (dk, dv) = (up(g, &k), up(g, &v)); + let (kc, vc) = (g.zeros::(kc_n).unwrap(), g.zeros::(vc_n).unwrap()); + let zero = up(g, &[0i32]); + g.kv_store(dk.addr(), dv.addr(), kc.addr(), vc.addr(), nkv * hd, pos0 + t, zero.addr(), hd).unwrap(); + let (dq, dg) = (up(g, &q), up(g, &qg)); + let step = up(g, &[pos0 as i32]); + let dout = g.zeros::(t * nh * hd).unwrap(); + g.attn_prefill(dq.addr(), kc.addr(), vc.addr(), dg.addr(), dout.addr(), step.addr(), t, nh, nkv, hd, scale).unwrap(); + let steps: Vec = (0..t).flat_map(|i| [(pos0 + i) as i32, 0]).collect(); + let ds = up(g, &steps); + let (dd, part) = (g.zeros::(t * nh * hd).unwrap(), g.zeros::(t * nh * ATT_SPLITS * (hd + 2)).unwrap()); + g.attn_decode_gq(dq.addr(), kc.addr(), vc.addr(), dg.addr(), dd.addr(), part.addr(), ds.addr(), + nh, nkv, hd, scale, ATT_GQA_MIN, t, 0, 0).unwrap(); + (down::(g, &kc), down::(g, &vc), down::(g, &dout), down::(g, &dd)) +} + +#[test] +fn turboquant_kv_modes() { + let _gpu = common::gpu_lock(); + let shapes = [(4, 2, 64), (4, 2, 128), (16, 2, 256), (8, 8, 128)]; + let (t, pos0) = (32, 5); + // 1. Legacy modes: byte-for-byte the same as main. A change to any shared prefill/decode/store path fails here. + for kv in ["f16", "q8", "q4", "q2"] { + let Some(g) = open(kv, kv) else { continue }; + let rows: Vec<_> = MAIN_REFERENCE.lines().filter(|l| l.starts_with(kv)).collect(); + for (line, (nh, nkv, hd)) in rows.iter().zip(shapes) { + let f: Vec<_> = line.split_whitespace().collect(); + assert_eq!((f[1].parse::().unwrap(), f[2].parse::().unwrap(), f[3].parse::().unwrap()), (nh, nkv, hd)); + let (kc, vc, pf, dec) = run(&g, nh, nkv, hd, t, pos0); + let got = [hash16(&kc), hash16(&vc), hash32(&pf), hash32(&dec)]; + for (j, want) in f[4..].iter().enumerate() { + assert_eq!(format!("{:016x}", got[j]), *want, "{kv} nh {nh} nkv {nkv} hd {hd} field {j} differs from main"); + } + } + } + // 2. Turbo4 occupies the same cache as q4 and stays within its own rounding error of f16. + let Some(g16) = open("f16", "f16") else { return }; + let Some(gq4) = open("q4", "q4") else { return }; + let Some(gt4) = open("turbo4", "turbo4") else { return }; + for &(nh, nkv, hd) in shapes.iter().filter(|&&(_, _, hd)| hd % 128 == 0) { + let n = (pos0 + t) * nkv * hd; + assert_eq!(gt4.kv_words(n), gq4.kv_words(n), "turbo4 and q4 must use the same cache size"); + let (_, _, pf16, dec16) = run(&g16, nh, nkv, hd, t, pos0); + let (_, _, _, dec4) = run(&gq4, nh, nkv, hd, t, pos0); + let (_, _, pft, dect) = run(>4, nh, nkv, hd, t, pos0); + eprintln!("nh {nh} nkv {nkv} hd {hd}: turbo4 vs f16 decode {:.2e}, prefill {:.2e}, prefill-vs-decode {:.2e}; f16 pf-vs-dec {:.2e}; q4 vs f16 decode {:.2e}", + rel_l2(&dect, &dec16), rel_l2(&pft, &pf16), rel_l2(&pft, &dect), rel_l2(&pf16, &dec16), rel_l2(&dec4, &dec16)); + assert!(rel_l2(&pft, &dect) < 5e-4, "turbo4 prefill vs decode nh {nh} nkv {nkv} hd {hd}"); + assert!(rel_l2(&dect, &dec16) < 0.9, "turbo4 decode nh {nh} nkv {nkv} hd {hd}"); + assert!(rel_l2(&pft, &dec16) < 0.9, "turbo4 prefill vs decode nh {nh} nkv {nkv} hd {hd}"); + } + // 3. Mixed halves are sized independently: only the K half changes when --k changes. + let Some(gmix) = open("turbo4", "f16") else { return }; + let n = 4096; + assert_eq!((gmix.kv_words(n), gmix.kv_words_v(n)), (gt4.kv_words(n), g16.kv_words(n))); +}