Skip to content

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

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

sayampy wants to merge 4 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.

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 and a head_dim divisible by 128. Quantized KV does not combine with --llama-numerics. Vulkan still only supports symmetric legacy formats.

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.

Correctness

Legacy modes stay bit-identical to main. tests/kv_turbo.rs pins 16 FNV-1a hashes of K cache bytes, V cache 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 4b3f44b, 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.

Quality

Numbers below are from an RTX 3050 Laptop with greedy decoding and --mtp 0. Perplexity comes from perplexity, top-1 and KLD come from --kld-base dumps compared with f16. 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 7.2539 80 MB
q4 7.1973 22 MB 348/381 = 91.34% 0.1986
turbo4 7.2151 22 MB 349/381 = 91.60% 0.1856

turbo4 is slightly ahead of q4 on top-1 and KLD at the same cache size. PPL is within 0.02 of q4, and Tiel's MoE expert cache swaps vary a little between runs, so that difference is not meaningful. On Inkling 2 Mini with a stable arithmetic prompt, all 18 symmetric and mixed configurations produced the same correct output.

Speed

This bench used Inkling 2 Mini UD-Q3_K_XL, --pp 128 --tg 32 --reps 3 --ctx 4096 --chunk 128 --mtp 0 --temp 0, mean of three runs in tokens/s. It was measured before the last review fixes, which changed layout and ordering rather than instruction count, so treat it as indicative.

KV prefill decode KV prefill decode
f16 27.4 6.1 turbo4 35.0 7.9
q8 30.2 7.7 turbo4-3 37.4 8.4
q4 32.8 7.1 turbo3 42.9 8.6
q2 32.6 7.9 turbo2 35.6 8.2
K=f16 V=q4 37.1 7.5 K=q8 V=q4 31.6 6.3
K=turbo4 V=f16 37.3 8.0 K=f16 V=turbo4 41.6 8.4
K=turbo4 V=q4 38.6 8.1 K=q4 V=turbo4 40.9 8.2
K=turbo3 V=turbo2 43.9 8.0

Tests

cargo test --release is green on the rebased branch. That covers 106 library tests, 25 binary tests, kv_q8 4/4, kernels 27/27 including NVRTC compiles for sm70 and sm75, and kv_turbo 1/1. Twelve mixed-mode combinations also compile as cubins under standalone sm75 checks.

Co-author

Hy4-Flash hy4-flash@local

@aletheore

aletheore Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

🔍 Aletheore evidence diff

graph LR
    n0["src/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["model.rs"]
    n23["ngram.rs"]
    n24["serve.rs"]
    n25["preflight.rs"]
    n26["weights.rs"]
    n27["tests/backend.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 --> n22
    n0 --> n27
    n0 --> n28
    n0 --> n29
    n0 --> n30
    n0 --> n31
    n0 --> n32
    n1 --> n15
    n1 --> n25
    n1 --> n28
    n1 --> n29
    n1 --> n31
    n1 --> n32
    n2 --> n14
    n2 --> n22
    n2 --> n27
    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
    n5 --> n25
    n5 --> 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.

  • docs/USAGE.md · modified · +8/-0
  • src/backend.rs · modified · +4/-1 · +2 functions · 14 other dependents
  • src/cuda/kernels.cu · modified · +551/-147
  • src/cuda/mod.rs · modified · +92/-41 · +5 functions · 6 other dependents
  • src/gpu_model.rs · modified · +4/-4 · 4 other dependents
  • src/inkling2/forward/device.rs · modified · +15/-14 · 1 other dependent
  • src/kv_turbo.rs · +248/-0 · new file, 19 symbols
  • src/lib.rs · modified · +1/-0 · 17 other dependents
  • src/main.rs · modified · +100/-23 · +7 functions
  • src/vulkan/mod.rs · modified · +1/-0 · 7 other dependents
  • tests/kv_turbo.rs · +134/-0 · new file, 8 symbols

Aggregate deltas

  • Modules: +2
  • Dependency graph edges: +4
  • Commits: 4

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 pull request adds TurboQuant KV cache compression on CUDA with separately configurable K and V formats (--k, --v), and a HIP/ROCm GPU backend selected with --backend hip that runs on a single device. It also changes the server: /v1/models lists and switches models, streamed replies send keep-alives, and max_tokens becomes optional. Users of the inference engine are affected, including people running CUDA or AMD GPUs, people choosing KV cache formats, and API clients of the server.

Merge confidence Review effort Merge risk
2 / 5 5 / 5 Medium
Area Files Lines
src 5 +476 −71
src/cuda 2 +1046 −205
docs 1 +25 −1
src/inkling2 1 +51 −14
src/vulkan 1 +2 −1
tests 1 +134 −0

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

# Severity Category Where
1 🟠 High Correctness kernels.cu:3050 ink_clip stores turbo cache rows unrotated and unnormalized whenever w != 128 ink_clip only calls…
2 🟠 High Correctness mod.rs:105 kv_mode() now returns 10 for mixed K/V, which Vulkan may not handle Vk::new reads the legacy kv_mode(), which…
7 🔵 Low Performance kernels.cu:3800 Turbo prefill V rotation serializes 128+ barrier-separated steps per tile The epilogue loops over wi, gi, gg…
8 🔵 Low Performance kernels.cu:2640 Each turbo store runs a full 128-thread reduction to get the reconstruction norm kv_put_tq calls tq_group_sum…
10 🔵 Low Maintainability kernels.cu:2990 Inverse-WHT and Q-rotation blocks are copied into five kernels The same if constexpr rotate-Q and…
- 🟠 High Correctness main.rs:389 Earlier finding, still open
- 🟠 High Correctness kernels.cu:2745 Earlier finding, still open
- 🟡 Medium Correctness kernels.cu:3807 Earlier finding, still open
- 🟡 Medium Correctness mod.rs:368 Earlier finding, still open
Review details

Reviewed 9 file(s); skipped 2. Dismissed 0; outside PR diff 5. Grounding: 16 of 19 proposed finding(s).

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

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.

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.

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.

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.

Note: 2 of 11 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/main.rs, src/cuda/kernels.cu.

Blast radius: 49 other file(s) depend on what this PR changes (28 directly, 21 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 (+13 more)
  • src/backend.rs is imported by src/cpu_worker.rs, src/deepseek/mat.rs, src/expert_cache.rs, src/gpu_model/prefill.rs (+10 more)
  • src/vulkan/mod.rs is imported by src/vulkan/preflight.rs, tests/backend.rs, tests/common/mod.rs, tests/gpu_model.rs (+3 more)
  • src/cuda/mod.rs is imported by src/hip/mod.rs, src/vulkan/preflight.rs, tests/common/mod.rs, tests/gpu_model.rs (+2 more)
  • src/gpu_model.rs is imported by src/gpu_model/prefill.rs, src/model.rs, tests/backend.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 (+15 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
else
#endif
kv_store_one<V_MODE, TQ_VBITS>(dst, dat, w, v, 1.0f);
}

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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Correctness · 5 of 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.

sayampy and others added 4 commits November 25, 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.
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);

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

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

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

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

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

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>

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

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

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

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