Repository navigation
Conversation
🔍 Aletheore evidence diffgraph 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
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 pull request adds TurboQuant KV cache compression on CUDA with separately configurable K and V formats (
5 finding(s) posted as inline review comment(s). 4 earlier finding(s) from previous pushes still open.
Review detailsReviewed 9 file(s); skipped 2. Dismissed 0; outside PR diff 5. Grounding: 16 of 19 proposed finding(s). Fix all with your agentNote: 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: 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.
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.
🟠 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.
🟡 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. |
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
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.
🟠 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.
🟠 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.
🔵 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.
🔵 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.
🔵 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.
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
--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 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-basedumps compared with f16. turbo4 and q4 have the same cache size.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.Tests
cargo test --releaseis 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