Skip to content

Speed up Inkling 2 and MoE decode on small-VRAM GPUs - #74

Merged
Vasyl-Trefilov merged 1 commit into
RustingStudio:mainfrom
sayampy:main-upstream
Nov 22, 2026
Merged

Vasyl-Trefilov merged 1 commit into
RustingStudio:mainfrom
sayampy:main-upstream

Conversation

@sayampy

@sayampy sayampy commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Makes Inkling 2 decode work and get much faster on small-VRAM GPUs, and enables lossless suffix speculative decoding by default for all MoE models.

Changes

  • Inkling 2 staging fallback (src/inkling2/forward/device.rs): when a routed expert cannot be staged into VRAM, finish that layer's experts on the host instead of panicking at device.rs:1393. This was a hard failure on a 4 GB GPU with the old 0.90 GPU fraction.
  • Adaptive GPU fraction (src/inkling2/mod.rs, chat.rs): 0.60 below 8 GB VRAM, 0.90 above. Applies only to Inkling 2; other architectures keep their existing defaults (applying it globally regressed Tiel from 29.3 to 17.1 tok/s).
  • Batched host experts (src/inkling2/forward.rs, src/deepseek/mat.rs): new shared matvec_many_cpu helper computes all host experts of a layer in one Rayon pass; also adds STRATA_DS_EX_AGE as a diagnostic knob for expert-cache eviction age.
  • Suffix drafts by default (src/main.rs): --spec-type now defaults to suffix instead of none. Drafts are verified, so greedy output is unchanged; use --spec-type none to restore the old default.
  • Docs (docs/PERFORMANCE.md, docs/USAGE.md): benchmarks, quality check, and configuration notes.

Benchmarks (RTX 3050 Laptop, 4 GB; release build)

Model Config Prefill Decode
Inkling 2 Mini UD-Q3_K_XL upstream defaults — panic (no room to stage)
fixed, no drafts ~42 tok/s 8.6 tok/s
suffix drafts (new default) 47.2 tok/s 16.3 tok/s (112/112 drafts accepted)
Tiel Coder 35B A3B MTP upstream defaults 43.1 tok/s 16.1 tok/s
suffix drafts (new default) 90.0 tok/s 26.7 tok/s (24/24 accepted)

STRATA_MOE_PREFETCH=1 remains opt-in: it helped once (29.3 → 31.8 tok/s) but was inconsistent on a full expert cache.

Output quality check

generate --temp 0 --seed 1 -n 48 --prompt "The capital of France is" run with suffix drafts and with --spec-type none:

  • Inkling 2: identical for 44 tokens; one later quiz-heading token differs (Past Simple Tense vs Present Perfect vs Past Simple), consistent with the documented small logit shift from the adaptive CPU/GPU expert split. Both continuations are sensible.
  • Tiel: suffix output was a coherent answer (Paris. Paris is a beautiful city. ...); the no-spec output repeated the prompt sentence. Similar or better.

Reverted experiments

Parallel routing (Rayon contention doubled route time), prefetch enabled by default (inconsistent), and a global adaptive GPU fraction (regressed Tiel). Details in docs/PERFORMANCE.md.

Co-authored-by: HY4-Flash

Inkling 2 aborted a decode step when a routed expert could not be staged into
VRAM (the default 0.90 GPU fraction left no room on a 4 GB card). It now falls
back to host experts for that layer, and picks a 0.60 fraction on small cards
while keeping 0.90 on large ones. Host experts of a layer are computed in one
Rayon pass through the new shared matvec_many_cpu helper.

Suffix speculative decoding is now the CLI default. Drafts are verified, so
greedy output is unchanged; acceptance was 100% on both models available here.

Benchmarks (RTX 3050 Laptop 4 GB, release):
- Inkling 2 Mini, pp512/tg64: upstream panicked; 8.6 tok/s after the fix;
  16.3 tok/s with suffix drafts (112/112 accepted).
- Tiel 35B A3B, pp128/tg16: 16.1 -> 26.7 tok/s with suffix drafts
  (24/24 accepted).

Zero-temp generation with and without suffix drafts was checked; outputs are
equivalent (Inkling 2 differs once at token 48, consistent with its adaptive
expert split) and the Tiel suffix output is more coherent.

Experiments reverted: parallel routing, prefetch-on-by-default, and global
adaptive GPU fraction (each regressed at least one model).

Docs: docs/PERFORMANCE.md, docs/USAGE.md.

Co-authored-by: HY4-Flash <hy4-flash@users.noreply.github.com>
@aletheore

aletheore Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

🔍 Aletheore evidence diff

graph LR
    n0["mat.rs"]
    n1["chat.rs"]
    n2["src/inkling2/forward.rs"]
    n3["src/inkling2/mod.rs"]
    n4["config.rs"]
    n5["src/deepseek/forward.rs"]
    n6["src/deepseek/mod.rs"]
    n7["src/gemma4/forward.rs"]
    n8["src/glm/forward.rs"]
    n9["src/hy4/forward.rs"]
    n10["dspark.rs"]
    n11["lib.rs"]
    n12["inkling2_forward.rs"]
    n13["quant.rs"]
    n14["vision.rs"]
    n0 --> n5
    n0 --> n6
    n0 --> n7
    n0 --> n8
    n0 --> n9
    n0 --> n10
    n0 --> n13
    n1 --> n12
    n1 --> n14
    n2 --> n10
    n2 --> n14
    n3 --> n4
    n3 --> n11
    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 dependent
    class n5 dependent
    class n6 dependent
    class n7 dependent
    class n8 dependent
    class n9 dependent
    class n10 dependent
    class n11 dependent
    class n12 dependent
    class n13 dependent
    class n14 dependent
Loading

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

  • docs/PERFORMANCE.md · added · +51/-0
  • docs/USAGE.md · modified · +9/-0
  • src/deepseek/mat.rs · modified · +31/-1 · +1 function · 7 other dependents
  • src/inkling2/chat.rs · modified · +4/-2 · 2 other dependents
  • src/inkling2/forward.rs · modified · +31/-4 · +1 function · 2 other dependents
  • src/inkling2/forward/device.rs · modified · +19/-8 · -1 function
  • src/inkling2/mod.rs · modified · +12/-0 · +1 function, -1 function · 2 other dependents
  • src/main.rs · modified · +1/-1

Aggregate deltas

  • Modules: +0
  • Dependency graph edges: +1
  • Commits: -3

Comment thread src/inkling2/mod.rs
if std::env::var_os("STRATA_DS_GPU_FRACTION").is_some() { return; }
let kind = std::env::var("STRATA_DS_BACKEND").ok();
let total = crate::backend::open(kind.as_deref(), 0).ok()
.and_then(|b| b.mem_info().ok().map(|(_, t)| t)).unwrap_or(0);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟠 High · Correctness · 1 of 10

Fraction is chosen from total VRAM, but the comment and docs say free VRAM mem_info returns (free, total) and the code keeps total. On a 6 GB card that is partly used by the desktop, the code picks 0.60 based on total, while the documented rule (free VRAM below 8 GB) would give a different answer. The comment and USAGE.md describe a rule the code does not implement.

Prompt for your AI agent
File: src/inkling2/mod.rs
Line: 18
Issue: Fraction is chosen from total VRAM, but the comment and docs say free VRAM mem_info returns (free, total) and the code keeps total. On a 6 GB card that is partly used by the desktop, the code picks 0.60 based on total, while the documented rule (free VRAM below 8 GB) would give a different answer. The comment and USAGE.md describe a rule the code does not implement.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Comment thread src/inkling2/mod.rs
let kind = std::env::var("STRATA_DS_BACKEND").ok();
let total = crate::backend::open(kind.as_deref(), 0).ok()
.and_then(|b| b.mem_info().ok().map(|(_, t)| t)).unwrap_or(0);
let frac = if total < 8 << 30 { "0.60" } else { "0.90" };

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟠 High · Correctness · 2 of 10

Failed backend open or mem query silently selects 0.60 fraction unwrap_or(0) turns any failure to open the backend or query memory into total=0, which is below 8 GB, so 0.60 is chosen. On a 12 GB card where the query fails (driver issue, wrong STRATA_DS_BACKEND), decode silently drops to the host-fallback regime the PR is meant to avoid, with no warning.

Prompt for your AI agent
File: src/inkling2/mod.rs
Line: 19
Issue: Failed backend open or mem query silently selects 0.60 fraction unwrap_or(0) turns any failure to open the backend or query memory into total=0, which is below 8 GB, so 0.60 is chosen. On a 12 GB card where the query fails (driver issue, wrong STRATA_DS_BACKEND), decode silently drops to the host-fallback regime the PR is meant to avoid, with no warning.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Comment thread src/inkling2/mod.rs
pub fn gpu_fraction_default() {
if std::env::var_os("STRATA_DS_GPU_FRACTION").is_some() { return; }
let kind = std::env::var("STRATA_DS_BACKEND").ok();
let total = crate::backend::open(kind.as_deref(), 0).ok()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Low · Performance · 3 of 10

Opens a full backend just to read memory, and this runs 3 times gpu_fraction_default is called from chat.rs, from new_with_ctx in forward.rs, and via gpu_defaults. Each call opens a backend (likely creating a CUDA context) to read one number. Startup pays that cost repeatedly, and the value is only needed once because the env var is then set.

Prompt for your AI agent
File: src/inkling2/mod.rs
Line: 17
Symbol: is_arch
Issue: Opens a full backend just to read memory, and this runs 3 times gpu_fraction_default is called from chat.rs, from new_with_ctx in forward.rs, and via gpu_defaults. Each call opens a backend (likely creating a CUDA context) to read one number. Startup pays that cost repeatedly, and the value is only needed once because the env var is then set.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Comment thread src/deepseek/mat.rs
}

/// Host integer dot of several matrices, one activation each, in a single Rayon pass. The activations are
/// quantised once and every weight row is read once; callers with many small expert matrices avoid one parallel

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Low · Performance · 4 of 10

Doc says activations are quantised once, but code quantises each copy run_experts passes gx = vec![x; n], so the same activation is quantised n_expert times in xs.par_iter(). The doc comment promises 'quantised once', which is false, and each layer repeats the quantisation work that the batching was supposed to remove.

Prompt for your AI agent
File: src/deepseek/mat.rs
Line: 477
Symbol: matvec_many_opt
Issue: Doc says activations are quantised once, but code quantises each copy run_experts passes gx = vec![x; n], so the same activation is quantised n_expert times in xs.par_iter(). The doc comment promises 'quantised once', which is false, and each layer repeats the quantisation work that the batching was supposed to remove.
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.

}
None => {
// No room to stage a routed weight: finish this layer's experts on the host and write the
// weighted sum straight into `s.acc`. The conv and residual stay on the device.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Low · Performance · 5 of 10

CPU experts computed in cpu_side are thrown away and recomputed cpu_side already computes on_cpu experts, and on the None path its result is discarded. experts_all_cpu then recomputes every routed expert on the host, including those already done. Each token on a small card does the host expert matmuls twice, which costs the speed-up this PR claims. The fast path in run_experts also falls through to a second full computation if the down-projection returns None.

Prompt for your AI agent
File: src/inkling2/forward/device.rs
Line: 1412
Symbol: layer
Issue: CPU experts computed in cpu_side are thrown away and recomputed cpu_side already computes on_cpu experts, and on the None path its result is discarded. experts_all_cpu then recomputes every routed expert on the host, including those already done. Each token on a small card does the host expert matmuls twice, which costs the speed-up this PR claims. The fast path in run_experts also falls through to a second full computation if the down-projection returns None.
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.

be.put(&y, &self.scr, ((s.acc - o) / 4) as usize).expect("inkling2 device step");
}
}
(|| -> Result<()> {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Correctness · 6 of 10

Fallback put overwrites s.acc, possibly dropping the residual sum The original path calls ink_ffn_sum(s.acc, ...), which likely accumulates the expert sum into the residual stream in s.acc. The new fallback writes y into s.acc with be.put, so any residual already in s.acc is overwritten. Numerics then drift on small-card layers, which the doc's 'small logit shift' note could hide.

Prompt for your AI agent
File: src/inkling2/forward/device.rs
Line: 1418
Symbol: layer
Issue: Fallback put overwrites s.acc, possibly dropping the residual sum The original path calls ink_ffn_sum(s.acc, ...), which likely accumulates the expert sum into the residual stream in s.acc. The new fallback writes y into s.acc with be.put, so any residual already in s.acc is overwritten. Numerics then drift on small-card layers, which the doc's 'small logit shift' note could hide.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Comment thread docs/PERFORMANCE.md
@@ -0,0 +1,51 @@
# Inference performance notes

Measured on an RTX 3050 Laptop (4 GB VRAM), Ryzen 7 7445HS, release build with `-C target-cpu=native`.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Low · Maintainability · 7 of 10

Doc says greedy output preserved, yet its own results show it changed The header states that greedy output is preserved. The same document reports that Inkling 2 output differs at token 45 because of the host-fallback logit shift. Users relying on the header will treat the fallback path as bit-stable when it is not.

Prompt for your AI agent
File: docs/PERFORMANCE.md
Line: 3
Issue: Doc says greedy output preserved, yet its own results show it changed The header states that greedy output is preserved. The same document reports that Inkling 2 output differs at token 45 because of the host-fallback logit shift. Users relying on the header will treat the fallback path as bit-stable when it is not.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Comment thread docs/USAGE.md
doubles decode throughput (9.5 → 16.3 tok/s at 512-token prefill). Adding the DSpark `--draft-model` on top is
not worth it: its drafts drop acceptance to 89% and decode fell to 15.7 tok/s in the same test.
- Generic MoE models (e.g. 35B-A3B) benefit from the same suffix default: measured 29 → 46 tok/s with 100% draft
acceptance. `STRATA_MOE_PREFETCH=1` is available as an opt-in next-layer L2 prefetch; it helped when the expert

@aletheore aletheore Bot Nov 22, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 44b6a373b932.


🔵 Low · Maintainability · 8 of 10

USAGE claims Tiel 46 tok/s, PERFORMANCE table reports 26.7 USAGE.md says 35B-A3B goes from 29 to 46 tok/s with suffix. PERFORMANCE.md reports 16.1 to 26.7 with suffix and gives 29.3 as a small-cache prefetch figure. A reader cannot tell which number is the real speedup, so the advertised gain is unreliable.

Prompt for your AI agent
File: docs/USAGE.md
Line: 158
Issue: USAGE claims Tiel 46 tok/s, PERFORMANCE table reports 26.7 USAGE.md says 35B-A3B goes from 29 to 46 tok/s with suffix. PERFORMANCE.md reports 16.1 to 26.7 with suffix and gives 29.3 as a small-cache prefetch figure. A reader cannot tell which number is the real speedup, so the advertised gain is unreliable.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Comment thread src/main.rs
#[arg(long, default_value = "none")]
#[arg(long, default_value = "suffix")]
spec_type: String,
/// Maximum number of speculative draft tokens verified per step (1..=16).

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Low · Maintainability · 9 of 10

Global spec-type default changes behaviour for every model The default changes for all architectures, including dense models and any with --draft-model or --mtp, which now hit the hybrid cascade without asking. On prompts with little repetition, suffix drafts that are rejected add verify overhead and can reduce decode speed for users who never opted in.

Prompt for your AI agent
File: src/main.rs
Line: 52
Symbol: Engine
Issue: Global spec-type default changes behaviour for every model The default changes for all architectures, including dense models and any with --draft-model or --mtp, which now hit the hybrid cascade without asking. On prompts with little repetition, suffix drafts that are rejected add verify overhead and can reduce decode speed for users who never opted in.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Comment thread src/deepseek/mat.rs
let age = std::env::var("STRATA_DS_EX_AGE").ok().and_then(|v| v.parse::<u64>().ok()).unwrap_or(96);
let victim = self.exs.iter().enumerate()
.filter(|(_, e)| e.2 + 96 <= now && { let t = self.tensor(e.0); t.ty == ty && t.rows == rows && t.cols == cols })
.filter(|(_, e)| e.2 + age <= now && { let t = self.tensor(e.0); t.ty == ty && t.rows == rows && t.cols == cols })

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Low · Maintainability · 10 of 10

Env var read inside eviction loop; knob adds no value std::env::var is evaluated on every eviction call, which is a hot path in expert caching. The PR's own notes say the knob did not change hit rate, so this adds a diagnostic setting with no measured benefit and it can be removed or hoisted out of the loop.

Prompt for your AI agent
File: src/deepseek/mat.rs
Line: 216
Symbol: expert
Issue: Env var read inside eviction loop; knob adds no value std::env::var is evaluated on every eviction call, which is a hot path in expert caching. The PR's own notes say the knob did not change hit rate, so this adds a diagnostic setting with no measured benefit and it can be removed or hoisted out of the loop.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

@aletheore

aletheore Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

Aletheore Flash review

No new issues found in this push. 15 earlier finding(s) from previous pushes are still open.

@Vasyl-Trefilov

Copy link
Copy Markdown
Member

@sayampy Merged in part, ty. The panic is real: I reproduced it on a 3060 with 3.4 GB of VRAM left free (main: panic at device.rs:1432, merged: 14 to 17 tok/s).

Kept:

  • The host fallback when a routed expert cannot be staged. It now keeps the result of the CPU side and runs only the GPU's experts on the host.
  • The 0.6 share for a small card, as STRATA_DS_GPU_FRACTION=0.6,0.9 (small,large), read where the device is opened. It uses the free VRAM of the selected card and opens no extra backend (the PR opened device 0 even with STRATA_DS_GPU=0).

Left out:

  • --spec-type suffix as default. It turns off the calibrated MTP drafts of Qwen models, and DeepSeek, GLM, Hy4 and Gemma 4 print a "decode without drafts" warning on every run. bench text repeats, so it accepts 100%, on a natural prompt I get 0 to 30% accepted and no gain (Qwen3-4B 84.7 against 83.7 tok/s).
  • Draft length 16: that branch sets the DSpark draft length. 400 tokens of natural text took 22 s with 3 and 32 to 36 s with 16.
  • matvec_many_cpu: no gain here (host-only decode 11.1 against 11.1 tok/s). If you have a before/after number for it alone on the 3050, send it and I will take it.
  • STRATA_DS_EX_AGE and docs/PERFORMANCE.md (the doc numbers must come from the reference machine), so if you want, you can add it in docs in some other file.
    Ty again!

Comment thread src/cuda/kernels.cu Outdated
}
__device__ __forceinline__ void kv_put(u16* c, size_t e, int hd, float x) {
template <int M, bool IS_K> __device__ __forceinline__ void kv_put(u16* c, size_t e, int hd, float x) {
#if M == 5

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟠 High · Correctness · 1 of 6

#if M == 5 and #if M >= 4 test a template parameter, so rotation is never applied on store The preprocessor treats the template parameter M as 0, so #if M == 5 (in kv_put for turbo3) and #if M >= 4 (in the q4-style kv_put for turbo4, rotorquant, turbo4-3 and turbo4-2) are always false. kv_rot_fwd is never called on store, but ldkv/ldkv1 apply kv_inv on load. Every turbo KV cache is therefore read back with an inverse rotation of unrotated data, so attention gets corrupted values and output is garbage. The same error is in the q4-style kv_put at about line 2297.

Prompt for your AI agent
File: src/cuda/kernels.cu
Line: 2273
Issue: `#if M == 5` and `#if M >= 4` test a template parameter, so rotation is never applied on store The preprocessor treats the template parameter M as 0, so `#if M == 5` (in kv_put for turbo3) and `#if M >= 4` (in the q4-style kv_put for turbo4, rotorquant, turbo4-3 and turbo4-2) are always false. kv_rot_fwd is never called on store, but ldkv/ldkv1 apply kv_inv on load. Every turbo KV cache is therefore read back with an inverse rotation of unrotated data, so attention gets corrupted values and output is garbage. The same error is in the q4-style kv_put at about line 2297.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Comment thread src/cuda/kernels.cu Outdated
}
#pragma unroll
for (int i = 0; i < 8; i++) v[i] *= 0.3535533905932738f;
#endif

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟠 High · Correctness · 2 of 6

PER < 8 in a preprocessor guard is always true, so ldkv<8> recurses into itself In #if KV_MODE >= 4 && PER < 8, PER is undefined to the preprocessor and evaluates to 0, so the condition is true for every instantiation. For PER=8 the block calls ldkv<8>, which calls ldkv<8> again and never returns. Any vector KV load in turbo modes recurses until the GPU stack overflows, so decode fails on the first attention step. Narrow PER values never reach the intended fallback either.

Prompt for your AI agent
File: src/cuda/kernels.cu
Line: 2418
Issue: `PER < 8` in a preprocessor guard is always true, so ldkv<8> recurses into itself In `#if KV_MODE >= 4 && PER < 8`, PER is undefined to the preprocessor and evaluates to 0, so the condition is true for every instantiation. For PER=8 the block calls ldkv<8>, which calls ldkv<8> again and never returns. Any vector KV load in turbo modes recurses until the GPU stack overflows, so decode fails on the first attention step. Narrow PER values never reach the intended fallback either.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Comment thread src/cuda/kernels.cu Outdated
#pragma unroll
for (int i = 0; i < 4; i++) { unsigned w = o[4 * b + i]; v[2 * i] = h2f((u16)w); v[2 * i + 1] = h2f((u16)(w >> 16)); }
#if KV_MODE >= 4
for (int s = 1; s >= 0; s--) { // inverse of the forward step-4 then step-2 Givens pair

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Low · Maintainability · 3 of 6

Hadamard #else branches in kv_inv are dead; the inverse rotation is duplicated in ldkv1 kv_inv sits inside #if KV_MODE >= 4, so its inner #if KV_MODE >= 4 is always true and the #else Hadamard loop never compiles. ldkv1 repeats the same Givens inverse loop instead of calling a shared helper. Two copies of the transform can drift apart, and the stale Hadamard code makes the rotation scheme harder to audit.

Prompt for your AI agent
File: src/cuda/kernels.cu
Line: 2400
Issue: Hadamard `#else` branches in kv_inv are dead; the inverse rotation is duplicated in ldkv1 kv_inv sits inside `#if KV_MODE >= 4`, so its inner `#if KV_MODE >= 4` is always true and the `#else` Hadamard loop never compiles. ldkv1 repeats the same Givens inverse loop instead of calling a shared helper. Two copies of the transform can drift apart, and the stale Hadamard code makes the rotation scheme harder to audit.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Comment thread src/cuda/kernels.cu Outdated
size_t g = off & ~(size_t)7;
int w8 = (int)(g % hd);
float v[8];
#if KV_MODE == 5

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Low · Performance · 4 of 6

Scalar ldkv1 re-dequantizes and inverse-rotates a whole 8-group for each element Every scalar KV read in turbo modes decodes all 8 values of its group, runs the inverse rotation, and then keeps one value. This is 8 times the dequant and shuffle-free math per read. The PR says decode is slower with these modes, and this scalar path is a likely reason. Caching the group per thread or using the vector path would avoid the redundant work.

Prompt for your AI agent
File: src/cuda/kernels.cu
Line: 2530
Issue: Scalar ldkv1 re-dequantizes and inverse-rotates a whole 8-group for each element Every scalar KV read in turbo modes decodes all 8 values of its group, runs the inverse rotation, and then keeps one value. This is 8 times the dequant and shuffle-free math per read. The PR says decode is slower with these modes, and this scalar path is a likely reason. Caching the group per thread or using the vector path would avoid the redundant work.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Comment thread src/cuda/mod.rs Outdated
super::nvrtc::cubin(&super::source(3, false), "sm_75").unwrap_or_else(|e| panic!("sm_75 kv_q2 must compile: {e:#}"));
for m in [4, 5, 6] {
super::nvrtc::cubin(&super::source(m, false), "sm_75").unwrap_or_else(|e| panic!("sm_75 turbo KV mode {m} must compile: {e:#}"));
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Low · Maintainability · 5 of 6

New test only checks that turbo modes compile, not that they round-trip correctly The added test only asserts that the NVRTC source for modes 4 to 6 compiles. The store-side rotation bug and the ldkv recursion both compile cleanly, so the test passes while every turbo KV cache is corrupt. A store-then-load round trip against the f16 reference would have caught both.

Prompt for your AI agent
File: src/cuda/mod.rs
Line: 1394
Symbol: nvrtc_compiles_full_source_for_sm70
Issue: New test only checks that turbo modes compile, not that they round-trip correctly The added test only asserts that the NVRTC source for modes 4 to 6 compiles. The store-side rotation bug and the ldkv recursion both compile cleanly, so the test passes while every turbo KV cache is corrupt. A store-then-load round trip against the f16 reference would have caught both.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Comment thread docs/PERFORMANCE.md Outdated
and was replaced by the fixed rotor above.

Asymmetric pairs `--kv turbo4-3` (alias `turbo4v3`) and `--kv turbo4-2` (`turbo4v2`) keep K at 4 bits and give V a
narrower 4-/2-bit code inside the same nibble layout, so K and V rows keep the same stride. In the zero-temperature

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Low · Maintainability · 6 of 6

Asymmetric modes are documented inconsistently

'4-/2-bit' here, 'V at 3 or 2' in USAGE PERFORMANCE.md says V gets a '4-/2-bit' code, while USAGE.md says V is 3 or 2 bits. The code uses RANGE 4 for turbo4-3 and RANGE 2 for turbo4-2, which gives about 3 and 2 bits. A user choosing the mode from the docs could expect the wrong quality/memory trade-off.

Prompt for your AI agent
File: docs/PERFORMANCE.md
Line: 88
Issue: Asymmetric modes are documented inconsistently: '4-/2-bit' here, 'V at 3 or 2' in USAGE PERFORMANCE.md says V gets a '4-/2-bit' code, while USAGE.md says V is 3 or 2 bits. The code uses RANGE 4 for turbo4-3 and RANGE 2 for turbo4-2, which gives about 3 and 2 bits. A user choosing the mode from the docs could expect the wrong quality/memory trade-off.
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
Vasyl-Trefilov merged commit d27fb28 into RustingStudio:main Nov 22, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants