Skip to content

TurboQuant: pack turbo3 in 3 bits (50 B per 128 values) - #215

Open
sayampy wants to merge 4 commits into
RustingStudio:mainfrom
sayampy:quant/attention-safe
Open

sayampy wants to merge 4 commits into
RustingStudio:mainfrom
sayampy:quant/attention-safe

Conversation

@sayampy

@sayampy sayampy commented Dec 5, 2026

Copy link
Copy Markdown
Contributor

Supersedes #121 (which GitHub locked after its head branch was force-pushed during the rebase). This is the same two commits, now rebased cleanly onto main.

What this does

  • turbo3 now uses a real 3-bit layout: a 2-bit code plane (4 values/byte) plus a 1-bit sign plane (8 values/byte) and one fp16 reconstruction-corrected norm per 128 values — 50 B per 128 values instead of the 4-bit modes' 66 B (25 u16 words vs 36).
  • hd64 (Inkling 2) centroid scale is matched to its WHT group: the norm is scaled by sqrt(128/group) on store so a 64-value group (twice the variance) quantizes correctly, with no width-dependent correction at dequant.

Where

  • CUDA: kv_put_tq, ldkv, ldkv1_at (3-bit branch), kv_mode_words (mode 5 → 25/128 words).
  • Vulkan: tq.glsl (tq_put, tq_ldkv, tq_ldkv2), kv_words/kv_words_v, regenerated .spv.
  • CPU reference: quantize3/dequantize3 in kv_turbo.rs + round-trip test.
  • Docs + tests (kv_turbo, vulkan_split_kv incl. a turbo3 hd64 case).

Verification

  • Rebased onto main (03cd705); no conflicts remain.
  • .spv regenerated with tools/gen_spirv.sh; local glslc reproduces the committed shaders byte-for-byte, so the freshness check holds.

@sayampy

sayampy commented Dec 5, 2026 •

Copy link
Copy Markdown
Contributor Author

The old PR (#121) was stuck: it was opened against a main from the 1.4.0 days, so by now it was ~1200 commits behind and GitHub flagged it as conflicting. To get it mergeable I rebased the two commits onto current main.

What I actually changed:

  • Replayed the two commits onto main. Two real conflicts, both mechanical:
    • src/cuda/mod.rs: upstream had made kv_mode_words pub(crate) and folded mode 5 into the 4-bit group. Kept the pub(crate) visibility and re-split mode 5 (turbo3) out to 25/128 words.
    • src/cuda/kernels.cu: upstream had renamed ldkv1 → ldkv1_at and switched it to separate row/w args. The 3-bit branch still used the old off, so I translated it (off/hd → row, off%hd → w). No logic change, just the new signature.
  • Regenerated every .spv with tools/gen_spirv.sh since tq.glsl changed. I double-checked the toolchain first: on a clean main checkout my glslc reproduces the committed shaders byte-for-byte, so the "spirv is fresh" test stays happy and the only shader growth is the actual 3-bit code.

@aletheore

aletheore Bot commented Dec 5, 2026 •

Copy link
Copy Markdown

🔍 Aletheore evidence diff

graph LR
    n0["src/cuda/mod.rs"]
    n1["kv_turbo.rs"]
    n2["src/vulkan/mod.rs"]
    n3["src/backend.rs"]
    n4["chat.rs"]
    n5["src/hip/mod.rs"]
    n6["device.rs"]
    n7["lib.rs"]
    n8["main.rs"]
    n9["preflight.rs"]
    n10["tests/backend.rs"]
    n11["tests/common/mod.rs"]
    n12["gpu_model.rs"]
    n13["inkling2_attn_kv.rs"]
    n14["kv_q8.rs"]
    n15["llama_numerics.rs"]
    n0 --> n3
    n0 --> n4
    n0 --> n5
    n0 --> n6
    n0 --> n7
    n0 --> n8
    n0 --> n9
    n0 --> n11
    n0 --> n12
    n0 --> n13
    n0 --> n14
    n0 --> n15
    n1 --> n7
    n2 --> n3
    n2 --> n7
    n2 --> n9
    n2 --> n10
    n2 --> n11
    n2 --> n12
    n2 --> n14
    n2 --> n15
    classDef changed fill:#d9772c,color:#fff,stroke:#b85f1c;
    classDef changedFinding fill:#c0392b,color:#fff,stroke:#922b21;
    classDef dependent fill:#f2f0ec,color:#18140f,stroke:#d6d0c5;
    class n0 changed
    class n1 changed
    class n2 changed
    class n3 dependent
    class n4 dependent
    class n5 dependent
    class n6 dependent
    class n7 dependent
    class n8 dependent
    class n9 dependent
    class n10 dependent
    class n11 dependent
    class n12 dependent
    class n13 dependent
    class n14 dependent
    class n15 dependent
Loading

What changed
Deterministic, computed from this commit's real scan and import graph - posted on every run, whether or not Flash Review found anything.

  • docs/USAGE.md · modified · +3/-1
  • src/cuda/kernels.cu · modified · +65/-18
  • src/cuda/mod.rs · modified · +1/-1 · 12 other dependents
  • src/kv_turbo.rs · modified · +59/-0 · +3 functions · 1 other dependent
  • src/vulkan/mod.rs · modified · +2/-2 · 8 other dependents
  • src/vulkan/shaders/tq.glsl · modified · +46/-6
  • src/vulkan/spv/attn_decode.spv · modified
  • src/vulkan/spv/attn_prefill_128.spv · modified
  • src/vulkan/spv/attn_prefill_256.spv · modified
  • src/vulkan/spv/attn_prefill_64.spv · modified
  • src/vulkan/spv/attn_prefill_dp.spv · modified
  • src/vulkan/spv/attn_prefill_tile.spv · modified
  • src/vulkan/spv/attn_sel.spv · modified
  • src/vulkan/spv/ink_attn.spv · modified
  • src/vulkan/spv/ink_attn_prefill.spv · modified
  • src/vulkan/spv/ink_clip.spv · modified
  • src/vulkan/spv/kv_store.spv · modified
  • src/vulkan/spv/rms_norm.spv · modified
  • tests/inkling2_q8_attention.rs · modified · +11/-2
  • tests/kv_turbo.rs · modified · +22/-1 · +1 function
  • +1 more changed file(s)

Aggregate deltas

  • Modules: -10
  • Dependency graph edges: -15
  • Commits: -61

Comment thread src/cuda/kernels.cu
| (__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.

| (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.

Comment thread src/cuda/mod.rs
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.

Comment thread src/cuda/kernels.cu
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.

Comment thread tests/kv_turbo.rs
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.

Comment thread src/kv_turbo.rs
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.

@aletheore

aletheore Bot commented Dec 5, 2026 •

Copy link
Copy Markdown

Aletheore Flash Lite review

What this PR does. The pull request rewrites docs/USAGE.md, reorganizing and condensing documentation for rustingstrata commands, flags, server, MCP, and model loading options. It affects users and operators reading usage documentation for chat, generate, serve, bench, calibrate, stats, and update.

Merge confidence Review effort Merge risk
2 / 5 5 / 5 Medium
Area Files Lines
tests 3 +49 −9
src/cuda 2 +86 −31
src/vulkan 2 +50 −10
docs 1 +494 −524
src 1 +59 −0

5 finding(s) posted as inline review comment(s). 3 earlier finding(s) from previous pushes still open. 3 earlier finding(s) no longer detected in this push.

# Severity Category Where
1 🟠 High Correctness kernels.cu:4352 Stored turbo3 norm uses unscaled norm, not qnorm, so hd<128 dequant is off by sqrt(128/hd) For hd=64…
2 🟠 High Correctness tq.glsl:138 turbo3 hd64 stored norm uses unscaled norm instead of qnorm, dequantized values off by sqrt(2) For hd=64…
3 🟡 Medium Correctness mod.rs:1353 kv_words for mode 5 under-allocates hd64
4 🟡 Medium Correctness mod.rs:276 kv_mode_words for mode 5 has same hd64 under-allocation as Vulkan kv_words With hd=64 (Inkling 2), n=rows*64…
6 🟡 Medium Correctness kv_turbo.rs:126 CPU quantize3/dequantize3 has no hd64 sqrt(128/group) scaling, mismatching Vulkan tq_put quantize3 quantizes…
- 🟠 High Correctness mod.rs:276 Earlier finding, still open
- 🟡 Medium Correctness kernels.cu:4317 Earlier finding, still open
- 🔵 Low Maintainability kv_turbo.rs:240 Earlier finding, still open
Review details

Reviewed 9 file(s); skipped 12. Dismissed 0; outside PR diff 1. Grounding: 14 of 15 proposed finding(s).

Fix all with your 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.

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.

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.

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.

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.

Note: 12 of 21 changed file(s) were not included in this review (the review reads at most 30 files, and skips any file over 100KB). Issues in them would not be found, and citations pointing into them could not be checked against the real file: src/vulkan/spv/attn_decode.spv, src/vulkan/spv/attn_prefill_128.spv, src/vulkan/spv/attn_prefill_256.spv, src/vulkan/spv/attn_prefill_64.spv, src/vulkan/spv/attn_prefill_dp.spv, src/vulkan/spv/attn_prefill_tile.spv, src/vulkan/spv/attn_sel.spv, src/vulkan/spv/ink_attn.spv, src/vulkan/spv/ink_attn_prefill.spv, src/vulkan/spv/ink_clip.spv….

Blast radius: 61 other file(s) depend on what this PR changes (13 directly, 48 indirectly)

Computed from the import graph of this exact commit, not guessed by a model. It sees imports only, so dynamic imports, reflection and non-code references are not counted.

  • src/cuda/mod.rs is imported by src/backend.rs, src/deepseek/chat.rs, src/hip/mod.rs, src/inkling2/forward/device.rs (+8 more)
  • src/vulkan/mod.rs is imported by src/backend.rs, src/lib.rs, src/vulkan/preflight.rs, tests/backend.rs (+4 more)
  • src/kv_turbo.rs is imported by src/lib.rs

Indirectly affected: src/calibrate.rs, src/cpu_worker.rs, src/deepseek/mat.rs, src/deepseek/mod.rs, src/expert_cache.rs, src/gemma4/mod.rs (+42 more)

The graph is large; this list is capped and not exhaustive.

@Vasyl-Trefilov

Copy link
Copy Markdown
Member

Hi, ty, 50 B per 128 values is a nice saving. I merged it onto main here and ran the tests on my GPU (RTX 3060). Some things pls before I can merge:

  1. Head width 64 (Inkling 2): the turbo3 row is 3*hd/8 + hd/64 = 25 bytes, but it holds 16 bytes of codes, 8 bytes of signs and a 2 byte norm, so 26. The norm of a row lands on the first code byte of the next row, and kv_mode_words(5, 64) gives 12 words = 24 bytes. tq.glsl has the same stride. With head width 128 and 256 the layout is fine. I think the norm part must be 2 bytes per group, not hd/64.
  2. tests/inkling2_q8_attention.rs is not in the PR and its cpu_cache still decodes turbo3 as nibbles. q8_attention_cases fails here with "index out of bounds: the len is 8 but the index is 13" at line 60. On main it passes.
  3. qnorm = norm * sqrtf(128 / gw) is outside of the BITS == 3 branch, so turbo4 and turbo2 store other values than before at head width 64. Is this wanted? It changes the output of modes that people use now, so if yes it needs its own test against the CPU reference at head width 64.
  4. docs/USAGE.md: the 4-bit modes take 72 B per 128 values, not 66 (kv_mode_words gives 36 words). And turbo4-3 and turbo3-2 are listed with the nibble packing, but their turbo3 side is 3-bit now.
    A CUDA test at head width 64 against quantize3 from kv_turbo.rs would catch point 1. The new turbo3 test runs only head width 128 on CUDA, and the Vulkan one compares prefill with decode on the same cache, so both sides have the same error.

Drop the temporary 'int we = w;' left over from adapting the old
off-based ldkv1 to the row/w ldkv1_at signature; the M==3/2/1 branches
already use w directly. Behavior-preserving.
…g2 turbo3 decode

Addresses the maintainer review of the turbo3 KV layout:

- CUDA + Vulkan: a turbo3 row is now 3*hd/8 + 2*ceil(hd/128) bytes (a 2-byte fp16
  norm per 128-value group) instead of hd/64, so the norm no longer overflows onto
  the next row's first code byte. Matches TheTom/llama-cpp-turboquant block_turbo3_0
  (QK_TURBO3=128, one norm per fixed 128-value block). At hd=64 the row is 26 B;
  at hd>=128 the stride is unchanged.
- CUDA + Vulkan: gate the sqrt(128/gw) norm rescale inside the 3-bit branch so
  turbo4/turbo2 keep the unscaled norm.
- tests/inkling2_q8_attention.rs: decode turbo3 as 3-bit (was a 4-bit nibble),
  byte-for-byte like kv_turbo::dequantize3; fixes the index-out-of-bounds.
- docs/USAGE.md: 4-bit modes are 72 B per 128 values (36 words), not 66; clarify
  that the turbo3 half of a composite is 3-bit packed.
- Regenerate SPIR-V so spirv_is_fresh holds.

hd=64 turbo3 stays guarded (hd % 128 == 0); no sizing change is required.
@sayampy
sayampy force-pushed the quant/attention-safe branch from a0e4bda to 4861885 Compare December 6, 2026 06:53
@sayampy

sayampy commented Dec 6, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed review — all four points are addressed, and the branch is rebased onto current main (90be912).

  1. hd=64 turbo3 row stride. The row now reserves 3*hd/8 + 2*ceil(hd/128) bytes (norm is one fp16 per 128-value group), so hd=64 gets 26 B/row instead of 24 — the second norm byte no longer overflows onto the next row's first code byte. Fixed at all six sites (three in kernels.cu, three in tq.glsl), with the norm at byte 3*hd/8 + 2*g. This matches the reference block_turbo3_0 layout (fixed 128-value block = rotation group). hd=128/256 are byte-identical to before (50 B/128). Note the general turbo path is still guarded by hd % 128 == 0 on all backends, so hd=64 turbo is only reachable via the Inkling 2 path — which now shares the same corrected layout.

  2. inkling2_q8_attention turbo3 decode. cpu_cache now decodes turbo3 as 3-bit (mag at col/4, sign at hd/4 + col/8, fp16 norm at 3*hd/8 + 2*(col/128), 8 centroids), byte-for-byte matching dequantize3. The index 13 out of bounds is gone.

  3. qnorm scope. The sqrt(128/gw) scale is now inside the BITS == 3 branch only, so turbo4 and turbo2 store the same values as main at every head width. (At the reachable widths gw=128, so the factor is 1 there anyway — this just stops the leak.)

  4. docs/USAGE.md. Corrected to 72 B per 128 values (36 words) for the 4-bit modes, and the turbo3 composites are documented as 3-bit rather than nibble.

New/updated tests: turbo3_uses_3_bit_packing and turboquant_ink_clip_hd64 (hd=64 against the CPU reference). Verified locally on an RTX 3050: spirv_is_fresh, kv_turbo (3), kv_q8 (4), kernels (39) all pass — f16/q8/q4/q2 remain bit-identical to main.

Comment thread src/cuda/kernels.cu
}
}
#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.

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 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.

Comment thread src/vulkan/mod.rs
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.

Comment thread src/cuda/mod.rs
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 · 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.

Comment thread src/kv_turbo.rs
/// 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.

@Vasyl-Trefilov

Copy link
Copy Markdown
Member

Hi, ty for the update. Points 2, 3 and 4 are good now, and the shaders are fresh. All the turbo tests pass here on CUDA and Vulkan.

Point 1 is only half done. The kernels and the shader use the right 26 B row at head width 64, but the buffer size still comes from n * 25 / 128 (kv_mode_words in src/cuda/mod.rs, kv_words and kv_words_v in src/vulkan/mod.rs). Inkling 2 sizes its cache with that, so at head width 64 a row gets 24 B and the last rows write past the end. Two ways I would be ok with:

  1. one fp16 norm per 64 values for turbo3, so a row is 13 words per 64 values and n * 13 / 64 is exact for 64 and 128
  2. pass the head width to kv_words so it can count 2 bytes per started 128 group

Two small things for the tests:

  1. pls add a CUDA turbo3 test at head width 64 that compares with kv_turbo::quantize3 / dequantize3, the hd64 test in kv_turbo.rs is still turbo4 and checks against f16
  2. rel_l2 < 1.0 in turbo3_uses_3_bit_packing passes almost anything, the log here shows about 0.13, so something like 0.2 would catch a broken layout

After that I merge it.

Licenser pushed a commit to Licenser/RustingStrata that referenced this pull request Dec 6, 2026
…hecks

Co-authored-by: Andrew Pavlov <100561417+andrew-pavlov-ua@users.noreply.github.com>
@sayampy

sayampy commented Dec 6, 2026

Copy link
Copy Markdown
Contributor Author

oh ok, I am not really running the inkling model, just running the tests to see if the quantizations are giving correctly rotated numbers so that might be an oversight from my part.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants