Skip to content

CUDA TurboQuant KV cache: WHT + Lloyd-Max, general engine, asymmetric K/V - #84

Open
sayampy wants to merge 6 commits into
RustingStudio:mainfrom
sayampy:turboquant/cuda
Open

sayampy wants to merge 6 commits into
RustingStudio:mainfrom
sayampy:turboquant/cuda

Conversation

@sayampy

@sayampy sayampy commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

CUDA TurboQuant KV cache

This adds TurboQuant as a KV cache format for CUDA. It is based on TheTom's llama-cpp-turboquant algorithm: each block of 128 values is unit-L2 normalized, signed-Walsh rotated, quantized with Lloyd-Max centroids, and stored with a reconstruction-corrected fp16 norm. That is 72 bytes per 128 values, about 28 percent of the f16 cache and the same size as q4.

Q gets the same rotation when the K cache is TurboQuant, and the attention output gets rotated back when the V cache is TurboQuant. The Rust side in src/kv_turbo.rs holds the seeded sign diagonals, the 2/3/4-bit centroids and the QJL code.

It works on the Inkling 2 path and on the general CUDA attention path. For head_dim 256 the code uses two groups of WHT-128 per head, each with its own norm. For head_dim 64 it uses one WHT-64 group.

Reference implementation

This is a native Rust port, not a ggml fork. src/kv_turbo.rs holds the seeded WHT-128 sign diagonals, the Lloyd-Max 2/3/4-bit codebooks and the QJL projection; the CUDA kernels are compiled at runtime with NVRTC, so no C++ changes to llama.cpp are needed.

The port was checked against TheTom's llama-cpp-turboquant (feature/turboquant-kv-cache at f7c3638e8): unit-L2 block norm with a reconstruction-corrected fp16 norm, seed-42 WHT signs S1 = {0xE46A0359, 0x42F85949, 0xA4C63BBB, 0x49F250A9} and S2 = {0x16ACEE90, 0x3F628FDC, 0xB7A5357A, 0xBEA56562}, forward rotation S1, butterfly, 1/sqrt(128), S2 and the inverse with the sign order swapped. The Lloyd-Max centroids for N(0, 1/128) have 4-bit max +/-0.241529, 3-bit +/-0.190207 and 2-bit +/-0.133462. K/V are rotated on write, Q in attention, and the output inverse-rotated once before the gate. The reference supports turbo2 through turbo6 with separate -ctk and -ctv types; this PR covers 2/3/4-bit and adds arbitrary legacy and turbo K/V pairs.

Related upstream work checked: llama.cpp PRs #387 (Vulkan turbo3 codebook fix), #420 (multi-GPU per-device InnerQ scale) and #421 (turbo5/6 at head_dim 512). None explained the issues found here.

How to use it

strata generate --model MODEL.gguf --gpu --kv turbo4
strata generate --model MODEL.gguf --gpu --kv turbo4-3
strata generate --model MODEL.gguf --gpu --k turbo4 --v q4
strata generate --model MODEL.gguf --gpu --k f16 --v turbo4
strata calibrate --model MODEL.gguf --kv turbo4
strata bench --model MODEL.gguf --gpu --pp 128 --tg 32 --reps 3 --kv turbo4

--kv takes f16, q8, q4, q2, turbo4, turbo4-3, turbo4-2, turbo3, turbo2 and turbo3-2. --k takes f16, q8, q4, turbo4, turbo3 and turbo2. --v takes f16, q8, q4, q2, turbo4, turbo3 and turbo2. --k and --v override the two halves of --kv, and they work even when --kv is left at its f16 default. The settings go out as STRATA_KV_K and STRATA_KV_V, with STRATA_KV kept as the symmetric alias, so generate, calibrate and bench use the same cache format.

TurboQuant needs CUDA or Vulkan. The general attention path needs a head_dim divisible by 128; the Inkling 2 path also handles head_dim 64 with one WHT-64 group. Quantized KV does not combine with --llama-numerics.

Review fixes

The int8 copy in attn_merge now happens after the Q gate, as on main, so q_gate models keep the right input in the output projection. The Inkling prefill kernel uses main's lane + 32*j layout for every legacy head size and only uses the contiguous WHT layout on a TurboQuant half, with K and V indexed independently. The general prefill kernel stages the inverse WHT per query row and per WHT group, which removed the row collisions that made prefill disagree with decode.

The Inkling grow path sizes K and V with their own word widths now, so f16 no longer uses twice the KV memory after the context grows. ds_env publishes --k and --v even with the default --kv f16.

ink_clip now stores rotated and normalized TurboQuant rows for every width, not just 128. Widths of 128 and above use WHT-128 groups, head_dim 64 uses WHT-64, and narrower widths leave Q and K unrotated on both sides. The lane mapping in the Inkling prefill epilogue follows the same rule, so prefill and decode stay consistent at head_dim 64. Turbo V prefill now lets all four warps rotate their own query rows in parallel, which cuts the barrier count per tile from 192 to 17, or 384 to 34 at head_dim 256, while keeping the same staged data.

Correctness

Legacy modes stay bit-identical to main. tests/kv_turbo.rs pins 16 rows of FNV-1a hashes (K bytes, V bytes, prefill and decode) for f16, q8, q4 and q2 over four shapes. The expected values came from running the same harness on main at bbd57c2, and every hash matches here.

For TurboQuant the same test checks that turbo4 and q4 use the same number of cache words, that mixed halves get their own word widths, and that prefill agrees with decode to better than 5e-4 relative L2. After the row-index fix the measured values are 9.28e-5 at head_dim 128, 7.91e-5 at head_dim 256 and 6.35e-5 with GQA 1. The f16 control is about 8e-5. A standalone CUDA round-trip on random vectors measured 0.104 RMSE at 4-bit and 0.179 at 3-bit. A new head_dim 64 case covers the Inkling clip and prefill paths at a non-128 width: prefill versus decode is 2.22e-7 and TurboQuant versus f16 is 1.07e-1 relative L2.

Quality

Numbers below are from greedy decoding with --mtp 0. Perplexity is over 511 scored tokens of a natural-text sample with --ctx-len 1024 --chunks 1. Top-1 and KLD compare --kld-base dumps against f16 over the same positions. turbo4 and q4 have the same cache size.

Model KV PPL KV at 4096 ctx top-1 vs f16 mean KLD vs f16
Tiel Coder 35B A3B, head_dim 256, GQA 8 f16 5.7504 80 MB
q4 5.8526 22 MB 455/511 = 89.04% 0.0429
q8 5.7597 40 MB 478/511 = 93.54% 0.0206
turbo4 5.8122 22 MB 464/511 = 90.80% 0.0361
K=turbo4 V=turbo3 5.7983 ~20 MB 464/511 = 90.80% 0.0611

turbo4 is ahead of q4 on PPL, top-1 and KLD at the same cache size. The mixed setting keeps the same top-1 but has a higher KLD, which is expected with a 2-bit V half.

On Inkling 2 Mini, five configurations (f16, q4, q8, turbo4 and K=turbo4 V=turbo3) were each given two fixed prompts: a train-average-speed word problem and an is_prime function. All ten completions gave the right answer and a function that passes basic primality tests, and the KV settings did not change the result.

Speed

This bench used Inkling 2 Mini UD-Q3_K_XL with the built-in prose, --pp 128 --tg 32 --reps 3 --ctx 4096 --chunk 128 --mtp 0 --temp 0. Numbers are mean tokens/s over three runs. MoE expert swaps move a few tokens/s between runs, so small differences are not meaningful.

KV prefill decode KV prefill decode
f16 30.5 7.1 turbo4 42.6 8.4
q8 40.7 7.9 turbo4-3 36.8 8.1
q4 43.1 8.2 turbo3 32.4 7.7
q2 41.8 8.0 turbo2 28.9 7.6
K=f16 V=q4 31.3 7.2 K=q8 V=q4 35.3 7.6
K=turbo4 V=f16 39.0 6.5 K=f16 V=turbo4 33.6 7.3
K=turbo4 V=q4 31.5 7.5 K=q4 V=turbo4 36.6 7.5
K=turbo3 V=turbo2 33.8 7.5

A larger-context run used --pp 2048 --tg 1024 --reps 1 --ctx 8192 --chunk 512 on the same model:

KV prefill decode
f16 47.3 8.9
q8 58.0 8.5
q4 55.8 8.5
turbo4 47.0 8.4
K=turbo4 V=turbo3 49.8 8.4

Tests

cargo test --release is green. The GPU suites cover 38 kernel tests, 2 kv_turbo tests and 2 vulkan_split_kv tests, including the pinned legacy hashes, the head_dim 64 Inkling case on both backends, and NVRTC compiles for older sm targets. The branch is rebased onto current main (6b88a33) and git merge-tree reports no conflicts.

The branch merges cleanly with main at 932b252 with no conflicts.

Vulkan support

Vulkan now uses the same independent K and V cache modes as CUDA. Specialization constants 15 and 16 carry the two modes, so f16, q8, q4, q2, turbo4, turbo3 and turbo2 can be paired in either half. The Vulkan shaders gained the WHT rotation from the CUDA port: K/V are rotated before the Lloyd-Max store, Q is rotated in attention, and only the attention output is inverse-rotated before the gate. The Inkling 2 clip, attention and prefill shaders use WHT-64 for head_dim 64, matching CUDA.

Symmetric legacy formats remain byte-identical to CUDA. tests/vulkan_split_kv.rs checks q8, q4 and q2 against CUDA byte-for-byte through the split K/V environment, checks K=q4 with V=q2, verifies the f16 half stays byte-identical next to a turbo half, and measures prefill versus decode relative L2 of 3.65e-4 for turbo4, 3.49e-4 for K=turbo4 V=f16, 3.19e-4 for K=f16 V=turbo4 and 2.43e-7 for the Inkling head_dim 64 case.

Co-author

Hy4-Flash hy4-flash@local

@aletheore

aletheore Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

🔍 Aletheore evidence diff

graph LR
    n0["backend.rs"]
    n1["src/cuda/mod.rs"]
    n2["src/gpu_model.rs"]
    n3["device.rs"]
    n4["lib.rs"]
    n5["src/vulkan/mod.rs"]
    n6["cpu_worker.rs"]
    n7["src/deepseek/chat.rs"]
    n8["mat.rs"]
    n9["expert_cache.rs"]
    n10["src/gemma4/mod.rs"]
    n11["gguf.rs"]
    n12["src/glm/forward.rs"]
    n13["src/glm/mod.rs"]
    n14["prefill.rs"]
    n15["src/hip/mod.rs"]
    n16["src/hy4/chat.rs"]
    n17["src/hy4/mod.rs"]
    n18["src/inkling2/chat.rs"]
    n19["dspark.rs"]
    n20["src/inkling2/forward.rs"]
    n21["src/inkling2/mod.rs"]
    n22["src/kolibri/chat.rs"]
    n23["src/kolibri/mod.rs"]
    n24["model.rs"]
    n25["ngram.rs"]
    n26["serve.rs"]
    n27["weights.rs"]
    n28["tests/common/mod.rs"]
    n29["tests/gpu_model.rs"]
    n30["kernels.rs"]
    n31["kv_q8.rs"]
    n32["llama_numerics.rs"]
    n33["vision.rs"]
    n0 --> n6
    n0 --> n8
    n0 --> n9
    n0 --> n14
    n0 --> n15
    n0 --> n19
    n0 --> n20
    n0 --> n24
    n0 --> n28
    n0 --> n29
    n0 --> n30
    n0 --> n31
    n0 --> n32
    n1 --> n15
    n1 --> n28
    n1 --> n29
    n1 --> n31
    n1 --> n32
    n2 --> n14
    n2 --> n24
    n2 --> n33
    n3 --> n20
    n4 --> n7
    n4 --> n8
    n4 --> n9
    n4 --> n10
    n4 --> n11
    n4 --> n12
    n4 --> n13
    n4 --> n14
    n4 --> n16
    n4 --> n17
    n4 --> n18
    n4 --> n21
    n4 --> n22
    n4 --> n23
    n4 --> n24
    n4 --> n25
    n4 --> n26
    n4 --> n27
    n5 --> n28
    n5 --> n29
    n5 --> n30
    n5 --> n31
    n5 --> n32
    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 changed
    class n4 changed
    class n5 changed
    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
    class n16 dependent
    class n17 dependent
    class n18 dependent
    class n19 dependent
    class n20 dependent
    class n21 dependent
    class n22 dependent
    class n23 dependent
    class n24 dependent
    class n25 dependent
    class n26 dependent
    class n27 dependent
    class n28 dependent
    class n29 dependent
    class n30 dependent
    class n31 dependent
    class n32 dependent
    class n33 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.

  • .vscode/settings.json · added · +3/-0
  • TURBOQUANT.md · added · +165/-0
  • docs/USAGE.md · modified · +8/-0
  • src/backend.rs · modified · +26/-1 · +5 functions · 13 other dependents
  • src/cuda/kernels.cu · modified · +571/-155
  • src/cuda/mod.rs · modified · +107/-42 · +7 functions · 5 other dependents
  • src/gpu_model.rs · modified · +4/-4 · 3 other dependents
  • src/inkling2/forward/device.rs · modified · +20/-19 · 1 other dependent
  • src/kv_turbo.rs · +248/-0 · new file, 19 symbols
  • src/lib.rs · modified · +1/-0 · 18 other dependents
  • src/main.rs · modified · +100/-23 · +7 functions
  • src/vulkan/mod.rs · modified · +60/-14 · +3 functions · 5 other dependents
  • src/vulkan/preflight.rs · modified · +3/-3
  • src/vulkan/shaders/attn_decode.comp · modified · +22/-8
  • src/vulkan/shaders/attn_merge.comp · modified · +17/-1
  • src/vulkan/shaders/attn_prefill.glsl · modified · +73/-5
  • src/vulkan/shaders/attn_prefill_dp.comp · modified · +29/-6
  • src/vulkan/shaders/attn_prefill_tile.comp · modified · +32/-9
  • src/vulkan/shaders/attn_sel.comp · modified · +36/-4
  • src/vulkan/shaders/common.glsl · modified · +37/-16
  • +77 more changed file(s)

Aggregate deltas

  • Modules: +3
  • Dependency graph edges: +8
  • Commits: 6

Comment thread src/cuda/kernels.cu Outdated
kv_put_tq(dst, dat, w, tq[t], sqrtf(ss) * f);
} else
#endif
kv_put(dst, dat, w, v);

@aletheore aletheore Bot Nov 23, 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 c25f1fa65864.


🟠 High · Correctness · 1 of 7

Rows with w!=128 are stored by kv_put, but KV_MODE 4 ldkv/ldkv1 always decode the turbo layout. In KV_MODE 4, ink_clip only uses kv_put_tq when w==128. For any w==64 K/V row it calls kv_put, whose layout is not the turbo nibble+fp16-norm layout. ldkv/ldkv1 for KV_MODE 4 always read the turbo layout (norm at byte hd/2), so hd==64 layers decode garbage norms and codes. The hd==64 attention path in this same diff becomes unreachable with correct data.

Prompt for your AI agent
File: src/cuda/kernels.cu
Line: 2615
Issue: Rows with w!=128 are stored by kv_put, but KV_MODE 4 ldkv/ldkv1 always decode the turbo layout. In KV_MODE 4, ink_clip only uses kv_put_tq when w==128. For any w==64 K/V row it calls kv_put, whose layout is not the turbo nibble+fp16-norm layout. ldkv/ldkv1 for KV_MODE 4 always read the turbo layout (norm at byte hd/2), so hd==64 layers decode garbage norms and codes. The hd==64 attention path in this same diff becomes unreachable with correct data.
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 Outdated
__syncthreads();
// Centroids are for N(0, 1/128) (unit-L2 vectors); ss was measured before the clip scale f,
// so the rotated vector's L2 is sqrt(ss)*f and x / L2 matches the centroid distribution.
kv_put_tq(dst, dat, w, tq[t], sqrtf(ss) * f);

@aletheore aletheore Bot Nov 23, 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 c25f1fa65864.


🟠 High · Correctness · 2 of 7

Stored norm uses sqrt(ss)*f, not the actual L2 of the values quantized after clipping. The norm comes from the pre-clip sum of squares scaled by f. If the clip step changes the values, the vector being quantized has a different L2 than the stored norm. Dequantization is then systematically scaled wrong for rows that hit the clip, and the error is not corrected by the reconstruction factor, which assumes the norm matches the quantized vector.

Prompt for your AI agent
File: src/cuda/kernels.cu
Line: 2612
Issue: Stored norm uses sqrt(ss)*f, not the actual L2 of the values quantized after clipping. The norm comes from the pre-clip sum of squares scaled by f. If the clip step changes the values, the vector being quantized has a different L2 than the stored norm. Dequantization is then systematically scaled wrong for rows that hit the clip, and the error is not corrected by the reconstruction factor, which assumes the norm matches the quantized vector.
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 Outdated
for (int j = 0; j < PER; j++) {
qv[j] = q[((size_t)t * nh + h) * HD + lane + 32 * j] * scale;
// Keep the values in contiguous element order 4*lane+j so tq_wht4's sign bits match the elements.
qv[j] = q[((size_t)t * nh + h) * HD + 4 * lane + j] * scale;

@aletheore aletheore Bot Nov 23, 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 c25f1fa65864.


🔵 Low · Performance · 3 of 7

Prefill element reordering to 4lane+j is applied to all KV modes, breaking coalesced access. Previously consecutive lanes read consecutive q/gate/output elements (lane+32j). Now lanes read elements 4 apart, so each warp load touches about 4x as many memory sectors. This slows prefill for f16, q8, q4 and q2 even though those modes do not need the change. The reorder should be limited to KV_MODE 4.

Prompt for your AI agent
File: src/cuda/kernels.cu
Line: 2718
Issue: Prefill element reordering to 4*lane+j is applied to all KV modes, breaking coalesced access. Previously consecutive lanes read consecutive q/gate/output elements (lane+32*j). Now lanes read elements 4 apart, so each warp load touches about 4x as many memory sectors. This slows prefill for f16, q8, q4 and q2 even though those modes do not need the change. The reorder should be limited to KV_MODE 4.
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 Outdated
tq[t] = v;
__syncthreads();
if (t < 32) {
if (w == 128) { float4 q = make_float4(tq[4*t], tq[4*t+1], tq[4*t+2], tq[4*t+3]); tq_wht4(q, t, false); tq[4*t]=q.x; tq[4*t+1]=q.y; tq[4*t+2]=q.z; tq[4*t+3]=q.w; }

@aletheore aletheore Bot Nov 23, 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 c25f1fa65864.


🔵 Low · Maintainability · 4 of 7

Redundant and unreachable w==128 test and dead else branch in ink_clip. The outer if (w == 128) already guarantees the inner if (w == 128) is true, so the else branch (the tq_wht2 path) can never run. A later maintainer may think hd=64 is handled here, which it is not, and may misread the control flow.

Prompt for your AI agent
File: src/cuda/kernels.cu
Line: 2606
Issue: Redundant and unreachable w==128 test and dead else branch in ink_clip. The outer `if (w == 128)` already guarantees the inner `if (w == 128)` is true, so the else branch (the tq_wht2 path) can never run. A later maintainer may think hd=64 is handled here, which it is not, and may misread the control flow.
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
let mut next = || {
state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
((state >> 11) as f32 / (1u64 << 53) as f32) * 2.0 - 1.0
};

@aletheore aletheore Bot Nov 23, 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 9cbd332325ac.


🔵 Low · Maintainability · 5 of 7

Production module holds unused QJL and 2/3-bit code; kernels duplicate its constants. The QJL projection, CENTROIDS2/3, MID2/3 and the quantizer helpers are used only by tests, not by the shipped kernels. The 4-bit centroids, midpoints and sign diagonals are duplicated as hardcoded values in kernels.cu (TQ_C4, TQ_M4, TQ_S1, TQ_S2). If one copy changes, the CPU reference and GPU kernel silently diverge.

Prompt for your AI agent
File: src/kv_turbo.rs
Line: 200
Issue: Production module holds unused QJL and 2/3-bit code; kernels duplicate its constants. The QJL projection, CENTROIDS2/3, MID2/3 and the quantizer helpers are used only by tests, not by the shipped kernels. The 4-bit centroids, midpoints and sign diagonals are duplicated as hardcoded values in kernels.cu (TQ_C4, TQ_M4, TQ_S1, TQ_S2). If one copy changes, the CPU reference and GPU kernel silently diverge.
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/main.rs Outdated
#[arg(long, default_value = "f16", value_parser = ["f16", "q8", "q4", "q2"])]
#[arg(long, default_value = "f16", value_parser = ["f16", "q8", "q4", "q2", "turbo4"])]
kv: String,
/// GPU backend: cuda or vulkan [default: cuda if it loads, else vulkan].

@aletheore aletheore Bot Nov 23, 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 c25f1fa65864.


🟡 Medium · Correctness · 6 of 7

CLI parser rejects the 'turboquant' alias that mod.rs accepts; turbo4 check ignores backend. mod.rs accepts STRATA_KV=turboquant, but the clap value_parser only allows turbo4, so the alias is reachable only via the env var. The ensure! in runner checks only the model arch, not the CUDA backend. On a non-CUDA build, --kv turbo4 is accepted for Inkling 2 with no CUDA backend to honour it.

Prompt for your AI agent
File: src/main.rs
Line: 149
Symbol: Engine
Issue: CLI parser rejects the 'turboquant' alias that mod.rs accepts; turbo4 check ignores backend. mod.rs accepts STRATA_KV=turboquant, but the clap value_parser only allows turbo4, so the alias is reachable only via the env var. The ensure! in runner checks only the model arch, not the CUDA backend. On a non-CUDA build, --kv turbo4 is accepted for Inkling 2 with no CUDA backend to honour it.
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 Outdated
size_t dat = (dst_pos * rows + row) * w + t;
#if KV_MODE == 4
if (w == 128) {
tq[t] = v;

@aletheore aletheore Bot Nov 23, 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 c25f1fa65864.


🟡 Medium · Correctness · 7 of 7

tq_wht4 WHT rotation is inside a possibly divergent block with __syncthreads. The turbo path calls __syncthreads() inside the store branch, and the enclosing condition for dat is not visible in the diff. If some threads of the block skip that condition while others enter it, the barrier deadlocks the kernel. Block-wide barriers must be reached by every thread, so the enclosing condition needs checking.

Prompt for your AI agent
File: src/cuda/kernels.cu
Line: 2603
Issue: tq_wht4 WHT rotation is inside a possibly divergent block with __syncthreads. The turbo path calls __syncthreads() inside the store branch, and the enclosing condition for `dat` is not visible in the diff. If some threads of the block skip that condition while others enter it, the barrier deadlocks the kernel. Block-wide barriers must be reached by every thread, so the enclosing condition needs checking.
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 Nov 23, 2026 •

Copy link
Copy Markdown

Aletheore Flash Lite review

What this PR does. This PR adds CUDA TurboQuant KV-cache modes (Walsh-Hadamard rotation with Lloyd-Max quantization) to RustingStrata's general engine, plus --k/--v flags for independent K and V formats, along with backend trait and kernel changes. It affects users who run RustingStrata with --gpu on NVIDIA hardware and want a smaller KV cache, and the bundled work log says the GPU path is not yet validated because baseline GPU inference also produces garbage on the test machine.

Merge confidence Review effort Merge risk
2 / 5 5 / 5 Medium
Area Files Lines
src/vulkan 16 +612 −100
src 5 +418 −39
tests 3 +352 −2
src/cuda 2 +791 −223
(root) 1 +165 −0
.vscode 1 +3 −0
docs 1 +13 −3
src/inkling2 1 +20 −19

7 finding(s) posted as inline review comment(s). 9 earlier finding(s) from previous pushes still open.

# Severity Category Where
2 🟠 High Correctness mod.rs:1246 Attention reads kv_mode() from the environment on every launch instead of the compiled modes. kv_mode() calls…
3 🟠 High Correctness kernels.cu:3152 ink_clip picks the K or V quantizer from the sign of thr, an implicit and fragile contract. ink_clip_v…
4 🟡 Medium Correctness mod.rs:1393 Turbo KV rejects head_dim 64, contradicting the description's WHT-64 claim. The description says head_dim 64…
6 🔵 Low Maintainability TURBOQUANT.md:1 Internal work log with local paths and unverified GPU claims is committed to the repo. The file exposes…
7 🔵 Low Performance kernels.cu:2979 Turbo dequant indexes constant centroid arrays with per-lane data, serializing reads…
8 🔵 Low Performance kernels.cu:4464 attn_prefill_llama declares a tro staging buffer it never uses. The new shared float tro[2][4][128] (4…
9 🔵 Low Maintainability mod.rs:153 kv_legacy_symmetric guard is dead code after the unreachable! path was removed. The doc comment says the…
- 🟠 High Correctness main.rs:389 Earlier finding, still open
- 🟡 Medium Correctness mod.rs:368 Earlier finding, still open
- 🟠 High Correctness kernels.cu:2872 Earlier finding, still open
- 🟠 High Correctness kernels.cu:2872 Earlier finding, still open
- 🟠 High Correctness kernels.cu:2763 Earlier finding, still open
- 🟡 Medium Correctness kernels.cu:2780 Earlier finding, still open
- 🟡 Medium Correctness kernels.cu:2856 Earlier finding, still open
- 🔵 Low Correctness kernels.cu:2910 Earlier finding, still open
- 🟡 Medium Correctness kernels.cu:3050 Earlier finding, still open
Review details

Reviewed 29 file(s); skipped 68. Dismissed 0; outside PR diff 3. Grounding: 20 of 26 proposed finding(s).

Fix all with your agent
File: src/cuda/mod.rs
Line: 1246
Symbol: ink_attn_prefill
Issue: Attention reads kv_mode() from the environment on every launch instead of the compiled modes. kv_mode() calls env::var on each attention launch. If STRATA_KV changes after Gpu::new, the shared-memory variant is chosen from the new env while kernels were compiled for the old modes, so the wrong KV layout is read. Each call also adds env lookups per layer per token. Use self.kv_k_mode and self.kv_v_mode.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/cuda/kernels.cu
Line: 3152
Issue: ink_clip picks the K or V quantizer from the sign of thr, an implicit and fragile contract. ink_clip_v forwards the caller's thr unchanged to the same kernel. A caller that passes thr > 0 for the V cache writes K-format (and, with TurboQuant, K-mode WHT) data into V, and the mismatch is silent. Pass an explicit is_v flag.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/cuda/mod.rs
Line: 1393
Symbol: kv_store
Issue: Turbo KV rejects head_dim 64, contradicting the description's WHT-64 claim. The description says head_dim 64 uses one WHT-64 group, but kv_store fails for any hd not divisible by 128. A 64-dim model with --kv turbo4 errors at the first store. attn_merge and attn_decode_t also only handle 128-wide groups, so the 64-dim case needs the WHT-64 path added there too.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: TURBOQUANT.md
Line: 1
Issue: Internal work log with local paths and unverified GPU claims is committed to the repo. The file exposes /home/sayam paths and a personal branch history. It says GPU output is garbage and mixed K/V pairs are not implemented, but USAGE.md and the code now support them. Its test counts (371/325) conflict with the code (399/330). Shipping it misleads reviewers and users.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/cuda/kernels.cu
Line: 2979
Issue: Turbo dequant indexes __constant__ centroid arrays with per-lane data, serializing reads. tq_centroid<BITS>(q) indexes TQ_C4 with a per-thread nibble. Divergent constant-memory addresses are serialized across the warp, and this runs for every K/V element in every decode step. A shared-memory table or a register formula avoids the serialization.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/cuda/kernels.cu
Line: 4464
Issue: attn_prefill_llama declares a tro staging buffer it never uses. The new __shared__ float tro[2][4][128] (4 KB) is added to attn_prefill_llama, but this diff adds no code that reads or writes it. The unused static shared memory lowers occupancy for the prefill kernel. Remove it.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/cuda/mod.rs
Line: 153
Issue: kv_legacy_symmetric guard is dead code after the unreachable! path was removed. The doc comment says the guard protects an unreachable! in size helpers, but this diff removes that unreachable! and adds no caller of kv_legacy_symmetric. It only has a unit test. Either wire it into the backend that needs it or delete it.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Note: 68 of 97 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/cuda/kernels.cu, src/vulkan/spv/argmax_rows.spv, src/vulkan/spv/attn_decode.spv, src/vulkan/spv/attn_decode_llama.spv, src/vulkan/spv/attn_merge.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_llama.spv….

Blast radius: 50 other file(s) depend on what this PR changes (28 directly, 22 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/lib.rs is imported by src/deepseek/chat.rs, src/deepseek/mat.rs, src/expert_cache.rs, src/gemma4/mod.rs (+14 more)
  • src/backend.rs is imported by src/cpu_worker.rs, src/deepseek/mat.rs, src/expert_cache.rs, src/gpu_model/prefill.rs (+9 more)
  • src/vulkan/mod.rs is imported by tests/common/mod.rs, tests/gpu_model.rs, tests/kernels.rs, tests/kv_q8.rs (+1 more)
  • src/cuda/mod.rs is imported by src/hip/mod.rs, tests/common/mod.rs, tests/gpu_model.rs, tests/kv_q8.rs (+1 more)
  • src/gpu_model.rs is imported by src/gpu_model/prefill.rs, src/model.rs, tests/vision.rs
  • src/inkling2/forward/device.rs is imported by src/inkling2/forward.rs

Indirectly affected: examples/gguf_dump.rs, src/chat.rs, src/config.rs, src/cpu_moe.rs, src/deepseek/forward.rs, src/deepseek/mod.rs (+16 more)

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

@Vasyl-Trefilov

Copy link
Copy Markdown
Member

Thanks for the work again. I can't merge this one as it is. I tested main + this branch on the RTX 3060 with Inkling 2 Mini IQ4_NL.

Blockers:

  1. The default f16 output changes. ink_attn_prefill_t now reads element 4lane+j in every KV mode (it was lane+32j), so the sums run in another order. Greedy, --fixed-experts --spec-type none --mtp 0, prompt "Explain in detail how a transformer KV cache works and why quantizing it changes the output.", 160 tokens: main gives the same text 3 runs of 3, this branch gives another text 3 runs of 3 (they part at byte 255). Please keep the old order for modes 0 to 3 and use the new one only under KV_MODE == 4.

  2. The same index is wrong for head size 64 and 32 in every mode. With PER = 2, lane 31 reads element 125 of a 64-wide head. It has to be PER*lane+j (or the old order).

  3. --kv turbo4 --backend vulkan panics: src/vulkan/mod.rs:1248, "entered unreachable code". It needs a clear error before the backend opens. The ensure! in Engine::runner does not do it, because Inkling 2 never goes through runner.

  4. There is no f16 fallback for other head sizes. With KV_MODE 4 and w != 128, ink_clip calls kv_put, which writes f16 words into rows that kv_words sized at 9/32, and ldkv/ldkv1 then read them as turbo rows. Refuse the mode when the head is not 128.

  5. On this card turbo4 is slower than f16 and than q4, which has the same row size (pp1024/tg64, two runs each):
    f16 prefill 265-270 tok/s, decode 29.1-30.6
    q4 prefill 241-248, decode 27.7-28.4
    turbo4 prefill 173-179, decode 24.1-27.5
    So it needs a reason to exist next to q4: a quality number. A crude check here (how many bytes of greedy text agree with the f16 text of the same binary, two prompts) gave q8 101 and 255, q4 3 and 34, turbo4 3 and 34. That is not a real metric, but it shows no gain. Something like top-1 agreement with f16 over a few hundred teacher-forced tokens, turbo4 against q4, would settle it.

Smaller things:

  • src/kv_turbo.rs is used only by its own tests. The QJL code and the 2/3-bit tables are dead, and the kernel has its own copy of the 4-bit tables with no test that ties the two. Either drop the module or make a test compare a kernel row with quantize4.
  • docs/USAGE.md: the numbers in the docs come from the reference machine, so the RTX 3050 line has to go (keep it in the PR text).
  • kv_mode() accepts "turboquant" but the CLI accepts only turbo4.
  • In ink_clip the inner "if (w == 128)" is always true, so the tq_wht2 branch is dead.

If 1 to 4 are fixed and turbo4 shows better quality than q4 at the same size, I will take it. But for now let's leave it open

@sayampy sayampy changed the title CUDA TurboQuant KV cache for Inkling 2 (faithful WHT + Lloyd-Max) CUDA TurboQuant KV cache: WHT + Lloyd-Max, general engine, asymmetric K/V Nov 23, 2026
Comment thread src/main.rs
fn ds_env(&self) -> anyhow::Result<()> {
// SAFETY: called at the start of a command, before any thread reads these variables.
if let Some(b) = &self.backend { unsafe { std::env::set_var("STRATA_DS_BACKEND", b) } }
if self.device != [0] { unsafe { std::env::set_var("STRATA_DS_DEVICES", self.device.iter().map(|d| d.to_string()).collect::<Vec<_>>().join(",")) } }

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

ds_env skips --k/--v entirely when --kv is the default f16. ds_env only calls set_kv_env_for when self.kv != "f16". Running generate or chat or serve with --k turbo4 (or --k f16 --v q4) and the default --kv f16 leaves STRATA_KV_K/STRATA_KV_V unset, so the GPU builds an f16 cache and the user's K/V choice is silently dropped. Bench and calibrate paths behave differently, so the same flags give different caches depending on the subcommand.

Prompt for your AI agent
File: src/main.rs
Line: 389
Symbol: own_calib
Issue: ds_env skips --k/--v entirely when --kv is the default f16. ds_env only calls set_kv_env_for when self.kv != "f16". Running `generate` or `chat` or `serve` with `--k turbo4` (or `--k f16 --v q4`) and the default `--kv f16` leaves STRATA_KV_K/STRATA_KV_V unset, so the GPU builds an f16 cache and the user's K/V choice is silently dropped. Bench and calibrate paths behave differently, so the same flags give different caches depending on the subcommand.
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 Outdated
else
#endif
kv_store_one<V_MODE, TQ_VBITS>(dst, dat, w, v, 1.0f);
}

@aletheore aletheore Bot Nov 23, 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 eabab8c58931.


🟠 High · Correctness · 2 of 5

ink_clip picks K or V cache mode by the sign of thr. The new ink_clip uses if (thr > 0.f) to decide whether it is writing K (K_MODE) or V (V_MODE). Any caller that passes thr <= 0 for the K side, such as a disabled or zero clip threshold, will store K values using V_MODE and V values using K_MODE. That silently corrupts the cache whenever the two modes differ, for example K=turbo4 with V=q4. The selection should be an explicit argument, not an overloaded float.

Prompt for your AI agent
File: src/cuda/kernels.cu
Line: 2745
Issue: ink_clip picks K or V cache mode by the sign of thr. The new ink_clip uses `if (thr > 0.f)` to decide whether it is writing K (K_MODE) or V (V_MODE). Any caller that passes thr <= 0 for the K side, such as a disabled or zero clip threshold, will store K values using V_MODE and V values using K_MODE. That silently corrupts the cache whenever the two modes differ, for example K=turbo4 with V=q4. The selection should be an explicit argument, not an overloaded float.
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
anyhow::ensure!((self.kv_k_mode == 0 && self.kv_v_mode == 0) || (hd % 32 == 0 && n % hd == 0), "quantized KV cache: head_dim {hd} is not a multiple of 32");
if self.kv_k_mode >= 4 || self.kv_v_mode >= 4 {
anyhow::ensure!(hd % 128 == 0, "TurboQuant KV needs head_dim divisible by 128, got {hd}");
launch!(self, "kv_store_turbo", cfg(((n * t / 128) as u32, 1), 128, 0),

@aletheore aletheore Bot Nov 23, 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 9cbd332325ac.


🟡 Medium · Correctness · 4 of 5

Turbo with head_dim not divisible by 128 errors instead of falling back. kv_store hard-fails with 'TurboQuant KV needs head_dim divisible by 128' for models such as those with 64 or 96 head dims. The PR description promises a smooth fallback to f16 for other head sizes, so a user who selects turbo on a mixed model gets a runtime error in the middle of generation rather than a working f16 cache.

Prompt for your AI agent
File: src/cuda/mod.rs
Line: 1327
Issue: Turbo with head_dim not divisible by 128 errors instead of falling back. kv_store hard-fails with 'TurboQuant KV needs head_dim divisible by 128' for models such as those with 64 or 96 head dims. The PR description promises a smooth fallback to f16 for other head sizes, so a user who selects turbo on a mixed model gets a runtime error in the middle of generation rather than a working f16 cache.
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 Outdated
int col = d * 8 + 2 * t4 + e;
#if V_MODE >= 4
tro[r][col] = o[d][2 * r + e] * inv;
#else

@aletheore aletheore Bot Nov 23, 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 eabab8c58931.


🟡 Medium · Correctness · 5 of 5

Shared tro[2][HD] is written by every warp with no warp index. tro is declared once per block as tro[2][HD] and indexed only by row r and column col. Each warp writes its own query rows (t depends on warp), so warps overwrite one another's values before the inverse WHT. The final orow writes then store another warp's output into this warp's rows. This corrupts prefill output whenever more than one warp handles a head with turbo V enabled.

Prompt for your AI agent
File: src/cuda/kernels.cu
Line: 3807
Issue: Shared tro[2][HD] is written by every warp with no warp index. tro is declared once per block as tro[2][HD] and indexed only by row r and column col. Each warp writes its own query rows (t depends on warp), so warps overwrite one another's values before the inverse WHT. The final orow writes then store another warp's output into this warp's rows. This corrupts prefill output whenever more than one warp handles a head with turbo V enabled.
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
pub fn new(device: usize) -> anyhow::Result<Vk> {
ensure!(crate::cuda::kv_mode() <= 3, "--kv turbo* needs the CUDA backend");
ensure!(!(crate::cuda::kv_mode() > 0 && crate::cuda::llama_numerics()), "--kv q8/q4 does not combine with --llama-numerics (its attention reads f16 KV)");
// RADV hides VK_AMD_device_coherent_memory on RDNA4 (RX 9000) unless this driconf option is set, and without

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

Vulkan rejects every mixed K/V layout with a misleading 'turbo needs CUDA' error. kv_mode() returns 10 for any mixed layout, so --k f16 --v q4 on Vulkan fails the <= 3 check and reports '--kv turbo* needs the CUDA backend'. The text does not match the real cause, which is the unsupported mixed layout, and it misleads users who never asked for turbo.

Prompt for your AI agent
File: src/vulkan/mod.rs
Line: 368
Symbol: new
Issue: Vulkan rejects every mixed K/V layout with a misleading 'turbo needs CUDA' error. kv_mode() returns 10 for any mixed layout, so `--k f16 --v q4` on Vulkan fails the `<= 3` check and reports '--kv turbo* needs the CUDA backend'. The text does not match the real cause, which is the unsupported mixed layout, and it misleads users who never asked for turbo.
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.

@sayampy

sayampy commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

@Vasyl-Trefilov Hi Can you please test a full benchmark with other models on this PR? And let me know if You face any issue or gibberish output.

@Vasyl-Trefilov

Copy link
Copy Markdown
Member

yes, but tomorrow, it's already very late, so I am going to sleep, bc benchmarks take a lot of time and I need to leave my PC training my own AI

@Vasyl-Trefilov

Copy link
Copy Markdown
Member

I read the new push, but I did not run the benchmark yet, bc I found things in the code that must be fixed first. The Vulkan panic is fixed, ty.

The biggest one is new: in attn_merge the int8 copy (xq) is now made before the gate, on main it is made after. So default f16 decode of the Qwen models with q_gate (qwen35, qwen35moe, qwen3next, qwen4exp) gets wrong input in the output projection.

Still open from last time: ink_attn_prefill_t uses 4 x lane + j in every mode, so f16/q8/q4 prefill of Inkling 2 is not the same as main, and heads of 64 or 32 read outside the head.

In attn_prefill_t with V turbo the shared tro buffer has no index for the query row, so threads with different rows write the same cells.

In the Inkling 2 grow path (device.rs) K and V are each allocated with kv_row_words, which is K + V together, so default f16 takes twice the KV memory after the context grows.

In ds_env --k and --v are dropped when --kv is the default f16, so your mixed rows for Inkling 2 could be plain f16.

And there is still no test and no quality number (turbo4 against q4, top-1 agreement with f16). Please also remove the RTX 3050 table from docs/USAGE.md, the numbers there come from my machine.

My suggestion: make this PR smaller. Only turbo4 for K and V together on Inkling 2 with head 128, f16/q8/q4/q2 bit-identical to main, one test like tests/kv_q8.rs and the quality number. General engine and mixed modes in a second PR after that. Now it is too much in one PR and hard to check.

@sayampy

sayampy commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

@Vasyl-Trefilov The main benefits of turboquant are asymmetric KV. So I made the whole implementation in one PR, I am trying to break it in small PR, but implementation of turboquant is the main big code, otherwise the --k and --v split and asymmetric quant PR will be small change. I will try to fix the issues, I missed those since I did not run long context benchmarks.

Also sorry for the repeated docs/ changing, I write my machine's bench in my fork, and forgot to remove them before submitting PRs. Anyways, Ty for correcting me.

@Vasyl-Trefilov

Copy link
Copy Markdown
Member

No problem, ty for the fast answer, and take your time. The most important for me: the old modes (f16/q8/q4/q2) stay bit-identical to main, one test, and the quality number, bc that shows if asymmetric really wins against q4 at the same size. How you split it is up to you, smaller is just easier for me to check.

Comment thread src/cuda/kernels.cu
int base = g * 128 + 4 * t;
if (t < 32) {
float4 v = make_float4(qs[base], qs[base+1], qs[base+2], qs[base+3]);
tq_wht4(v, t, false);

@aletheore aletheore Bot Nov 24, 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 eabab8c58931.


🟠 High · Correctness · 1 of 5

ink_clip stores turbo cache rows unrotated and unnormalized whenever w != 128 ink_clip only calls ink_tq_store when w == 128. For any other width (for example 256 or 64) it calls kv_store_one with norm 1.0, so kv_put_tq quantizes raw, unrotated values. Meanwhile ink_attn rotates Q for hd == 64 and for every multiple of 128. Scores then mix rotated Q with unrotated K, giving wrong attention for Inkling 2 layers with those head sizes.

Prompt for your AI agent
File: src/cuda/kernels.cu
Line: 3050
Issue: ink_clip stores turbo cache rows unrotated and unnormalized whenever w != 128 ink_clip only calls ink_tq_store when w == 128. For any other width (for example 256 or 64) it calls kv_store_one with norm 1.0, so kv_put_tq quantizes raw, unrotated values. Meanwhile ink_attn rotates Q for hd == 64 and for every multiple of 128. Scores then mix rotated Q with unrotated K, giving wrong attention for Inkling 2 layers with those head sizes.
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
"turbo3" => 5,
"turbo2" => 6,
_ => 0,
}

@aletheore aletheore Bot Nov 24, 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 eabab8c58931.


🟠 High · Correctness · 2 of 5

kv_mode() now returns 10 for mixed K/V, which Vulkan may not handle Vk::new reads the legacy kv_mode(), which now returns 10 when K and V differ (for example --k f16 --v q4). The Vulkan backend only supports symmetric legacy formats, and nothing in this diff rejects a mixed layout there, so the value falls into an unhandled case or is silently treated as one format for both halves.

Prompt for your AI agent
File: src/cuda/mod.rs
Line: 105
Issue: kv_mode() now returns 10 for mixed K/V, which Vulkan may not handle Vk::new reads the legacy kv_mode(), which now returns 10 when K and V differ (for example --k f16 --v q4). The Vulkan backend only supports symmetric legacy formats, and nothing in this diff rejects a mixed layout there, so the value falls into an unhandled case or is silently treated as one format for both halves.
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 last = pos0 + min(q0 + FA_BQ, T) - 1; // last key any query of the tile sees
int qp[2] = {pos0 + q0 + warp * 16 + g, pos0 + q0 + warp * 16 + g + 8};
float o[HD / 8][4] = {}, m[2] = {-INFINITY, -INFINITY}, l[2] = {0.0f, 0.0f};
#if V_MODE >= 4

@aletheore aletheore Bot Nov 24, 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 eabab8c58931.


🔵 Low · Performance

Turbo prefill V rotation serializes 128+ barrier-separated steps per tile The epilogue loops over wi, gi, gg and r, running a staging write, a barrier, one warp WHT, and another barrier for each step. That is over 250 __syncthreads per query tile per head, so turbo V prefill is much slower than the legacy path.

Prompt for your AI agent
File: src/cuda/kernels.cu
Line: 3800
Issue: Turbo prefill V rotation serializes 128+ barrier-separated steps per tile The epilogue loops over wi, gi, gg and r, running a staging write, a barrier, one warp WHT, and another barrier for each step. That is over 250 __syncthreads per query tile per head, so turbo V prefill is much slower than the legacy 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/cuda/kernels.cu
return v;
}
// One value into the cache at value offset e. M is this half's cache mode; BITS matters only for turbo modes.
template <int M, int BITS = TQ_KBITS>

@aletheore aletheore Bot Nov 24, 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 eabab8c58931.


🔵 Low · Performance

Each turbo store runs a full 128-thread reduction to get the reconstruction norm kv_put_tq calls tq_group_sum for every value, which runs warp shuffles and two __syncthreads each time, to compute recon. This is repeated for each cache element in kv_store_turbo and in rms_norm_rope, which adds heavy barrier overhead to every decode token.

Prompt for your AI agent
File: src/cuda/kernels.cu
Line: 2640
Issue: Each turbo store runs a full 128-thread reduction to get the reconstruction norm kv_put_tq calls tq_group_sum for every value, which runs warp shuffles and two __syncthreads each time, to compute recon. This is repeated for each cache element in kv_store_turbo and in rms_norm_rope, which adds heavy barrier overhead to every decode token.
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
}
__syncthreads();
kv_put_tq<BITS>(dst, dat, w, tq[t], norm);
}

@aletheore aletheore Bot Nov 24, 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 eabab8c58931.


🔵 Low · Maintainability

Inverse-WHT and Q-rotation blocks are copied into five kernels The same if constexpr rotate-Q and inverse-rotate-output blocks appear in ink_attn, attn_decode_t, attn_prefill_t, attn_merge and the prefill epilogue, with small differences. A fix to one copy, such as the hd == 64 path, is easily missed in the others.

Prompt for your AI agent
File: src/cuda/kernels.cu
Line: 2990
Issue: Inverse-WHT and Q-rotation blocks are copied into five kernels The same if constexpr rotate-Q and inverse-rotate-output blocks appear in ink_attn, attn_decode_t, attn_prefill_t, attn_merge and the prefill epilogue, with small differences. A fix to one copy, such as the hd == 64 path, is easily missed in the others.
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.

@sayampy
sayampy marked this pull request as draft November 24, 2026 20:17
@sayampy
sayampy marked this pull request as ready for review November 25, 2026 16:43
sayampy and others added 5 commits November 26, 2026 00:57
Store K/V as signed-Walsh-rotated 4-bit Lloyd-Max blocks, rotate Q in attention, and inverse-rotate only the attention output. Includes a tested Rust core (WHT, centroids, QJL), NVRTC kernels, corrected prefill element<->sign mapping, and docs. Measured on RTX 3050 Laptop / Inkling 2 Mini Q3_K_XL: KV ~28% of f16 size, pp128 44.8 vs 43.8 tok/s, tg32 8.5 vs 8.2 tok/s; greedy coding/math/prose checks sensible (math 391).

Co-authored-by: Hy4-Flash <hy4-flash@local>
Co-authored-by: Hy4-Flash <hy4-flash@local>
- Split the KV cache mode into independent K_MODE/V_MODE: --k and --v accept
  any pair from K={f16,q8,q4,turbo4,turbo3} and V={f16,q8,q4,q2,turbo4,turbo3,turbo2}.
- Publish STRATA_KV_K/STRATA_KV_V; expand --kv turbo4-3/turbo4-2/turbo3-2 aliases
  for both runs and calibrate.
- Allocate K and V cache halves with their own word width; add kv_words_v to
  the Backend trait and update the general engine and Inkling 2 device paths.
- Template KV store/load helpers on the per-side mode and gate Q rotation on
  K_MODE, output de-rotation on V_MODE; fix mixed-mode prefill/cp.async paths.
- Fix the fused rms_norm_rope store writing f16 into a compressed cache.
- Generalize TurboQuant to hd=256 with two grouped WHT-128 blocks per head,
  per-group norms and centroids; relax the hd guard to hd%128==0.
- Fix inverse-WHT output overwrite in ink_attn that degraded symmetric turbo.
- Add docs for the flags and RTX 3050 benchmark matrix.
…V barriers

- ink_clip now rotates and normalizes TurboQuant rows at every supported
  width: WHT-128 for 128 and up, WHT-64 at head_dim 64, and no rotation
  below 64 where attention leaves Q unrotated too. Inactive lanes past the
  width still join the block reduction but write no cache bytes.
- Inkling prefill uses the 64-wide lane mapping for TurboQuant K/V at
  head_dim 64, matching the clip store and the decode kernel.
- Vulkan rejects mixed K/V layouts with kv_legacy_symmetric before its
  legacy-only size helpers instead of falling through with mode 10.
- Turbo V prefill rotates all four warps' query rows concurrently, cutting
  barriers per tile from 192 to 17 (384 to 34 at head_dim 256).
- Add a head_dim 64 Inkling prefill-versus-decode test and a CPU-only test
  for the Vulkan mode guard.

Co-authored-by: Hy4-Flash <hy4-flash@local>
Comment thread src/cuda/kernels.cu
}
__syncthreads();
{
int chunks = n <= 256 ? 1 : n / 256;

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 9

rms_norm_rope chunk loop has no bound check for n < 256, so threads write past the head For n = 64 (or any n below 256 other than 128), chunks is 1 and j = threadIdx.x runs to 255 with no j < n guard. The kernel reads uninitialised tqk/tqv entries and calls kv_store_one at e + j for j up to 255, overwriting the next head's or next position's cache rows. The old loop had a j < n guard, and this change drops it.

Prompt for your AI agent
File: src/cuda/kernels.cu
Line: 2872
Issue: rms_norm_rope chunk loop has no bound check for n < 256, so threads write past the head For n = 64 (or any n below 256 other than 128), chunks is 1 and j = threadIdx.x runs to 255 with no j < n guard. The kernel reads uninitialised tqk/tqv entries and calls kv_store_one at e + j for j up to 255, overwriting the next head's or next position's cache rows. The old loop had a j < n guard, and this change drops it.
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
}
__syncthreads();
{
int chunks = n <= 256 ? 1 : n / 256;

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 9

chunk count truncates n/256, so n = 384 and similar widths drop values For n = 384, chunks = n / 256 = 1, so elements 256..383 are never quantised or stored. Their cache slots keep stale data, and attention reads garbage for those dimensions. The count should be ceil(n / 256), with a guard on j.

Prompt for your AI agent
File: src/cuda/kernels.cu
Line: 2872
Issue: chunk count truncates n/256, so n = 384 and similar widths drop values For n = 384, chunks = n / 256 = 1, so elements 256..383 are never quantised or stored. Their cache slots keep stale data, and attention reads garbage for those dimensions. The count should be ceil(n / 256), with a guard on j.
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
}

// Store `total` values (consecutive tokens of n each, n a multiple of 32) starting at position step[0].
extern "C" __global__ void kv_store(const float* k, const float* v, u16* kc, u16* vc, int n, int total, const int* step,

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 9

kv_store passes unnormalised, unrotated values into turbo modes With K_MODE or V_MODE >= 4, kv_store calls kv_store_one with norm = 1.0 and no WHT. Values are quantised without unit-L2 normalisation or rotation, so they clip to the outer centroids and decode wrong. Also kv_put_tq calls tq_group_sum, which runs __syncthreads inside the if (i < total) guard. A partial last block then deadlocks. The turbo path should be routed through kv_store_turbo.

Prompt for your AI agent
File: src/cuda/kernels.cu
Line: 2763
Issue: kv_store passes unnormalised, unrotated values into turbo modes With K_MODE or V_MODE >= 4, kv_store calls kv_store_one with norm = 1.0 and no WHT. Values are quantised without unit-L2 normalisation or rotation, so they clip to the outer centroids and decode wrong. Also kv_put_tq calls tq_group_sum, which runs __syncthreads inside the `if (i < total)` guard. A partial last block then deadlocks. The turbo path should be routed through kv_store_turbo.
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
#if K_MODE >= 4 || V_MODE >= 4
__shared__ float kq[128], vq[128];
int t = threadIdx.x;
size_t e = (size_t)blockIdx.x * 128 + t;

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 9

kv_store_turbo reads k[e] and v[e] with no e < total guard The kernel indexes k[e] and v[e] at blockIdx.x * 128 + t without checking against total. If the launch grid is rounded up, or total is not a multiple of 128, it reads and writes past the buffers. The older kv_store kernel had an i < total guard.

Prompt for your AI agent
File: src/cuda/kernels.cu
Line: 2780
Issue: kv_store_turbo reads k[e] and v[e] with no e < total guard The kernel indexes k[e] and v[e] at blockIdx.x * 128 + t without checking against total. If the launch grid is rounded up, or total is not a multiple of 128, it reads and writes past the buffers. The older kv_store kernel had an i < total guard.
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/backend.rs
/// u16 words of a KV cache row for `n` values in the K format (and, separately, the V format).
/// `kv_row_words` is the size of one K row plus one V row.
fn kv_words(&self, n: usize) -> usize;
fn kv_words_v(&self, n: usize) -> usize { self.kv_words(n) }

@aletheore aletheore Bot Nov 25, 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 d53b9fde9b6e.


🟡 Medium · Correctness · 6 of 9

default kv_words_v silently reuses the K width for the V half A backend that does not override kv_words_v (Vulkan, which only supports symmetric formats) gets the K word width for V. A layout such as --k f16 --v q4 then allocates V with the wrong size and indexing, with no error. The default should fail or the mixed layout should be rejected.

Prompt for your AI agent
File: src/backend.rs
Line: 207
Symbol: kv_words_v
Issue: default kv_words_v silently reuses the K width for the V half A backend that does not override kv_words_v (Vulkan, which only supports symmetric formats) gets the K word width for V. A layout such as --k f16 --v q4 then allocates V with the wrong size and indexing, with no error. The default should fail or the mixed layout should be rejected.
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
for (int j = threadIdx.x; j < n; j += 256) { tqk[j] = o[j]; tqv[j] = vr[j]; }
__syncthreads();
if (threadIdx.x < 32) {
for (int gi = 0; gi < n / 128; gi++) {

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 · 7 of 9

hd = 64 general path skips the WHT, while ink_attn still rotates Q at hd = 64 In rms_norm_rope with n = 64, the loop over n / 128 groups does zero iterations, so K and V are stored unrotated. The general attention path rotates Q with WHT-128 only, and ink_attn rotates Q with WHT-64. Scores then mix rotated Q with unrotated K, so attention for head_dim 64 is wrong. Rotation should be consistent for every head width.

Prompt for your AI agent
File: src/cuda/kernels.cu
Line: 2856
Issue: hd = 64 general path skips the WHT, while ink_attn still rotates Q at hd = 64 In rms_norm_rope with n = 64, the loop over n / 128 groups does zero iterations, so K and V are stored unrotated. The general attention path rotates Q with WHT-128 only, and ink_attn rotates Q with WHT-64. Scores then mix rotated Q with unrotated K, so attention for head_dim 64 is wrong. Rotation should be consistent for every head width.
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
auto deq = [&](unsigned x, unsigned sel) {
unsigned h = __byte_perm(x ^ 0x80808080u, 0x64646464u, sel), r;
template <int M, int PER, int BITS = TQ_KBITS> __device__ __forceinline__ void ldkv(const u16* c, size_t off, int hd, unsigned* o) {
if constexpr (M >= 4) {

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 · Correctness · 8 of 9

ldkv defaults BITS to the K bit width for every caller, including V ldkv<M, PER> with the default BITS = TQ_KBITS is used for V reads. If TQ_VBITS differs from TQ_KBITS (for example K at 4 bits and V at 3 bits), V is dequantised with the wrong centroid table and the output is silently wrong. Callers should pass the bit width of the half they read, as ldkv1 does.

Prompt for your AI agent
File: src/cuda/kernels.cu
Line: 2910
Issue: ldkv defaults BITS to the K bit width for every caller, including V ldkv<M, PER> with the default BITS = TQ_KBITS is used for V reads. If TQ_VBITS differs from TQ_KBITS (for example K at 4 bits and V at 3 bits), V is dequantised with the wrong centroid table and the output is silently wrong. Callers should pass the bit width of the half they read, as ldkv1 does.
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
tq[t] = v;
__syncthreads();
if (t < 32) {
if (w == 64) { // one WHT-64 block: two dims per lane

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 · 9 of 9

ink_tq_store indexes a 128-entry shared array by full thread id ink_tq_store writes tq[t] for every thread, but tq holds only 128 floats. If ink_clip is launched with more than 128 threads per block (for example for a wide w), threads 128 and up write past the shared array. Guard the write with t < 128 or size the array to blockDim.

Prompt for your AI agent
File: src/cuda/kernels.cu
Line: 3050
Issue: ink_tq_store indexes a 128-entry shared array by full thread id ink_tq_store writes tq[t] for every thread, but tq holds only 128 floats. If ink_clip is launched with more than 128 threads per block (for example for a wide w), threads 128 and up write past the shared array. Guard the write with t < 128 or size the array to blockDim.
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
launch!(self, "kv_store", Self::grid(n * t), k, v, kc, vc, n as i32, (n * t) as i32, step, hd as i32);
anyhow::ensure!((self.kv_k_mode == 0 && self.kv_v_mode == 0) || (hd % 32 == 0 && n % hd == 0), "quantized KV cache: head_dim {hd} is not a multiple of 32");
if self.kv_k_mode >= 4 || self.kv_v_mode >= 4 {
anyhow::ensure!(hd % 128 == 0, "TurboQuant KV needs head_dim divisible by 128, got {hd}");

@aletheore aletheore Bot Nov 25, 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 d53b9fde9b6e.


🟡 Medium · Correctness

kv_store routes both halves through kv_store_turbo when either side is TurboQuant. With STRATA_KV_K=turbo4 and STRATA_KV_V=q8 (or f16), kv_k_mode is 4 so the turbo store kernel runs for the whole K/V pair. If that kernel writes the TurboQuant layout to both buffers, the V cache gets turbo-encoded data while attention reads it as q8 or f16, so decode outputs are garbage. The mixed layout is explicitly supported (kv_mode() returns 10 for it), so this is reachable.

Prompt for your AI agent
File: src/cuda/mod.rs
Line: 1368
Symbol: kv_store
Issue: kv_store routes both halves through kv_store_turbo when either side is TurboQuant. With STRATA_KV_K=turbo4 and STRATA_KV_V=q8 (or f16), kv_k_mode is 4 so the turbo store kernel runs for the whole K/V pair. If that kernel writes the TurboQuant layout to both buffers, the V cache gets turbo-encoded data while attention reads it as q8 or f16, so decode outputs are garbage. The mixed layout is explicitly supported (kv_mode() returns 10 for it), so this is reachable.
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.

Add independent K and V cache modes to the Vulkan backend via specialization constants 15 and 16. Legacy f16/q8/q4/q2 and TurboQuant 4/3/2 can be combined in either half. Port the WHT rotation, Lloyd-Max store/load and output inverse rotation to the Vulkan attention, store and Inkling 2 shaders, regenerate SPIR-V, and add Vulkan split-KV and hd64 TurboQuant tests.
Comment thread src/cuda/mod.rs
let g = nh / nkv.max(1);
if win == 0 && nkv > 0 && nh % nkv == 0 && g <= 4 {
// The shared-memory variant reads a legacy f16 layout and has no WHT; TurboQuant uses the grouped kernel.
if kv_mode() == 0 && win == 0 && nkv > 0 && nh % nkv == 0 && g <= 4 {

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 7

Attention reads kv_mode() from the environment on every launch instead of the compiled modes. kv_mode() calls env::var on each attention launch. If STRATA_KV changes after Gpu::new, the shared-memory variant is chosen from the new env while kernels were compiled for the old modes, so the wrong KV layout is read. Each call also adds env lookups per layer per token. Use self.kv_k_mode and self.kv_v_mode.

Prompt for your AI agent
File: src/cuda/mod.rs
Line: 1246
Symbol: ink_attn_prefill
Issue: Attention reads kv_mode() from the environment on every launch instead of the compiled modes. kv_mode() calls env::var on each attention launch. If STRATA_KV changes after Gpu::new, the shared-memory variant is chosen from the new env while kernels were compiled for the old modes, so the wrong KV layout is read. Each call also adds env lookups per layer per token. Use self.kv_k_mode and self.kv_v_mode.
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
if (thr > 0.f) {
#if K_MODE >= 4
ink_tq_store<TQ_KBITS>(dst, dat, t, w, v, tq, sqrtf(ss) * f, active);
#else

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 7

ink_clip picks the K or V quantizer from the sign of thr, an implicit and fragile contract. ink_clip_v forwards the caller's thr unchanged to the same kernel. A caller that passes thr > 0 for the V cache writes K-format (and, with TurboQuant, K-mode WHT) data into V, and the mismatch is silent. Pass an explicit is_v flag.

Prompt for your AI agent
File: src/cuda/kernels.cu
Line: 3152
Issue: ink_clip picks the K or V quantizer from the sign of thr, an implicit and fragile contract. ink_clip_v forwards the caller's thr unchanged to the same kernel. A caller that passes thr > 0 for the V cache writes K-format (and, with TurboQuant, K-mode WHT) data into V, and the mismatch is silent. Pass an explicit is_v flag.
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
launch!(self, "kv_store", Self::grid(n * t), k, v, kc, vc, n as i32, (n * t) as i32, step, hd as i32);
anyhow::ensure!((self.kv_k_mode == 0 && self.kv_v_mode == 0) || (hd % 32 == 0 && n % hd == 0), "quantized KV cache: head_dim {hd} is not a multiple of 32");
if self.kv_k_mode >= 4 || self.kv_v_mode >= 4 {
anyhow::ensure!(hd % 128 == 0, "TurboQuant KV needs head_dim divisible by 128, got {hd}");

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 7

Turbo KV rejects head_dim 64, contradicting the description's WHT-64 claim. The description says head_dim 64 uses one WHT-64 group, but kv_store fails for any hd not divisible by 128. A 64-dim model with --kv turbo4 errors at the first store. attn_merge and attn_decode_t also only handle 128-wide groups, so the 64-dim case needs the WHT-64 path added there too.

Prompt for your AI agent
File: src/cuda/mod.rs
Line: 1393
Symbol: kv_store
Issue: Turbo KV rejects head_dim 64, contradicting the description's WHT-64 claim. The description says head_dim 64 uses one WHT-64 group, but kv_store fails for any hd not divisible by 128. A 64-dim model with --kv turbo4 errors at the first store. attn_merge and attn_decode_t also only handle 128-wide groups, so the 64-dim case needs the WHT-64 path added there too.
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 TURBOQUANT.md
@@ -0,0 +1,165 @@
# TurboQuant work log — RustingStrata

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

Internal work log with local paths and unverified GPU claims is committed to the repo. The file exposes /home/sayam paths and a personal branch history. It says GPU output is garbage and mixed K/V pairs are not implemented, but USAGE.md and the code now support them. Its test counts (371/325) conflict with the code (399/330). Shipping it misleads reviewers and users.

Prompt for your AI agent
File: TURBOQUANT.md
Line: 1
Issue: Internal work log with local paths and unverified GPU claims is committed to the repo. The file exposes /home/sayam paths and a personal branch history. It says GPU output is garbage and mixed K/V pairs are not implemented, but USAGE.md and the code now support them. Its test counts (371/325) conflict with the code (399/330). Shipping it misleads reviewers and users.
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
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;

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

Turbo dequant indexes constant centroid arrays with per-lane data, serializing reads. tq_centroid<BITS>(q) indexes TQ_C4 with a per-thread nibble. Divergent constant-memory addresses are serialized across the warp, and this runs for every K/V element in every decode step. A shared-memory table or a register formula avoids the serialization.

Prompt for your AI agent
File: src/cuda/kernels.cu
Line: 2979
Issue: Turbo dequant indexes __constant__ centroid arrays with per-lane data, serializing reads. tq_centroid<BITS>(q) indexes TQ_C4 with a per-thread nibble. Divergent constant-memory addresses are serialized across the warp, and this runs for every K/V element in every decode step. A shared-memory table or a register formula avoids the serialization.
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
constexpr int R = (HD + 127) / 128;
#if V_MODE >= 4
// query half x warp x 128 dims: one WHT group per warp, reused across its eight rows.
__shared__ float tro[2][4][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.

🔵 Low · Performance

attn_prefill_llama declares a tro staging buffer it never uses. The new shared float tro[2][4][128] (4 KB) is added to attn_prefill_llama, but this diff adds no code that reads or writes it. The unused static shared memory lowers occupancy for the prefill kernel. Remove it.

Prompt for your AI agent
File: src/cuda/kernels.cu
Line: 4464
Issue: attn_prefill_llama declares a tro staging buffer it never uses. The new __shared__ float tro[2][4][128] (4 KB) is added to attn_prefill_llama, but this diff adds no code that reads or writes it. The unused static shared memory lowers occupancy for the prefill kernel. Remove it.
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
/// Backends without per-side K/V formats only handle a symmetric legacy layout. `kv_mode()` reports 10 for a
/// mixed layout, which would otherwise pass a `<= 3` guard and reach an `unreachable!` in the size helpers.
pub fn kv_legacy_symmetric(k: u32, v: u32) -> bool { k == v && k <= 3 }

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

kv_legacy_symmetric guard is dead code after the unreachable! path was removed. The doc comment says the guard protects an unreachable! in size helpers, but this diff removes that unreachable! and adds no caller of kv_legacy_symmetric. It only has a unit test. Either wire it into the backend that needs it or delete it.

Prompt for your AI agent
File: src/cuda/mod.rs
Line: 153
Issue: kv_legacy_symmetric guard is dead code after the unreachable! path was removed. The doc comment says the guard protects an unreachable! in size helpers, but this diff removes that unreachable! and adds no caller of kv_legacy_symmetric. It only has a unit test. Either wire it into the backend that needs it or delete it.
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.

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