Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion docs/USAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,9 @@ other MCP clients use, and pass it with `--mcp <file>` (or `STRATA_MCP`; the def
- `--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.
`--kv turbo3` uses 3-bit packing: a 2-bit code plane plus a sign plane and one corrected norm per 128 values,
or 50 B per 128 values instead of the 4-bit modes' 66 B. `--kv turbo4-3`, `turbo4-2`, `turbo2` and `turbo3-2`
select narrower centroids with the 4-bit nibble packing.
- `--k TYPE` and `--v TYPE` set the two cache formats independently (CUDA). Either half may be `f16`, `q8`,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Correctness · 4 of 6

Doc says 4-bit modes use 66 B per 128 values; the code gives 72 B The 4-bit stride is hd/2 + hd/16 = 72 bytes for hd=128, and the test expects 36 u16 words (n*9/32). The doc's 66 B figure understates the 4-bit footprint, so users sizing memory from the doc will under-allocate and the stated 50-vs-66 comparison is wrong.

Prompt for your AI agent
File: docs/USAGE.md
Line: 151
Issue: Doc says 4-bit modes use 66 B per 128 values; the code gives 72 B The 4-bit stride is hd/2 + hd/16 = 72 bytes for hd=128, and the test expects 36 u16 words (n*9/32). The doc's 66 B figure understates the 4-bit footprint, so users sizing memory from the doc will under-allocate and the stated 50-vs-66 comparison is wrong.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

`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
Expand Down
79 changes: 61 additions & 18 deletions src/cuda/kernels.cu
Original file line number Diff line number Diff line change
Expand Up @@ -2963,18 +2963,43 @@ __device__ __forceinline__ float tq_group_sum(float cs, int g) {
return warp_sum(t);
}
template<int BITS> __device__ __forceinline__ void kv_put_tq(u16* c, size_t e, int hd, float x, float norm, bool active) {
int q = tq_nearest<BITS>(x / norm);
unsigned nib = (unsigned)q;
unsigned pair = nib | (__shfl_xor_sync(0xffffffff, nib, 1) << 4);
// 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.
int gw = hd >= 128 ? 128 : hd;
float qnorm = norm * sqrtf(128.0f / (float)gw);
int q = tq_nearest<BITS>(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<BITS>(q) * tq_centroid<BITS>(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<BITS>(q) * tq_centroid<BITS>(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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Correctness · 1 of 6

3-bit head stride reserves hd/64 norm bytes but writes 2 per group, so hd=64 norms overlap the next head For hd=64 the per-head stride is 364/8 + 64/64 = 25 bytes, but the fp16 norm is written at r+24 (2 bytes, to offset 25) and every head has one group. Each head's norm overwrites the first code byte of the following head, and the odd stride misaligns the u16 store. Inkling-2 (hd=64) turbo3 KV then decodes corrupted values. The stride should reserve 2max(1, hd/128) norm bytes, e.g. 3hd/8 + 2max(1,hd/128).

Prompt for your AI agent
File: src/cuda/kernels.cu
Line: 2868
Issue: 3-bit head stride reserves hd/64 norm bytes but writes 2 per group, so hd=64 norms overlap the next head For hd=64 the per-head stride is 3*64/8 + 64/64 = 25 bytes, but the fp16 norm is written at r+24 (2 bytes, to offset 25) and every head has one group. Each head's norm overwrites the first code byte of the following head, and the odd stride misaligns the u16 store. Inkling-2 (hd=64) turbo3 KV then decodes corrupted values. The stride should reserve 2*max(1, hd/128) norm bytes, e.g. 3*hd/8 + 2*max(1,hd/128).
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

unsigned char* r = (unsigned char*)c + e / hd * (3 * hd / 8 + hd / 64);
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) {
Expand Down Expand Up @@ -3203,12 +3228,23 @@ template <int M, int PER, int BITS = TQ_KBITS> __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<BITS>(q0) * norm) | ((unsigned)f2h(tq_centroid<BITS>(q1) * norm) << 16);
if constexpr (BITS == 3) {
const unsigned char* r = (const unsigned char*)c + off / hd * (3 * hd / 8 + hd / 64);
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<BITS>(q0) * norm) | ((unsigned)f2h(tq_centroid<BITS>(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<BITS>(q0) * norm) | ((unsigned)f2h(tq_centroid<BITS>(q1) * norm) << 16);
}
}
} else if constexpr (M == 3) {
int w = off % hd;
Expand Down Expand Up @@ -3304,11 +3340,18 @@ __device__ __forceinline__ float rh(float x) { return h2f(f2h(x)); }
template <int M, int BITS = TQ_KBITS> __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<BITS>(q) * norm);
if constexpr (BITS == 3) {
const unsigned char* r = (const unsigned char*)c + off / hd * (3 * hd / 8 + hd / 64);
float norm = h2f(*(const u16*)(r + 3 * hd / 8 + 2 * (we >> 7)));
int q = ((r[we / 4] >> (2 * (we & 3))) & 3) | (((r[hd / 4 + we / 8] >> (we & 7)) & 1) << 2);
return rh(tq_centroid<BITS>(q) * norm);
} 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)));
unsigned b = r[we / 2];
int q = (we & 1) == 0 ? (int)(b & 15u) : (int)(b >> 4);
return rh(tq_centroid<BITS>(q) * norm);
}
} else if constexpr (M == 3) {
int w = off % hd;
const unsigned char* r = (const unsigned char*)c + off / hd * (3 * hd / 8);
Expand Down
2 changes: 1 addition & 1 deletion src/cuda/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ pub fn kv_mode() -> u32 {

/// 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 }
match m { 1 => n * 17 / 32, 2 | 4 | 6 => n * 9 / 32, 5 => n * 25 / 128, 3 => n * 3 / 16, _ => n }
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Correctness · 5 of 6

Mode 5 changes from nibble packing (9/32) to 3-bit packing (25/128) without visible mapping Previously modes 4..=6 all used n*9/32 words (4-bit nibble layout). This diff makes mode 5 use 25/128, but the diff never shows that mode 5 is turbo3. If mode 5 is one of turbo4-3, turbo4-2, turbo2 or turbo3-2 (which the docs say stay on 4-bit nibble packing), those modes allocate too little and read/write out of bounds. The same change appears in src/vulkan/mod.rs.

Prompt for your AI agent
File: src/cuda/mod.rs
Line: 188
Symbol: kv_mode_words
Issue: Mode 5 changes from nibble packing (9/32) to 3-bit packing (25/128) without visible mapping Previously modes 4..=6 all used n*9/32 words (4-bit nibble layout). This diff makes mode 5 use 25/128, but the diff never shows that mode 5 is turbo3. If mode 5 is one of turbo4-3, turbo4-2, turbo2 or turbo3-2 (which the docs say stay on 4-bit nibble packing), those modes allocate too little and read/write out of bounds. The same change appears in src/vulkan/mod.rs.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.


/// `--kv q8`: KV cache rows in ggml q8_0 form (`kv_mode() == 1`).
Expand Down
59 changes: 59 additions & 0 deletions src/kv_turbo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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::<f32>().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::<f32>() / 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::<f32>();
let cos = dot / restored.iter().map(|x| x * x).sum::<f32>().sqrt();
assert!(cos > 0.97, "round-trip cosine {cos} too low");
}
}
}
4 changes: 2 additions & 2 deletions src/vulkan/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1303,10 +1303,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<()> {
Expand Down
48 changes: 42 additions & 6 deletions src/vulkan/shaders/tq.glsl
Original file line number Diff line number Diff line change
Expand Up @@ -111,25 +111,61 @@ 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);
// Centroids are calibrated for a 128-value WHT group. A 64-value group has twice the variance, so scale
// the norm by sqrt(128 / group) on store and keep the corrected norm in the same scaled units.
uint gw = hd >= 128u ? 128u : hd;
float 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 + hd / 64u);
uint m4 = mag | (subgroupShuffleXor(mag, 1u) << 2) | (subgroupShuffleXor(mag, 2u) << 4) | (subgroupShuffleXor(mag, 3u) << 6);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Correctness · 3 of 6

return; in a float-returning GLSL function does not compile tq_group_reduce is declared to return float, but the new bits==3 branch uses a bare return;. GLSL rejects this, so the Vulkan shader fails to build and every turbo3 path fails. The branch should return a value, such as the reduced recon, or restructure so the function ends in one return.

Prompt for your AI agent
File: src/vulkan/shaders/tq.glsl
Line: 122
Issue: `return;` in a float-returning GLSL function does not compile tq_group_reduce is declared to return float, but the new bits==3 branch uses a bare `return;`. GLSL rejects this, so the Vulkan shader fails to build and every turbo3 path fails. The branch should return a value, such as the reduced recon, or restructure so the function ends in one return.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

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;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Correctness · 2 of 6

Vulkan 3-bit stride and norm read share the hd=64 bug, with an odd base offset tq_ldkv and tq_group_reduce use r = off/hd*(3hd/8 + hd/64). For hd=64 that is 25 bytes per head, so r is odd for every head after the first. The norm index (r + 3hd/8)/2 truncates to the wrong u16 and reads the previous head's code bytes as the scale. The Vulkan turbo3 hd=64 path (the new vulkan_inkling_turbo3_hd64 test) decodes wrong values, and the CUDA and Vulkan layouts must match for shared caches.

Prompt for your AI agent
File: src/vulkan/shaders/tq.glsl
Line: 131
Issue: Vulkan 3-bit stride and norm read share the hd=64 bug, with an odd base offset tq_ldkv and tq_group_reduce use r = off/hd*(3*hd/8 + hd/64). For hd=64 that is 25 bytes per head, so r is odd for every head after the first. The norm index (r + 3*hd/8)/2 truncates to the wrong u16 and reads the previous head's code bytes as the scale. The Vulkan turbo3 hd=64 path (the new vulkan_inkling_turbo3_hd64 test) decodes wrong values, and the CUDA and Vulkan layouts must match for shared caches.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

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 + hd / 64u);
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) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Low · Performance · 6 of 6

tq_ldkv2 for 3-bit recomputes the lo half through tq_ldkv, reloading the norm and codes The 3-bit branch of tq_ldkv2 calls tq_ldkv(c, off, ...) for the low half, which repeats the norm load and both code-byte loads already done for the high half. Each dual-element read therefore does redundant memory traffic, which matters in the attention inner loop. The lo element should be computed from the same loaded norm and code bytes as the hi element.

Prompt for your AI agent
File: src/vulkan/shaders/tq.glsl
Line: 153
Issue: tq_ldkv2 for 3-bit recomputes the lo half through tq_ldkv, reloading the norm and codes The 3-bit branch of tq_ldkv2 calls tq_ldkv(c, off, ...) for the low half, which repeats the norm load and both code-byte loads already done for the high half. Each dual-element read therefore does redundant memory traffic, which matters in the attention inner loop. The lo element should be computed from the same loaded norm and code bytes as the hi element.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

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 + hd / 64u);
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);
Expand Down
Binary file modified src/vulkan/spv/attn_decode.spv
Binary file not shown.
Binary file modified src/vulkan/spv/attn_prefill_128.spv
Binary file not shown.
Binary file modified src/vulkan/spv/attn_prefill_256.spv
Binary file not shown.
Binary file modified src/vulkan/spv/attn_prefill_64.spv
Binary file not shown.
Binary file modified src/vulkan/spv/attn_prefill_dp.spv
Binary file not shown.
Binary file modified src/vulkan/spv/attn_prefill_tile.spv
Binary file not shown.
Binary file modified src/vulkan/spv/attn_sel.spv
Binary file not shown.
Binary file modified src/vulkan/spv/ink_attn.spv
Binary file not shown.
Binary file modified src/vulkan/spv/ink_attn_prefill.spv
Binary file not shown.
Binary file modified src/vulkan/spv/ink_clip.spv
Binary file not shown.
Binary file modified src/vulkan/spv/kv_store.spv
Binary file not shown.
Binary file modified src/vulkan/spv/rms_norm.spv
Binary file not shown.
23 changes: 22 additions & 1 deletion tests/kv_turbo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,5 +177,26 @@ fn turboquant_ink_clip_hd64() {
let (pft, dect) = ink_run(&gt, 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");
}
22 changes: 16 additions & 6 deletions tests/vulkan_split_kv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -166,6 +164,18 @@ fn vulkan_inkling_turbo_hd64() {
want.extend_from_slice(&down::<f32>(g, &dout));
}
let got = down::<f32>(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");
}
Loading