Repository navigation
CUDA TurboQuant KV cache: WHT + Lloyd-Max, general engine, asymmetric K/V - #84
Conversation
🔍 Aletheore evidence diffgraph 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
What changed
Aggregate deltas
|
| kv_put_tq(dst, dat, w, tq[t], sqrtf(ss) * f); | ||
| } else | ||
| #endif | ||
| kv_put(dst, dat, w, v); |
There was a problem hiding this comment.
✅ 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.
| __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); |
There was a problem hiding this comment.
✅ 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.
| 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; |
There was a problem hiding this comment.
✅ 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.
| 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; } |
There was a problem hiding this comment.
✅ 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.
| let mut next = || { | ||
| state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); | ||
| ((state >> 11) as f32 / (1u64 << 53) as f32) * 2.0 - 1.0 | ||
| }; |
There was a problem hiding this comment.
✅ 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.
| #[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]. |
There was a problem hiding this comment.
✅ 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.
| size_t dat = (dst_pos * rows + row) * w + t; | ||
| #if KV_MODE == 4 | ||
| if (w == 128) { | ||
| tq[t] = v; |
There was a problem hiding this comment.
✅ 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 Flash Lite reviewWhat this PR does. This PR adds CUDA TurboQuant KV-cache modes (Walsh-Hadamard rotation with Lloyd-Max quantization) to RustingStrata's general engine, plus
7 finding(s) posted as inline review comment(s). 9 earlier finding(s) from previous pushes still open.
Review detailsReviewed 29 file(s); skipped 68. Dismissed 0; outside PR diff 3. Grounding: 20 of 26 proposed finding(s). Fix all with your agentNote: 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: 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.
Indirectly affected: The graph is large; this list is capped and not exhaustive. |
|
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:
Smaller things:
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 |
| 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(",")) } } |
There was a problem hiding this comment.
🟠 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.
| else | ||
| #endif | ||
| kv_store_one<V_MODE, TQ_VBITS>(dst, dat, w, v, 1.0f); | ||
| } |
There was a problem hiding this comment.
✅ 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.
| 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), |
There was a problem hiding this comment.
✅ 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.
| int col = d * 8 + 2 * t4 + e; | ||
| #if V_MODE >= 4 | ||
| tro[r][col] = o[d][2 * r + e] * inv; | ||
| #else |
There was a problem hiding this comment.
✅ 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.
| 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 |
There was a problem hiding this comment.
🟡 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.
|
@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. |
|
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 |
|
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. |
|
@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. |
|
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. |
c25f1fa to
9cbd332
Compare
| 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); |
There was a problem hiding this comment.
✅ 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.
| "turbo3" => 5, | ||
| "turbo2" => 6, | ||
| _ => 0, | ||
| } |
There was a problem hiding this comment.
✅ 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.
| 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 |
There was a problem hiding this comment.
✅ 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.
| 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> |
There was a problem hiding this comment.
✅ 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.
| } | ||
| __syncthreads(); | ||
| kv_put_tq<BITS>(dst, dat, w, tq[t], norm); | ||
| } |
There was a problem hiding this comment.
✅ 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.
9cbd332 to
5eb58d8
Compare
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.
…env) and add regression test
…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>
| } | ||
| __syncthreads(); | ||
| { | ||
| int chunks = n <= 256 ? 1 : n / 256; |
There was a problem hiding this comment.
🟠 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.
| } | ||
| __syncthreads(); | ||
| { | ||
| int chunks = n <= 256 ? 1 : n / 256; |
There was a problem hiding this comment.
🟠 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.
| } | ||
|
|
||
| // 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, |
There was a problem hiding this comment.
🟠 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.
| #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; |
There was a problem hiding this comment.
🟡 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.
| /// 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) } |
There was a problem hiding this comment.
✅ 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.
| 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++) { |
There was a problem hiding this comment.
🟡 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.
| 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) { |
There was a problem hiding this comment.
🔵 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.
| tq[t] = v; | ||
| __syncthreads(); | ||
| if (t < 32) { | ||
| if (w == 64) { // one WHT-64 block: two dims per lane |
There was a problem hiding this comment.
🟡 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.
| 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}"); |
There was a problem hiding this comment.
✅ 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.
eabab8c to
d53b9fd
Compare
| 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 { |
There was a problem hiding this comment.
🟠 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.
| if (thr > 0.f) { | ||
| #if K_MODE >= 4 | ||
| ink_tq_store<TQ_KBITS>(dst, dat, t, w, v, tq, sqrtf(ss) * f, active); | ||
| #else |
There was a problem hiding this comment.
🟠 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.
| 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}"); |
There was a problem hiding this comment.
🟡 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.
| @@ -0,0 +1,165 @@ | |||
| # TurboQuant work log — RustingStrata | |||
There was a problem hiding this comment.
🔵 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.
| 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; |
There was a problem hiding this comment.
🔵 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.
| 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]; |
There was a problem hiding this comment.
🔵 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.
| /// 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 } | ||
|
|
There was a problem hiding this comment.
🔵 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.
|
Merged to main, big ty for this, TurboQuant is a big piece and you fixed all the points from my review! I checked that the old modes stay the same: f16, q8 and q4 give the same greedy output as main on CUDA and Vulkan for Qwen3-4B and Qwen3.5-2B (the q_gate one), and Inkling 2 too. turbo4 on CUDA gives good text. A few things I changed while merging: in the Inkling 2 SWA copy and the verify logs the row step was kv_row_words (K+V words) for both K and V, which is right only when both are the same type, so now K and V each use their own row size. On Vulkan turbo4 gave broken text on Qwen3-4B on my 3060 and the hd 128 prefill needs 64000 B of shared memory (the card allows 49152), so Vulkan says turbo is not ready for now, STRATA_VK_TURBO=1 opens it for testing. I also left out TURBOQUANT.md, .vscode and tielcoder-dynamic.bin bc they look like local files. If you want to fix the Vulkan side later, a PR is very welcome, and a quality number (ppl or KLD) for turbo4 vs q4 would be great too. Ty again! |
|
Glad to contribute! I hit so many walls and learned so much. And It's the 1st project I contributed to. And for the vulkan support, I don't have a vulkan driver to test so I just followed the llama-cpp-turboquant's vulkan implementation. If someone fix the issues and tests on vulkan that would be great tho. |
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.rsholds 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-cacheatf7c3638e8): unit-L2 block norm with a reconstruction-corrected fp16 norm, seed-42 WHT signsS1 = {0xE46A0359, 0x42F85949, 0xA4C63BBB, 0x49F250A9}andS2 = {0x16ACEE90, 0x3F628FDC, 0xB7A5357A, 0xBEA56562}, forward rotationS1, butterfly,1/sqrt(128),S2and the inverse with the sign order swapped. The Lloyd-Max centroids forN(0, 1/128)have 4-bit max+/-0.241529, 3-bit+/-0.190207and 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-ctkand-ctvtypes; 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
--kvtakes f16, q8, q4, q2, turbo4, turbo4-3, turbo4-2, turbo3, turbo2 and turbo3-2.--ktakes f16, q8, q4, turbo4, turbo3 and turbo2.--vtakes f16, q8, q4, q2, turbo4, turbo3 and turbo2.--kand--voverride the two halves of--kv, and they work even when--kvis 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_clipnow 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-basedumps against f16 over the same positions. turbo4 and q4 have the same cache size.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_primefunction. 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.A larger-context run used
--pp 2048 --tg 1024 --reps 1 --ctx 8192 --chunk 512on the same model:Tests
cargo test --releaseis 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) andgit merge-treereports no conflicts.The branch merges cleanly with
mainat 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.rschecks 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