Skip to content
Open
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 @@ -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.
Expand Down
83 changes: 65 additions & 18 deletions src/cuda/kernels.cu
Original file line number Diff line number Diff line change
Expand Up @@ -4306,18 +4306,47 @@ __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);
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<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)

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

gw=hd for hd<128 gives hd/64=0 or 1 norm bytes, insufficient for one fp16 norm For hd=32, hd/64=0 so norm store at 3*hd/8 writes entirely past the row; for hd=64 it reserves 1 B for a 2 B norm. The formula only equals 2 B per 128 values when hd>=128, so any head_dim <128 corrupts the cache even before misalignment is considered.

Prompt for your AI agent
File: src/cuda/kernels.cu
Line: 4317
Issue: gw=hd for hd<128 gives hd/64=0 or 1 norm bytes, insufficient for one fp16 norm For hd=32, hd/64=0 so norm store at 3*hd/8 writes entirely past the row; for hd=64 it reserves 1 B for a 2 B norm. The formula only equals 2 B per 128 values when hd>=128, so any head_dim <128 corrupts the cache even before misalignment is considered.
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 * (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);
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));

@aletheore aletheore Bot Dec 5, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 4861885e5088.


🟠 High · Correctness · 1 of 6

3-bit stride is 25 B/row for hd=64, norm overflows and u16 store is misaligned For hd=64, 3*hd/8+hd/64=25 bytes/row but code+sign need 24 B plus a 2 B norm =26 B. The norm store at r+24 writes 1 B past the row into the next row's code plane, the next row starts at odd offset 25 making (u16) misaligned (UB/crash on CUDA), and rows overwrite each other's codes/norms.

Prompt for your AI agent
File: src/cuda/kernels.cu
Line: 4338
Issue: 3-bit stride is 25 B/row for hd=64, norm overflows and u16 store is misaligned For hd=64, 3*hd/8+hd/64=25 bytes/row but code+sign need 24 B plus a 2 B norm =26 B. The norm store at r+24 writes 1 B past the row into the next row's code plane, the next row starts at odd offset 25 making *(u16*) misaligned (UB/crash on CUDA), and rows overwrite each other's codes/norms.
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.

} 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) {

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 5

Stored turbo3 norm uses unscaled norm, not qnorm, so hd<128 dequant is off by sqrt(128/hd) For hd=64, qnorm=normsqrt(2) is used to pick centroids, but the fp16 stored value is f2h(norm/recon) instead of f2h(qnorm/recon). Dequant multiplies centroidstored_norm with no width correction, so reconstructed K/V are systematically low by sqrt(2) (by 2x for hd=32), corrupting attention for Inkling-2 hd64 heads despite the comment saying the corrected norm is stored in scaled units.

Prompt for your AI agent
File: src/cuda/kernels.cu
Line: 4352
Issue: Stored turbo3 norm uses unscaled norm, not qnorm, so hd<128 dequant is off by sqrt(128/hd) For hd=64, qnorm=norm*sqrt(2) is used to pick centroids, but the fp16 stored value is f2h(norm/recon) instead of f2h(qnorm/recon). Dequant multiplies centroid*stored_norm with no width correction, so reconstructed K/V are systematically low by sqrt(2) (by 2x for hd=32), corrupting attention for Inkling-2 hd64 heads despite the comment saying the corrected norm is stored in scaled units.
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.

Expand Down Expand Up @@ -4546,12 +4575,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 + 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<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 @@ -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 <int M, int BITS = TQ_KBITS> __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<BITS>(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<BITS>(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<BITS>(q) * norm);
}
} else if constexpr (M == 3) {
const unsigned char* r = (const unsigned char*)c + row * (3 * hd / 8);
unsigned b = r[w / 4];
Expand Down
2 changes: 1 addition & 1 deletion src/cuda/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
}

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

kv_mode_words n25/128 under-allocates for hd=64 (and any n not multiple of 128) For hd=64 each row needs 26 B=13 u16 words, but n25/128 gives 12.5 words/row (truncated, 24-25 B/row total). The buffer is short by ~1 B/row, so the last row's norm write is out of bounds and earlier rows' norms overlap following code planes. Same formula in src/vulkan/mod.rs kv_words/kv_words_v.

Prompt for your AI agent
File: src/cuda/mod.rs
Line: 276
Issue: kv_mode_words n*25/128 under-allocates for hd=64 (and any n not multiple of 128) For hd=64 each row needs 26 B=13 u16 words, but n*25/128 gives 12.5 words/row (truncated, 24-25 B/row total). The buffer is short by ~1 B/row, so the last row's norm write is out of bounds and earlier rows' norms overlap following code planes. Same formula in src/vulkan/mod.rs kv_words/kv_words_v.
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.

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 5

kv_mode_words for mode 5 has same hd64 under-allocation as Vulkan kv_words With hd=64 (Inkling 2), n=rows64 gives n25/128 words, but the 3-bit layout needs 13 words per row (16B code + 8B sign + 2B norm). Allocation is 0.5 word/row short, so CUDA KV writes overflow the buffer / corrupt following rows, same as Vulkan path.

Prompt for your AI agent
File: src/cuda/mod.rs
Line: 276
Issue: kv_mode_words for mode 5 has same hd64 under-allocation as Vulkan kv_words With hd=64 (Inkling 2), n=rows*64 gives n*25/128 words, but the 3-bit layout needs 13 words per row (16B code + 8B sign + 2B norm). Allocation is 0.5 word/row short, so CUDA KV writes overflow the buffer / corrupt following rows, same as Vulkan path.
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];

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

CPU quantize3/dequantize3 has no hd64 sqrt(128/group) scaling, mismatching Vulkan tq_put quantize3 quantizes x/l2 with no group scaling and stores l2/recon, while Vulkan quantizes x/(norm*sqrt(128/gw)). For hd64 the CPU reference and GPU produce different codes/norms for same input, so CPU round-trip test (D=128 only) passes but CPU-vs-GPU hd64 comparisons and any CPU fallback decode of GPU-written KV are wrong by sqrt(2).

Prompt for your AI agent
File: src/kv_turbo.rs
Line: 126
Symbol: quantize3
Issue: CPU quantize3/dequantize3 has no hd64 sqrt(128/group) scaling, mismatching Vulkan tq_put quantize3 quantizes x/l2 with no group scaling and stores l2/recon, while Vulkan quantizes x/(norm*sqrt(128/gw)). For hd64 the CPU reference and GPU produce different codes/norms for same input, so CPU round-trip test (D=128 only) passes but CPU-vs-GPU hd64 comparisons and any CPU fallback decode of GPU-written KV are wrong by sqrt(2).
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.

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

@aletheore aletheore Bot Dec 5, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 4861885e5088.


🔵 Low · Maintainability · 6 of 6

Rust turbo3 test only verifies packing of first 8 values, leaving 120 values unchecked The loop asserts mag/sign only for i in 0..8 (signs[0] only). A sign-plane or code-plane bug at i>=8 (e.g. wrong byte/bit index in quantize3/dequantize3) would not be caught by the exact check; only the loose mean_err<0.09/cos>0.97 aggregate might catch gross errors.

Prompt for your AI agent
File: src/kv_turbo.rs
Line: 295
Issue: Rust turbo3 test only verifies packing of first 8 values, leaving 120 values unchecked The loop asserts mag/sign only for i in 0..8 (signs[0] only). A sign-plane or code-plane bug at i>=8 (e.g. wrong byte/bit index in quantize3/dequantize3) would not be caught by the exact check; only the loose mean_err<0.09/cos>0.97 aggregate might catch gross errors.
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.

}
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 @@ -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 {

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 · 3 of 5

kv_words for mode 5 under-allocates hd64

25/128 words vs shader's 13 words per 64 values Shader per-row stride is 364/8+2((64+127)/128)=26 bytes=13 u16 words (one fp16 norm per 64-group). kv_words gives n*25/128 = 12.5 words per 64 values, e.g. 25 words for 2 rows instead of 26. Host allocation is short, shader writes/reads the last row's norm/code past the buffer and rows overlap the allocation end.

Prompt for your AI agent
File: src/vulkan/mod.rs
Line: 1353
Symbol: kv_words_v
Issue: kv_words for mode 5 under-allocates hd64: 25/128 words vs shader's 13 words per 64 values Shader per-row stride is 3*64/8+2*((64+127)/128)=26 bytes=13 u16 words (one fp16 norm per 64-group). kv_words gives n*25/128 = 12.5 words per 64 values, e.g. 25 words for 2 rows instead of 26. Host allocation is short, shader writes/reads the last row's norm/code past the buffer and rows overlap the allocation end.
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.

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
52 changes: 46 additions & 6 deletions src/vulkan/shaders/tq.glsl
Original file line number Diff line number Diff line change
Expand Up @@ -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);

@aletheore aletheore Bot Dec 5, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 4861885e5088.


🟠 High · Correctness · 2 of 6

Vulkan 3-bit layout has same 25 B odd stride and truncated u16 norm index for hd<128 tq_put/tq_ldkv use r=e/hd*(3hd/8+hd/64)=25 B/row for hd=64 and c.v[(r+3hd/8)/2+g] for the norm. Odd r truncates on /2, the norm word overlaps the next row, and allocation from kv_words is 1 B/row short, corrupting codes and norms for Inkling hd64 turbo3.

Prompt for your AI agent
File: src/vulkan/shaders/tq.glsl
Line: 131
Issue: Vulkan 3-bit layout has same 25 B odd stride and truncated u16 norm index for hd<128 tq_put/tq_ldkv use r=e/hd*(3*hd/8+hd/64)=25 B/row for hd=64 and c.v[(r+3*hd/8)/2+g] for the norm. Odd r truncates on /2, the norm word overlaps the next row, and allocation from kv_words is 1 B/row short, corrupting codes and norms for Inkling hd64 turbo3.
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.

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 5

turbo3 hd64 stored norm uses unscaled norm instead of qnorm, dequantized values off by sqrt(2) For hd=64, qnorm=normsqrt(128/64)=1.414norm and q=nearest(x/qnorm), so x≈centroidqnorm/recon. Code stores norm/recon, and tq_ldkv returns centroid(norm/recon), underestimating every hd64 turbo3 value by 1.414x. Prefill-vs-decode tests pass because both use same wrong norm, but values drift from f16/CPU.

Prompt for your AI agent
File: src/vulkan/shaders/tq.glsl
Line: 138
Issue: turbo3 hd64 stored norm uses unscaled norm instead of qnorm, dequantized values off by sqrt(2) For hd=64, qnorm=norm*sqrt(128/64)=1.414*norm and q=nearest(x/qnorm), so x≈centroid*qnorm/recon. Code stores norm/recon, and tq_ldkv returns centroid*(norm/recon), underestimating every hd64 turbo3 value by 1.414x. Prefill-vs-decode tests pass because both use same wrong norm, but values drift from f16/CPU.
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 + 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);
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.
13 changes: 11 additions & 2 deletions tests/inkling2_q8_attention.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@ fn cpu_cache(words: &[u16], mode: &str, rows: usize, hd: usize) -> Vec<f32> {
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"),
};
Expand All @@ -54,9 +55,17 @@ fn cpu_cache(words: &[u16], mode: &str, rows: usize, hd: usize) -> Vec<f32> {
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)
}
Expand Down
23 changes: 22 additions & 1 deletion tests/kv_turbo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -215,5 +215,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");
}

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 · Maintainability · 5 of 6

turbo3 vs f16 assertion rel_l2 < 1.0 is vacuous and cannot catch drift/scaling bugs rel_l2 < 1.0 passes for a zero vector or a vector scaled by ~0 (error ~1.0 boundary) and for the sqrt(2) hd64 scaling error. The test therefore passes even if dequantized turbo3 values are systematically wrong, masking the hd64 layout/scaling defects above.

Prompt for your AI agent
File: tests/kv_turbo.rs
Line: 240
Issue: turbo3 vs f16 assertion rel_l2 < 1.0 is vacuous and cannot catch drift/scaling bugs rel_l2 < 1.0 passes for a zero vector or a vector scaled by ~0 (error ~1.0 boundary) and for the sqrt(2) hd64 scaling error. The test therefore passes even if dequantized turbo3 values are systematically wrong, masking the hd64 layout/scaling defects above.
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.

Loading
Loading