diff --git a/docs/USAGE.md b/docs/USAGE.md index 48c2e807..0384a65c 100644 --- a/docs/USAGE.md +++ b/docs/USAGE.md @@ -165,7 +165,9 @@ settings: ctx 32768, kv q8, chunk 2048 (calibration), mtp 1 (preset), short 32 ( - `q8` halves the KV cache (345 instead of 650 MB at 32K). 32K decode is about 6% slower, 32K prefill 14%. - `q4` and `q2` take about 28% and 19% of the f16 size, for very long contexts. q2 differs most from f16. -- `turbo4` (TurboQuant, CUDA only) takes about 28% of the f16 size. The other turbo types are narrower. +- `turbo4` (TurboQuant, CUDA only) takes about 28% of the f16 size (72 B per 128 values). `turbo3` packs in 3 bits, + 50 B per 128 values; the other turbo types are narrower. A composite name (`turbo4-3`, `turbo3-2`) pairs a K and a V + half, and a `turbo3` half is 3-bit like `turbo3`, not 4-bit. - Every type but `f16` rounds keys and values, so the output can differ. - The head size must be a multiple of 32. `--llama-numerics` needs the f16 cache. - Vulkan takes `f16`, `q8`, `q4` and `q2`, the same type for K and V. diff --git a/src/cuda/kernels.cu b/src/cuda/kernels.cu index 70a07c2c..3ef51698 100644 --- a/src/cuda/kernels.cu +++ b/src/cuda/kernels.cu @@ -4306,18 +4306,47 @@ __device__ __forceinline__ float tq_group_sum(float cs, int g) { return warp_sum(t); } template __device__ __forceinline__ void kv_put_tq(u16* c, size_t e, int hd, float x, float norm, bool active) { - int q = tq_nearest(x / norm); - unsigned nib = (unsigned)q; - unsigned pair = nib | (__shfl_xor_sync(0xffffffff, nib, 1) << 4); + float qnorm = norm; + if constexpr (BITS == 3) { + // The 3-bit centroids are calibrated for N(0, 1/128), the coordinates of a unit-L2 128-value WHT group. A + // 64-value group has twice that variance, so scale the norm by sqrt(128 / group) before quantizing and store + // the corrected norm in the same scaled units. Dequant then needs no width-dependent correction. Other bit + // widths keep the unscaled norm, so turbo4/turbo2 store exactly the values they did before this scaling. + int gw = hd >= 128 ? 128 : hd; + qnorm = norm * sqrtf(128.0f / (float)gw); + } + int q = tq_nearest(x / qnorm); 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 (active && (we & 1) == 0) r[we / 2] = (unsigned char)pair; + float recon = sqrtf(tq_group_sum(active ? tq_centroid(q) * tq_centroid(q) : 0.f, g)); // The reference stores norm / ||reconstructed centroids||; without it dequant is systematically low. // Inactive lanes of a short head width still join the reduction but contribute no centroid energy. - float recon = sqrtf(tq_group_sum(active ? tq_centroid(q) * tq_centroid(q) : 0.f, g)); - if (active && w == 0) *(u16*)(r + hd / 2 + 2 * g) = f2h(norm / fmaxf(recon, 1e-6f)); + if constexpr (BITS == 3) { + // True 3-bit layout: a 2-bit code plane (4 values per byte) and a 1-bit sign plane (8 per byte), + // followed by one fp16 corrected norm per 128 values. 50 B per group instead of 66. + unsigned mag = (unsigned)(q & 3), sign = (unsigned)(q >> 2); + unsigned char* r = (unsigned char*)c + e / hd * (3 * hd / 8 + 2 * ((hd + 127) / 128)); + unsigned m4 = mag | (__shfl_xor_sync(0xffffffffu, mag, 1) << 2) + | (__shfl_xor_sync(0xffffffffu, mag, 2) << 4) + | (__shfl_xor_sync(0xffffffffu, mag, 3) << 6); + unsigned s8 = sign | (__shfl_xor_sync(0xffffffffu, sign, 1) << 1) + | (__shfl_xor_sync(0xffffffffu, sign, 2) << 2) + | (__shfl_xor_sync(0xffffffffu, sign, 3) << 3) + | (__shfl_xor_sync(0xffffffffu, sign, 4) << 4) + | (__shfl_xor_sync(0xffffffffu, sign, 5) << 5) + | (__shfl_xor_sync(0xffffffffu, sign, 6) << 6) + | (__shfl_xor_sync(0xffffffffu, sign, 7) << 7); + if (active && (we & 3) == 0) r[we / 4] = (unsigned char)m4; + if (active && (we & 7) == 0) r[hd / 4 + we / 8] = (unsigned char)s8; + if (active && w == 0) *(u16*)(r + 3 * hd / 8 + 2 * g) = f2h(norm / fmaxf(recon, 1e-6f)); + } else { + unsigned nib = (unsigned)q; + unsigned pair = nib | (__shfl_xor_sync(0xffffffffu, nib, 1) << 4); + unsigned char* r = (unsigned char*)c + e / hd * (hd / 2 + hd / 16); + if (active && (we & 1) == 0) r[we / 2] = (unsigned char)pair; + if (active && w == 0) *(u16*)(r + hd / 2 + 2 * g) = f2h(norm / fmaxf(recon, 1e-6f)); + } } #endif __device__ __forceinline__ float warp_min(float v) { @@ -4546,12 +4575,23 @@ template __device__ __forceinline__ void l 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); + if constexpr (BITS == 3) { + const unsigned char* r = (const unsigned char*)c + off / hd * (3 * hd / 8 + 2 * ((hd + 127) / 128)); + float norm = h2f(*(const u16*)(r + 3 * hd / 8 + 2 * (we >> 7))); + for (int i = 0; i < PER / 2; i++) { + int a = we + 2 * i, b = a + 1; + int q0 = ((r[a / 4] >> (2 * (a & 3))) & 3) | (((r[hd / 4 + a / 8] >> (a & 7)) & 1) << 2); + int q1 = ((r[b / 4] >> (2 * (b & 3))) & 3) | (((r[hd / 4 + b / 8] >> (b & 7)) & 1) << 2); + o[i] = (unsigned)f2h(tq_centroid(q0) * norm) | ((unsigned)f2h(tq_centroid(q1) * norm) << 16); + } + } else { + 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; @@ -4646,11 +4686,18 @@ __device__ __forceinline__ float rh(float x) { return h2f(f2h(x)); } // Scalar KV element load matching GLSL ldkv(): value w (0 <= w < hd) of cache row `row`, hd values a row. template __device__ __forceinline__ float ldkv1_at(const u16* c, size_t row, unsigned w, int hd) { if constexpr (M >= 4) { - const unsigned char* r = (const unsigned char*)c + row * (hd / 2 + hd / 16); - float norm = h2f(*(const u16*)(r + hd / 2 + 2 * (w >> 7))); - unsigned b = r[w / 2]; - int q = (w & 1) == 0 ? (int)(b & 15u) : (int)(b >> 4); - return rh(tq_centroid(q) * norm); + if constexpr (BITS == 3) { + const unsigned char* r = (const unsigned char*)c + row * (3 * hd / 8 + 2 * ((hd + 127) / 128)); + float norm = h2f(*(const u16*)(r + 3 * hd / 8 + 2 * (w >> 7))); + int q = ((r[w / 4] >> (2 * (w & 3))) & 3) | (((r[hd / 4 + w / 8] >> (w & 7)) & 1) << 2); + return rh(tq_centroid(q) * norm); + } else { + const unsigned char* r = (const unsigned char*)c + row * (hd / 2 + hd / 16); + float norm = h2f(*(const u16*)(r + hd / 2 + 2 * (w >> 7))); + unsigned b = r[w / 2]; + int q = (w & 1) == 0 ? (int)(b & 15u) : (int)(b >> 4); + return rh(tq_centroid(q) * norm); + } } else if constexpr (M == 3) { const unsigned char* r = (const unsigned char*)c + row * (3 * hd / 8); unsigned b = r[w / 4]; diff --git a/src/cuda/mod.rs b/src/cuda/mod.rs index 15fd67df..e947a5bb 100644 --- a/src/cuda/mod.rs +++ b/src/cuda/mod.rs @@ -271,7 +271,7 @@ pub(crate) fn tq_bits(m: u32) -> u32 { match m { 5 => 3, 6 => 2, _ => 4 } } /// u16 words a cache row of `n` values occupies in mode `m`. pub(crate) 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 } + match m { 1 => n * 17 / 32, 2 | 4 | 6 => n * 9 / 32, 5 => n * 25 / 128, 3 => n * 3 / 16, _ => n } } /// `--kv q8`: KV cache rows in ggml q8_0 form (`kv_mode() == 1`). diff --git a/src/kv_turbo.rs b/src/kv_turbo.rs index a3e45bc1..819d2841 100644 --- a/src/kv_turbo.rs +++ b/src/kv_turbo.rs @@ -119,6 +119,32 @@ pub fn dequantize4(codes: &[u8; D / 2], norm: f32) -> [f32; D] { out } +/// Pack 128 rotated, unit-L2 coordinates into 32 bytes of 2-bit codes plus 16 bytes of sign bits and the +/// reconstruction-corrected norm. Mirrors TheTom's `block_turbo3_0` layout: 50 B per 128 values. +pub fn quantize3(x: &[f32; D], l2: f32) -> ([u8; D / 4], [u8; D / 8], f32) { + let mut qs = [0u8; D / 4]; + let mut signs = [0u8; D / 8]; + let mut recon2 = 0f32; + for i in 0..D { + let q = nearest(x[i] / l2, 3); + qs[i / 4] |= ((q & 3) as u8) << (2 * (i % 4)); + if q >= 4 { signs[i / 8] |= 1 << (i % 8); } + recon2 += CENTROIDS3[q] * CENTROIDS3[q]; + } + (qs, signs, l2 / recon2.sqrt().max(1e-6)) +} + +/// Unpack 3-bit codes into 128 rotated values, scaled by the stored corrected norm. +pub fn dequantize3(qs: &[u8; D / 4], signs: &[u8; D / 8], norm: f32) -> [f32; D] { + let mut out = [0f32; D]; + for i in 0..D { + let mag = (qs[i / 4] >> (2 * (i % 4))) & 3; + let sign = (signs[i / 8] >> (i % 8)) & 1; + out[i] = CENTROIDS3[(mag | (sign << 2)) as usize] * norm; + } + out +} + /// Deterministic Gaussian PRNG and QJL projection matrix, matching the reference (LCG + Box-Muller, seed 1042). struct Prng(u64); impl Prng { @@ -245,4 +271,37 @@ mod tests { let mean = err / (trials as f64); assert!(mean < 5.0, "mean absolute QJL error {mean} too high"); } + + #[test] + fn turbo3_packs_50_bytes_per_128_and_round_trips() { + let mut state = 0x9e37_79b9_7f4a_7c15u64; + 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 (qs, signs, norm) = quantize3(&rotated, 1.0); + assert_eq!(qs.len() + signs.len() + 2, 50, "turbo3 block must be 50 B"); + // The first eight values exercise both sign halves and all four magnitude code positions. + for i in 0..8 { + let mag = (qs[i / 4] >> (2 * (i % 4))) & 3; + let sign = (signs[0] >> i) & 1; + assert_eq!((mag | (sign << 2)) as usize, nearest(rotated[i], 3)); + } + let back_rot = dequantize3(&qs, &signs, norm); + let mean_err = rotated.iter().zip(&back_rot).map(|(a, b)| (a - b).abs()).sum::() / D as f32; + assert!(mean_err < 0.09, "3-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 cos = dot / restored.iter().map(|x| x * x).sum::().sqrt(); + assert!(cos > 0.97, "round-trip cosine {cos} too low"); + } + } } diff --git a/src/vulkan/mod.rs b/src/vulkan/mod.rs index ad99615b..319cf930 100644 --- a/src/vulkan/mod.rs +++ b/src/vulkan/mod.rs @@ -1348,10 +1348,10 @@ impl Backend for Vk { } fn preflight(&self, types: &[GgmlType], verbose: bool) -> anyhow::Result<()> { Vk::preflight(self, types, verbose) } fn kv_words(&self, n: usize) -> usize { - match self.0.kv_k_mode { 0 => n, 1 => n * 17 / 32, 2 | 4..=6 => n * 9 / 32, 3 => n * 3 / 16, _ => unreachable!() } + match self.0.kv_k_mode { 0 => n, 1 => n * 17 / 32, 2 | 4 | 6 => n * 9 / 32, 5 => n * 25 / 128, 3 => n * 3 / 16, _ => unreachable!() } } fn kv_words_v(&self, n: usize) -> usize { - match self.0.kv_v_mode { 0 => n, 1 => n * 17 / 32, 2 | 4..=6 => n * 9 / 32, 3 => n * 3 / 16, _ => unreachable!() } + match self.0.kv_v_mode { 0 => n, 1 => n * 17 / 32, 2 | 4 | 6 => n * 9 / 32, 5 => n * 25 / 128, 3 => n * 3 / 16, _ => unreachable!() } } fn gemm(&self, ty: GgmlType, rows: usize, cols: usize, tiles: u64, n_tiles: usize, x: u64, x_stride: usize, n_x: usize, xrow: u64, y: u64, y_stride: usize, act: i32) -> anyhow::Result<()> { diff --git a/src/vulkan/shaders/tq.glsl b/src/vulkan/shaders/tq.glsl index ae8ab110..b6dd3807 100644 --- a/src/vulkan/shaders/tq.glsl +++ b/src/vulkan/shaders/tq.glsl @@ -111,25 +111,65 @@ float tq_group_reduce(float cs, uint slot) { } // Store one rotated, quantized value. Active lanes join the reduction; inactive ones contribute no energy and write nothing. void tq_put(U16 c, uint e, uint hd, float x, float norm, bool valid, uint bits, uint slot) { - int q = tq_nearest(bits, fdiv(x, norm)); - uint nib = uint(q), pair = nib | (subgroupShuffleXor(nib, 1u) << 4); + float qnorm = norm; + if (bits == 3u) { + // The 3-bit centroids are calibrated for a unit-L2 128-value WHT group; a 64-value group has twice that + // variance, so scale the norm by sqrt(128 / group) on store and keep the corrected norm in the same scaled + // units. Other bit widths keep the unscaled norm, so turbo4/turbo2 store the values they did before. + uint gw = hd >= 128u ? 128u : hd; + qnorm = norm * sqrt_(fdiv(128.0, float(gw))); + } + int q = tq_nearest(bits, fdiv(x, qnorm)); uint we = e % hd, g = we >> 7u, w = we & 127u; - uint r = e / hd * (hd / 2u + hd / 16u); - if (valid && (we & 1u) == 0u) U8(uint64_t(c)).v[r + we / 2u] = uint8_t(pair); float cen = tq_centroid(bits, q); float recon = sqrt_(tq_group_reduce(valid ? cen * cen : 0.0, slot)); + if (bits == 3u) { + // 2-bit code plane plus 1-bit sign plane, then one corrected fp16 norm per 128 values: 50 B per group. + uint mag = uint(q & 3), sign = uint(q >> 2); + uint r = e / hd * (3u * hd / 8u + 2u * ((hd + 127u) / 128u)); + uint m4 = mag | (subgroupShuffleXor(mag, 1u) << 2) | (subgroupShuffleXor(mag, 2u) << 4) | (subgroupShuffleXor(mag, 3u) << 6); + uint s8 = sign | (subgroupShuffleXor(sign, 1u) << 1) | (subgroupShuffleXor(sign, 2u) << 2) + | (subgroupShuffleXor(sign, 3u) << 3) | (subgroupShuffleXor(sign, 4u) << 4) + | (subgroupShuffleXor(sign, 5u) << 5) | (subgroupShuffleXor(sign, 6u) << 6) + | (subgroupShuffleXor(sign, 7u) << 7); + if (valid && (we & 3u) == 0u) U8(uint64_t(c)).v[r + we / 4u] = uint8_t(m4); + if (valid && (we & 7u) == 0u) U8(uint64_t(c)).v[r + hd / 4u + we / 8u] = uint8_t(s8); + if (valid && w == 0u) c.v[(r + 3u * hd / 8u) / 2u + g] = uint16_t(f2h(fdiv(norm, max(recon, 1e-6)))); + return; + } + uint nib = uint(q), pair = nib | (subgroupShuffleXor(nib, 1u) << 4); + uint r = e / hd * (hd / 2u + hd / 16u); + if (valid && (we & 1u) == 0u) U8(uint64_t(c)).v[r + we / 2u] = uint8_t(pair); if (valid && w == 0u) c.v[(r + hd / 2u) / 2u + g] = uint16_t(f2h(fdiv(norm, max(recon, 1e-6)))); } float tq_ldkv(U16 c, uint off, uint hd, uint bits) { - uint we = off % hd, r = off / hd * (hd / 2u + hd / 16u); + uint we = off % hd; + if (bits == 3u) { + uint r = off / hd * (3u * hd / 8u + 2u * ((hd + 127u) / 128u)); + float norm = float(uint16BitsToHalf(c.v[(r + 3u * hd / 8u) / 2u + (we >> 7u)])); + uint m = (uint(U8(uint64_t(c)).v[r + we / 4u]) >> (2u * (we & 3u))) & 3u; + uint s = (uint(U8(uint64_t(c)).v[r + hd / 4u + we / 8u]) >> (we & 7u)) & 1u; + return rh(tq_centroid(3u, int(m | (s << 2u))) * norm); + } + uint r = off / hd * (hd / 2u + hd / 16u); float norm = float(uint16BitsToHalf(c.v[(r + hd / 2u) / 2u + (we >> 7u)])); uint b = uint(U8(uint64_t(c)).v[r + we / 2u]); int q = int((we & 1u) == 0u ? b & 15u : b >> 4); return rh(tq_centroid(bits, q) * norm); } uint tq_ldkv2(U16 c, uint off, uint hd, uint bits) { - uint a0 = off % hd, r = off / hd * (hd / 2u + hd / 16u); + uint a0 = off % hd; + if (bits == 3u) { + uint r = off / hd * (3u * hd / 8u + 2u * ((hd + 127u) / 128u)); + uint lo = f2h(tq_ldkv(c, off, hd, bits)); + uint a1 = (off + 1u) % hd; + float n1 = float(uint16BitsToHalf(c.v[(r + 3u * hd / 8u) / 2u + (a1 >> 7u)])); + uint m1 = (uint(U8(uint64_t(c)).v[r + a1 / 4u]) >> (2u * (a1 & 3u))) & 3u; + uint s1 = (uint(U8(uint64_t(c)).v[r + hd / 4u + a1 / 8u]) >> (a1 & 7u)) & 1u; + return lo | (f2h(tq_centroid(3u, int(m1 | (s1 << 2u))) * n1) << 16); + } + uint r = off / hd * (hd / 2u + hd / 16u); float n0 = float(uint16BitsToHalf(c.v[(r + hd / 2u) / 2u + (a0 >> 7u)])); uint b = uint(U8(uint64_t(c)).v[r + a0 / 2u]); uint lo = f2h(tq_centroid(bits, int(b & 15u)) * n0); diff --git a/src/vulkan/spv/attn_decode.spv b/src/vulkan/spv/attn_decode.spv index f79047ef..e9e77f6b 100644 Binary files a/src/vulkan/spv/attn_decode.spv and b/src/vulkan/spv/attn_decode.spv differ diff --git a/src/vulkan/spv/attn_prefill_128.spv b/src/vulkan/spv/attn_prefill_128.spv index 98cf20e5..ca158057 100644 Binary files a/src/vulkan/spv/attn_prefill_128.spv and b/src/vulkan/spv/attn_prefill_128.spv differ diff --git a/src/vulkan/spv/attn_prefill_256.spv b/src/vulkan/spv/attn_prefill_256.spv index cef34255..4842f7a1 100644 Binary files a/src/vulkan/spv/attn_prefill_256.spv and b/src/vulkan/spv/attn_prefill_256.spv differ diff --git a/src/vulkan/spv/attn_prefill_64.spv b/src/vulkan/spv/attn_prefill_64.spv index 3c9b86ab..0907e2b3 100644 Binary files a/src/vulkan/spv/attn_prefill_64.spv and b/src/vulkan/spv/attn_prefill_64.spv differ diff --git a/src/vulkan/spv/attn_prefill_dp.spv b/src/vulkan/spv/attn_prefill_dp.spv index 51eee38e..7a2d23de 100644 Binary files a/src/vulkan/spv/attn_prefill_dp.spv and b/src/vulkan/spv/attn_prefill_dp.spv differ diff --git a/src/vulkan/spv/attn_prefill_tile.spv b/src/vulkan/spv/attn_prefill_tile.spv index d5bf8bdc..07424970 100644 Binary files a/src/vulkan/spv/attn_prefill_tile.spv and b/src/vulkan/spv/attn_prefill_tile.spv differ diff --git a/src/vulkan/spv/attn_sel.spv b/src/vulkan/spv/attn_sel.spv index ce57e2fa..0ee26964 100644 Binary files a/src/vulkan/spv/attn_sel.spv and b/src/vulkan/spv/attn_sel.spv differ diff --git a/src/vulkan/spv/ink_attn.spv b/src/vulkan/spv/ink_attn.spv index 35a2face..9c10fc74 100644 Binary files a/src/vulkan/spv/ink_attn.spv and b/src/vulkan/spv/ink_attn.spv differ diff --git a/src/vulkan/spv/ink_attn_prefill.spv b/src/vulkan/spv/ink_attn_prefill.spv index 43e55a99..8d20dd65 100644 Binary files a/src/vulkan/spv/ink_attn_prefill.spv and b/src/vulkan/spv/ink_attn_prefill.spv differ diff --git a/src/vulkan/spv/ink_clip.spv b/src/vulkan/spv/ink_clip.spv index 854c8c86..ff0f6c67 100644 Binary files a/src/vulkan/spv/ink_clip.spv and b/src/vulkan/spv/ink_clip.spv differ diff --git a/src/vulkan/spv/kv_store.spv b/src/vulkan/spv/kv_store.spv index daf0de50..231e598b 100644 Binary files a/src/vulkan/spv/kv_store.spv and b/src/vulkan/spv/kv_store.spv differ diff --git a/src/vulkan/spv/rms_norm.spv b/src/vulkan/spv/rms_norm.spv index 1836ab51..bad5c6c5 100644 Binary files a/src/vulkan/spv/rms_norm.spv and b/src/vulkan/spv/rms_norm.spv differ diff --git a/tests/inkling2_q8_attention.rs b/tests/inkling2_q8_attention.rs index 821da6b7..dd6420a2 100644 --- a/tests/inkling2_q8_attention.rs +++ b/tests/inkling2_q8_attention.rs @@ -35,7 +35,8 @@ fn cpu_cache(words: &[u16], mode: &str, rows: usize, hd: usize) -> Vec { let stride = match mode { "f16" => 2 * hd, "q8" => hd + hd / 16, - "q4" | "turbo4" | "turbo3" | "turbo2" => hd / 2 + hd / 16, + "q4" | "turbo4" | "turbo2" => hd / 2 + hd / 16, + "turbo3" => 3 * hd / 8 + 2 * ((hd + 127) / 128), "q2" => 3 * hd / 8, _ => panic!("unknown cache format"), }; @@ -54,9 +55,17 @@ fn cpu_cache(words: &[u16], mode: &str, rows: usize, hd: usize) -> Vec { q.mul_add(half(base + hd / 4 + 2 * (col / 32)), half(base + hd / 4 + hd / 16 + 2 * (col / 32))) } + "turbo3" => { + // 3-bit packing: 2-bit code plane at we/4, 1-bit sign plane at hd/4 + we/8, one fp16 norm + // per 128-value group at 3*hd/8. Matches kv_turbo::dequantize3 byte-for-byte. + let mag = (b[base + col / 4] >> (2 * (col % 4))) & 3; + let sign = (b[base + hd / 4 + col / 8] >> (col % 8)) & 1; + let c = rusting_strata::kv_turbo::bits_centroids(3)[(mag | (sign << 2)) as usize]; + c * half(base + 3 * hd / 8 + 2 * (col / 128)) + } _ => { let q = ((b[base + col / 2] >> (4 * (col % 2))) & 15) as usize; - let bits = match mode { "turbo4" => 4, "turbo3" => 3, _ => 2 }; + let bits = match mode { "turbo4" => 4, _ => 2 }; let c = rusting_strata::kv_turbo::bits_centroids(bits)[q]; c * half(base + hd / 2) } diff --git a/tests/kv_turbo.rs b/tests/kv_turbo.rs index 02ffdf20..f54857ca 100644 --- a/tests/kv_turbo.rs +++ b/tests/kv_turbo.rs @@ -215,5 +215,26 @@ fn turboquant_ink_clip_hd64() { let (pft, dect) = ink_run(>, hd, nh, nkv, nt, pos0, ring); eprintln!("turbo hd 64: prefill vs decode {:.2e}, vs f16 {:.2e}", rel_l2(&pft, &dect), rel_l2(&pft, &pf16)); assert!(rel_l2(&pft, &dect) < 5e-4, "turbo hd 64 prefill vs decode"); - assert!(rel_l2(&pft, &pf16) < 0.9, "turbo hd 64 vs f16"); + assert!(rel_l2(&pft, &pf16) < 0.2, "turbo hd 64 vs f16"); +} + +/// TurboQuant 3-bit uses a 2-bit code plane plus a sign plane: 25 u16 words per 128 values, against 36 for the +/// 4-bit modes. Prefill and decode still have to agree, and the result stays close to f16. +#[test] +fn turbo3_uses_3_bit_packing() { + let _gpu = common::gpu_lock(); + let Some(g3) = open("turbo3", "turbo3") else { return }; + let Some(g4) = open("turbo4", "turbo4") else { return }; + let Some(g16) = open("f16", "f16") else { return }; + let (nh, nkv, hd, t, pos0) = (4usize, 2usize, 128usize, 32usize, 5usize); + let n = (pos0 + t) * nkv * hd; + assert_eq!(g3.kv_words(n), n * 25 / 128); + assert_eq!(g4.kv_words(n), n * 9 / 32); + assert_eq!(g3.kv_words(n) * 36, g4.kv_words(n) * 25, "3-bit must use 25/36 of the 4-bit words"); + let (_, _, pf3, dec3) = run(&g3, nh, nkv, hd, t, pos0); + let (_, _, _, dec16) = run(&g16, nh, nkv, hd, t, pos0); + let e = rel_l2(&pf3, &dec3); + eprintln!("turbo3 prefill vs decode {e:.2e}, vs f16 {:.2e}", rel_l2(&dec3, &dec16)); + assert!(e < 5e-4, "turbo3 prefill vs decode {e}"); + assert!(rel_l2(&dec3, &dec16) < 1.0, "turbo3 decode drifted from f16"); } diff --git a/tests/vulkan_split_kv.rs b/tests/vulkan_split_kv.rs index 173eadf7..87ac684f 100644 --- a/tests/vulkan_split_kv.rs +++ b/tests/vulkan_split_kv.rs @@ -132,10 +132,8 @@ fn vulkan_split_legacy_and_turbo() { } /// Inkling 2 uses head_dim 64, where TurboQuant needs WHT-64 on both store and attention. -#[test] -fn vulkan_inkling_turbo_hd64() { - let _lock = common::gpu_lock(); - set("turbo4", "turbo4"); +fn ink_turbo_hd64_check(mode: &str) { + set(mode, mode); let Some(vk) = open_vk() else { return }; let (nh, nkv, hd, nt, pos0, ring) = (4usize, 2usize, 64usize, 6usize, 3usize, 16usize); let (nr, ext) = (16usize, 8usize); @@ -166,8 +164,20 @@ fn vulkan_inkling_turbo_hd64() { want.extend_from_slice(&down::(g, &dout)); } let got = down::(g, &dout_pre); - eprintln!("vulkan turbo hd64 prefill vs decode {:.2e}", rel_l2(&got, &want)); - assert!(rel_l2(&got, &want) < 5e-4, "vulkan turbo hd64 prefill vs decode"); + eprintln!("vulkan {mode} hd64 prefill vs decode {:.2e}", rel_l2(&got, &want)); + assert!(rel_l2(&got, &want) < 5e-4, "vulkan {mode} hd64 prefill vs decode"); +} + +#[test] +fn vulkan_inkling_turbo_hd64() { + let _lock = common::gpu_lock(); + ink_turbo_hd64_check("turbo4"); +} + +#[test] +fn vulkan_inkling_turbo3_hd64() { + let _lock = common::gpu_lock(); + ink_turbo_hd64_check("turbo3"); } /// Without cooperative matrices (STRATA_VK_NO_COOP) prefill takes attn_prefill_tile, which must rotate the query