Skip to content

raon1: add KRAFTON Raon-1 mini architecture support (mHC, RDA, gated NoPE MLA, SiTU-GLU MoE, effort steering) - #103

Merged
Vasyl-Trefilov merged 6 commits into
RustingStudio:mainfrom
ybenyedder:feat/raon-1-mini
Nov 26, 2026
Merged

Vasyl-Trefilov merged 6 commits into
RustingStudio:mainfrom
ybenyedder:feat/raon-1-mini

Conversation

@ybenyedder

Copy link
Copy Markdown
Contributor

Adds support for KRAFTON Raon-1 mini (general.architecture = "raon1", KRAFTON/Raon-1-mini-gguf), mirroring krafton-ai/llama.cpp (src/models/raon1.cpp) and KRAFTON/Raon-1-mini (modeling_raon1_mini.py).

Summary of Changes

  • src/raon/mod.rs: RaonConfig::from_gguf parsing all raon1.* hyperparameters (25 layers partitioned into 18 RDA + 7 MLA via attention.head_count_kv, 4-stream Raon-mHC, SiTU-GLU betas, MoE + shared expert, and per-layer reasoning_effort steering metadata).
  • src/raon/forward.rs:
    • 4-stream Raon-mHC (helmert_basis, raon_mhc_coeffs, hc_pre, hc_post) using the doubly-stochastic Helmert chart (E = Q Z Q^T, Phi = B + E / (1 + rho), H = (1 - gamma) I + gamma Phi).
    • RDA (Raon Delta Attention): depthwise causal conv1d (width 4) + SiLU on Q/K/V, lower-bounded/softplus per-head decay gate, decoupled write/erase gate folded into V, L2-normalized Q/K, and V-first recurrent delta-rule state update parallelized across heads.
    • Gated NoPE MLA: absorbed k_b / v_b attention over [kv_lora_rank + qk_rope_hd] latents without RoPE rotation + sigmoid output gate.
    • SiTU-GLU dense & MoE FFN (sigmoid router with selection-only bias + shared expert + reasoning effort steering), with GPU/CPU matvecs & expert cache via crate::deepseek::mat and chunked expert-deduplicated prefill_chunk.
  • src/raon/chat.rs: ChatML template (<|im_start|>, <|im_end|>, <think>, <tool_call><function=...><parameter=...>) matching chat_template.jinja, parse_calls, generate, chat, and serve (with serve::alive / serve::held SSE keep-alive and reasoning_effort selection).
  • src/tokenizer.rs: Added "raon" pre-tokenizer regex (LLAMA_VOCAB_PRE_TYPE_RAON) with Unicode NFC normalization.
  • src/lib.rs, src/config.rs, src/main.rs, docs/MODELS.md: Registered raon1 in OWN_ARCHS, generate, chat, serve, bench (bench_raon), check, calibrate, and docs.
  • tests/raon_forward.rs: Synthetic 2-layer end-to-end raon1 GGUF test verifying RaonConfig::from_gguf, RaonModel::new, chunked prefill vs token-by-token step parity (< 1e-4), reasoning effort steering, and reset() determinism, plus STRATA_RAON_MODEL-gated real-model test.

Verification

  • cargo build --release --bin rustingstrata --locked (0 warnings in new code)
  • cargo test --release --test raon_forward --locked (2/2 pass)
  • cargo test --release --lib --locked -- --skip hip::tests (all pass, including 5 new raon::* unit tests)
  • cargo test --release --test backend --locked (all pass)

@aletheore

aletheore Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

🔍 Aletheore evidence diff

graph LR
    n0["config.rs"]
    n1["src/cpu_moe.rs"]
    n2["mat.rs"]
    n3["lib.rs"]
    n4["tokenizer.rs"]
    n5["cpu_worker.rs"]
    n6["src/cuda/mod.rs"]
    n7["src/deepseek/chat.rs"]
    n8["src/deepseek/forward.rs"]
    n9["src/deepseek/mod.rs"]
    n10["expert_cache.rs"]
    n11["src/gemma4/forward.rs"]
    n12["src/gemma4/mod.rs"]
    n13["src/gguf.rs"]
    n14["src/glm/forward.rs"]
    n15["src/glm/mod.rs"]
    n16["gpu_model.rs"]
    n17["prefill.rs"]
    n18["src/hy4/chat.rs"]
    n19["src/hy4/forward.rs"]
    n20["src/hy4/mod.rs"]
    n21["src/inkling2/chat.rs"]
    n22["dspark.rs"]
    n23["src/inkling2/forward.rs"]
    n24["device.rs"]
    n25["src/inkling2/mod.rs"]
    n26["src/kolibri/chat.rs"]
    n27["src/kolibri/forward.rs"]
    n28["src/kolibri/mod.rs"]
    n29["model.rs"]
    n30["ngram.rs"]
    n31["serve.rs"]
    n32["preflight.rs"]
    n33["weights.rs"]
    n34["tests/cpu_moe.rs"]
    n35["tests/gguf.rs"]
    n36["quant.rs"]
    n37["vision.rs"]
    n0 --> n16
    n0 --> n29
    n0 --> n33
    n0 --> n35
    n0 --> n36
    n1 --> n5
    n1 --> n11
    n1 --> n17
    n1 --> n34
    n1 --> n36
    n2 --> n8
    n2 --> n9
    n2 --> n11
    n2 --> n14
    n2 --> n19
    n2 --> n22
    n2 --> n23
    n2 --> n24
    n2 --> n27
    n2 --> n36
    n3 --> n6
    n3 --> n7
    n3 --> n10
    n3 --> n12
    n3 --> n13
    n3 --> n14
    n3 --> n15
    n3 --> n16
    n3 --> n17
    n3 --> n18
    n3 --> n20
    n3 --> n21
    n3 --> n25
    n3 --> n26
    n3 --> n28
    n3 --> n29
    n3 --> n30
    n3 --> n31
    n3 --> n32
    n3 --> n33
    n4 --> n12
    n4 --> n15
    n4 --> n30
    n4 --> n37
    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 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
    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
    class n34 dependent
    class n35 dependent
    class n36 dependent
    class n37 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/MODELS.md · modified · +1/-0
  • src/config.rs · modified · +1/-1 · 5 other dependents
  • src/cpu_moe.rs · modified · +170/-0 · +4 functions · 5 other dependents
  • src/deepseek/mat.rs · modified · +173/-13 · +4 functions · 10 other dependents
  • src/lib.rs · modified · +1/-0 · 20 other dependents
  • src/main.rs · modified · +19/-1
  • src/raon/chat.rs · +358/-0 · new file, 8 symbols
  • src/raon/dflash.rs · +442/-0 · new file, 11 symbols
  • src/raon/forward.rs · +1472/-0 · new file, 46 symbols
  • src/raon/mod.rs · +185/-0 · new file, 3 symbols
  • src/tokenizer.rs · modified · +7/-0 · 4 other dependents
  • tests/raon_forward.rs · +274/-0 · new file, 11 symbols

Aggregate deltas

  • Modules: +5
  • Dependency graph edges: +27
  • Commits: 6

Comment thread src/raon/chat.rs
let max_ctx = m.cfg.n_ctx;
Ok(Box::new(move |c: &mut std::net::TcpStream, q: &crate::serve::ChatRequest| {
let think = q.think.unwrap_or(false);
m.set_effort(q.reasoning_effort.as_deref(), think);

@aletheore aletheore Bot Nov 24, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 42636b5e9662.


🟠 High · Correctness · 1 of 8

Effort steering changes per request, but the prefix KV cache built under the previous alpha is still reused. Request A runs with effort 'low', so the prefix KV cache is built with steering alpha 0.3 in the effort layers. Request B shares the same prompt prefix and asks for effort 'none'. set_effort sets alpha to 0.0, but the keep check still reuses the cached prefix. The suffix is computed with alpha 0.0 while the prefix hidden states carry the steered values, so the output is inconsistent with a fresh run.

Prompt for your AI agent
File: src/raon/chat.rs
Line: 216
Issue: Effort steering changes per request, but the prefix KV cache built under the previous alpha is still reused. Request A runs with effort 'low', so the prefix KV cache is built with steering alpha 0.3 in the effort layers. Request B shares the same prompt prefix and asks for effort 'none'. set_effort sets alpha to 0.0, but the `keep` check still reuses the cached prefix. The suffix is computed with alpha 0.0 while the prefix hidden states carry the steered values, so the output is inconsistent with a fresh run.
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/raon/chat.rs
#[test]
fn template_and_calls() {
let user = [Msg::new("user", "hi")];
assert_eq!(render(&user, &[], false, None), "<|im_start|>user\nhi<|im_end|>\n<|im_start|>assistant\n<think></think>\n\n");

@aletheore aletheore Bot Nov 24, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 42636b5e9662.


🟠 High · Correctness · 2 of 8

Assistant turns are stored from decoded text without the <think> wrapper, so reasoning is re-rendered incorrectly. In chat with think=true the prompt already ends with '<think>\n', so the decoded output is 'reasoning</think>\n\nanswer' and does not start with '<think>'. render() treats the whole string as body, so the next turn emits a literal '</think>' inside the assistant content and drops the reasoning block. The model sees a malformed history and the prefix cache no longer matches.

Prompt for your AI agent
File: src/raon/chat.rs
Line: 266
Issue: Assistant turns are stored from decoded text without the <think> wrapper, so reasoning is re-rendered incorrectly. In chat with think=true the prompt already ends with '<think>\n', so the decoded output is 'reasoning</think>\n\nanswer' and does not start with '<think>'. render() treats the whole string as body, so the next turn emits a literal '</think>' inside the assistant content and drops the reasoning block. The model sees a malformed history and the prefix cache no longer matches.
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/raon/chat.rs Outdated
let mut calls = Vec::new();
for block in text[start..].split(CALL_TAG).skip(1) {
let inner = block.split("</tool_call>").next()?;
let (_, after_fn) = inner.split_once("<function=")?;

@aletheore aletheore Bot Nov 24, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 681149bacbc7.


🟠 High · Correctness · 3 of 8

parse_calls uses ? inside the per-block loop, so one malformed block discards every tool call. A reply contains two tool_call blocks, and the second is missing '<function='. The ? on split_once returns None for the whole function, so no calls are parsed. The raw tool_call markup is then returned as plain assistant content and the finish reason becomes 'stop' instead of 'tool_calls'.

Prompt for your AI agent
File: src/raon/chat.rs
Line: 128
Issue: parse_calls uses `?` inside the per-block loop, so one malformed block discards every tool call. A reply contains two tool_call blocks, and the second is missing '<function='. The `?` on split_once returns None for the whole function, so no calls are parsed. The raw tool_call markup is then returned as plain assistant content and the finish reason becomes 'stop' instead of 'tool_calls'.
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/raon/chat.rs Outdated
let next = logits.iter().enumerate().max_by(|a, b| a.1.partial_cmp(b.1).unwrap()).unwrap().0 as u32;
if eos.contains(&next) { return (out, true); }
out.push(next);
let s = tok.decode(&out).unwrap_or_default();

@aletheore aletheore Bot Nov 24, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 15f95300b1e6.


🔵 Low · Performance · 4 of 8

decode re-decodes the entire output vector on every generated token. Generating n tokens calls tok.decode(&out) n times on a growing vector, so detokenization cost is O(n^2). For long answers (thousands of tokens) this adds noticeable per-token latency that grows with output length.

Prompt for your AI agent
File: src/raon/chat.rs
Line: 149
Issue: decode re-decodes the entire output vector on every generated token. Generating n tokens calls tok.decode(&out) n times on a growing vector, so detokenization cost is O(n^2). For long answers (thousands of tokens) this adds noticeable per-token latency that grows with output length.
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/raon/chat.rs
let line = line.trim_end();
if line.is_empty() { continue; }
history.push(Msg::new("user", line));
let text = render(&history, &[], think, None);

@aletheore aletheore Bot Nov 24, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 42636b5e9662.


🔵 Low · Performance · 5 of 8

chat re-renders and re-encodes the full history each turn, and the cache check often fails. Every turn renders the whole conversation and re-encodes it. Because the assistant turns are re-rendered differently from what was generated (see the reasoning-wrapper issue), ids.starts_with(&m.toks) usually fails, so m.reset() runs and the entire history is prefilled from scratch each turn, which is quadratic over a session.

Prompt for your AI agent
File: src/raon/chat.rs
Line: 193
Issue: chat re-renders and re-encodes the full history each turn, and the cache check often fails. Every turn renders the whole conversation and re-encodes it. Because the assistant turns are re-rendered differently from what was generated (see the reasoning-wrapper issue), `ids.starts_with(&m.toks)` usually fails, so m.reset() runs and the entire history is prefilled from scratch each turn, which is quadratic over a session.
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/raon/forward.rs
pub fn step(&mut self, tok: u32) -> Vec<f32> {
self.step_opt(tok, true)
}

@aletheore aletheore Bot Nov 24, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 42636b5e9662.


🔵 Low · Maintainability · 6 of 8

prefill_chunk duplicates the per-token hc_pre, RDA, MLA, and MoE logic from rda_step, mla_step, and ffn_step. Two copies of the RDA gating, MLA attention, and MoE routing now exist. Any fix to one, such as the log_alpha or ratio formula, must be mirrored in the other. The parity test only covers one 8-token chunk, so the copies can silently diverge and produce prefill/decode mismatches.

Prompt for your AI agent
File: src/raon/forward.rs
Line: 663
Issue: prefill_chunk duplicates the per-token hc_pre, RDA, MLA, and MoE logic from rda_step, mla_step, and ffn_step. Two copies of the RDA gating, MLA attention, and MoE routing now exist. Any fix to one, such as the log_alpha or ratio formula, must be mirrored in the other. The parity test only covers one 8-token chunk, so the copies can silently diverge and produce prefill/decode mismatches.
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/raon/forward.rs
rms_norm_w(&kv[..kr], &a.kv_a_norm, self.cfg.latent_eps, &mut krow[..kr]);
krow[kr..].copy_from_slice(&kv[kr..]);
self.mla_keys[il].extend_from_slice(&krow);

@aletheore aletheore Bot Nov 24, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 42636b5e9662.


🔵 Low · Performance · 7 of 8

mla_step rebuilds the per-head k_b and v_b Mat views on every decode step. For each generated token and each MLA layer, the code allocates two Vec<Mat> of nh group views (k_groups and v_groups), plus a per-head scores Vec inside the parallel loop. These are constant per layer and could be built once in RaonModel::new, avoiding allocations on the hot decode path.

Prompt for your AI agent
File: src/raon/forward.rs
Line: 538
Issue: mla_step rebuilds the per-head k_b and v_b Mat views on every decode step. For each generated token and each MLA layer, the code allocates two Vec<Mat> of nh group views (k_groups and v_groups), plus a per-head scores Vec inside the parallel loop. These are constant per layer and could be built once in RaonModel::new, avoiding allocations on the hot decode path.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

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

Comment thread src/raon/forward.rs
}

fn hc_post(&self, flat: &mut [f32], branch: &[f32], post: &[f32], h_res: &[f32]) {
let (hc, n) = (self.cfg.hc, self.cfg.n_embd);

@aletheore aletheore Bot Nov 24, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 42636b5e9662.


🔵 Low · Performance · 8 of 8

hc_post clones the full multi-stream buffer on every call. hc_post calls flat.to_vec() for each of the two sublayers in every layer and every token. That allocates and copies hc*n_embd floats per call. Writing the update in place with a small hc-sized temporary per output row would avoid it.

Prompt for your AI agent
File: src/raon/forward.rs
Line: 443
Issue: hc_post clones the full multi-stream buffer on every call. hc_post calls flat.to_vec() for each of the two sublayers in every layer and every token. That allocates and copies hc*n_embd floats per call. Writing the update in place with a small hc-sized temporary per output row would avoid 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.

@aletheore

aletheore Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Aletheore Flash Lite review

What this PR does. This PR adds the raon1 architecture as a model with its own forward pass, and also adds support for kolibri1 (Kolibri 1.1), AVX-512 four-activation dot kernels behind a STRATA_AVX512 environment flag, and batched GPU weight allocation in the DeepSeek device path. Users who load Raon-1 mini or Kolibri 1.1 GGUF files in RustingStrata are affected, as are maintainers of the CPU MoE kernels and the DeepSeek CUDA/Vulkan code, since the title mentions only Raon-1 but the diff covers more.

Merge confidence Review effort Merge risk
4 / 5 5 / 5 Low
Area Files Lines
src 5 +1351 −192
src/raon 4 +2457 −0
docs 1 +47 −2
src/deepseek 1 +307 −34
tests 1 +274 −0

6 finding(s) posted as inline review comment(s).

# Severity Category Where
4 🔵 Low Maintainability mat.rs:655 matvec_many_cpu_shared duplicates matvec_many_cpu almost line for line The eligibility loop, starts/dots…
6 🔵 Low Maintainability mat.rs:862 Mat::load_host repeats Mat::load's parsing and scale lookup The dims, dtype and .scale lookup are…
7 🟡 Medium Correctness chat.rs:262 chat() keeps the KV prefix but never resyncs the DFlash context, so draft positions drift. On a follow-up…
8 🔵 Low Performance chat.rs:128 decode re-detokenizes the whole output on every emitted token. emit() calls tok.decode(out) over all…
9 🔵 Low Performance dflash.rs:80 rope_neox_inplace recomputes base.powf per head and per position. The inv_freq powf sits inside the head…
10 🔵 Low Performance dflash.rs:330 Selector scoring builds a full (index, logit) vector over the vocabulary at each position. For vocab around…
Review details

Reviewed 11 file(s); skipped 1. Dismissed 0; outside PR diff 4. Grounding: 17 of 25 proposed finding(s).

Fix all with your agent
File: src/deepseek/mat.rs
Line: 655
Symbol: load_groups
Issue: matvec_many_cpu_shared duplicates matvec_many_cpu almost line for line The eligibility loop, starts/dots build and parallel row loop are copied between matvec_many_cpu_shared and matvec_many_cpu, so a fix to one (for example the total_rows rule) is easily missed in the other and the two drift apart.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/deepseek/mat.rs
Line: 862
Issue: Mat::load_host repeats Mat::load's parsing and scale lookup The dims, dtype and .scale lookup are re-implemented here, so a future change to how Mat::load reads scales or shapes will not reach load_host and the two loaders can disagree on the same tensor.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/raon/chat.rs
Line: 262
Issue: chat() keeps the KV prefix but never resyncs the DFlash context, so draft positions drift. On a follow-up turn where the prefix is kept, df is not reset. Generated tokens from the previous turn were never committed to df, so df.ctx_len lags m.toks. New prompt features are then appended with shifted RoPE positions. Drafts are still verified, so output stays correct, but acceptance collapses and the speedup is lost silently.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/raon/chat.rs
Line: 128
Issue: decode re-detokenizes the whole output on every emitted token. emit() calls tok.decode(out) over all generated ids every step. For a 4k-token reply this is about 8M token-decodes in total, which adds visible latency to streaming and slows long generations.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/raon/dflash.rs
Line: 80
Issue: rope_neox_inplace recomputes base.powf per head and per position. The inv_freq powf sits inside the head loop, so each call does n_heads*half transcendental calls for the same frequencies. draft_block and commit_ctx call it per token, per layer, so a single block does tens of thousands of powf calls. A precomputed table of half entries would remove this.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/raon/dflash.rs
Line: 330
Issue: Selector scoring builds a full (index, logit) vector over the vocabulary at each position. For vocab around 250k, each draft position pushes about 250k (usize, f32) pairs and runs select_nth over them to keep 16. That allocation and pass repeats for every block position, which is wasteful next to the 16 candidates actually scored.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Note: 1 of 12 changed file(s) were not included in this review (the review reads at most 30 files, and skips any file over 100KB). Issues in them would not be found, and citations pointing into them could not be checked against the real file: src/main.rs.

Blast radius: 53 other file(s) depend on what this PR changes (33 directly, 20 indirectly)

Computed from the import graph of this exact commit, not guessed by a model. It sees imports only, so dynamic imports, reflection and non-code references are not counted.

  • src/lib.rs is imported by src/cuda/mod.rs, src/deepseek/chat.rs, src/expert_cache.rs, src/gemma4/mod.rs (+16 more)
  • src/deepseek/mat.rs is imported by src/deepseek/forward.rs, src/deepseek/mod.rs, src/gemma4/forward.rs, src/glm/forward.rs (+6 more)
  • src/config.rs is imported by src/gpu_model.rs, src/model.rs, src/weights.rs, tests/gguf.rs (+1 more)
  • src/cpu_moe.rs is imported by src/cpu_worker.rs, src/gemma4/forward.rs, src/gpu_model/prefill.rs, tests/cpu_moe.rs (+1 more)
  • src/tokenizer.rs is imported by src/gemma4/mod.rs, src/glm/mod.rs, src/ngram.rs, tests/vision.rs

Indirectly affected: examples/gguf_dump.rs, src/backend.rs, src/chat.rs, src/hf.rs, src/hip/mod.rs, src/vision/mmproj.rs (+14 more)

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

Comment thread src/raon/chat.rs
for block in text[start..].split(CALL_TAG).skip(1) {
let Some(inner) = block.split("</tool_call>").next() else { continue; };
let Some((_, after_fn)) = inner.split_once("<function=") else { continue; };
let Some((name, rest)) = after_fn.split_once('>') else { continue; };

@aletheore aletheore Bot Nov 24, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 42636b5e9662.


🟠 High · Correctness · 1 of 6

parse_calls silently skips malformed blocks and parameters instead of failing, so calls run with missing arguments or get lost. The model emits a parameter without a closing '>', e.g. <parameter=city Seoul</parameter>. The new continue drops that argument, the call runs without it, and the bad output is never reported. If every block is malformed, the function can return Some with an empty call list, which a caller may treat as a real tool call.

Prompt for your AI agent
File: src/raon/chat.rs
Line: 129
Symbol: parse_calls
Issue: parse_calls silently skips malformed blocks and parameters instead of failing, so calls run with missing arguments or get lost. The model emits a parameter without a closing '>', e.g. <parameter=city Seoul</parameter>. The new `continue` drops that argument, the call runs without it, and the bad output is never reported. If every block is malformed, the function can return Some with an empty call list, which a caller may treat as a real tool call.
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/raon/chat.rs
println!();
let reply = tok.decode(&out).unwrap_or_default();
let stored = if think { format!("{THINK_OPEN}{reply}") } else { reply };
history.push(Msg::new("assistant", &stored));

@aletheore aletheore Bot Nov 24, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 42636b5e9662.


🟠 High · Correctness · 2 of 6

Prepending THINK_OPEN to the decoded reply assumes the model never emits its own <think> tag, which may double it. When think=true, the decoded output already contains '<think>' because the model generated it. format!("{THINK_OPEN}{reply}") stores '<think><think>...' in history, and the next render passes the corrupted reasoning block back to the model.

Prompt for your AI agent
File: src/raon/chat.rs
Line: 206
Symbol: chat
Issue: Prepending THINK_OPEN to the decoded reply assumes the model never emits its own <think> tag, which may double it. When think=true, the decoded output already contains '<think>' because the model generated it. format!("{THINK_OPEN}{reply}") stores '<think><think>...' in history, and the next render passes the corrupted reasoning block back to the model.
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/raon/forward.rs
kv_a_norm: v("attn_kv_a_norm")?,
k_b,
v_b,
k_groups,

@aletheore aletheore Bot Nov 24, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 42636b5e9662.


🔵 Low · Maintainability · 3 of 6

MLA now keeps k_b/v_b and the new k_groups/v_groups, which may duplicate weight storage and leave the k_b/v_b fields unused. If group() copies the data, each of the 7 MLA layers stores the attn_k_b and attn_v_b weights twice, increasing memory use. If the forward path only reads the group vectors, the k_b and v_b fields are dead state that future maintainers may update incorrectly.

Prompt for your AI agent
File: src/raon/forward.rs
Line: 366
Symbol: new
Issue: MLA now keeps k_b/v_b and the new k_groups/v_groups, which may duplicate weight storage and leave the k_b/v_b fields unused. If group() copies the data, each of the 7 MLA layers stores the attn_k_b and attn_v_b weights twice, increasing memory use. If the forward path only reads the group vectors, the k_b and v_b fields are dead state that future maintainers may update incorrectly.
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/raon/forward.rs
})
} else {
let k_b = Mat::load_groups(g, &format!("blk.{il}.attn_k_b.weight"), cfg.n_head)?;
let v_b = Mat::load_groups(g, &format!("blk.{il}.attn_v_b.weight"), cfg.n_head)?;

@aletheore aletheore Bot Nov 24, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 42636b5e9662.


🟡 Medium · Correctness · 4 of 6

k_groups and v_groups are built from k_b and v_b before those are moved into the struct, which only compiles if group() returns an owned or 'a-lifetime Mat. If Mat::group borrows from &self, the move of k_b and v_b into MlaWeights fails borrow checking, so the crate does not build. If it does compile, a later change to the group lifetime could leave dangling views.

Prompt for your AI agent
File: src/raon/forward.rs
Line: 355
Symbol: new
Issue: k_groups and v_groups are built from k_b and v_b before those are moved into the struct, which only compiles if group() returns an owned or 'a-lifetime Mat. If Mat::group borrows from &self, the move of k_b and v_b into MlaWeights fails borrow checking, so the crate does not build. If it does compile, a later change to the group lifetime could leave dangling views.
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/raon/forward.rs
let (hc, n) = (self.cfg.hc, self.cfg.n_embd);
if hc <= 8 {
let mut col = [0.0f32; 8];
for j in 0..n {

@aletheore aletheore Bot Nov 24, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 42636b5e9662.


🔵 Low · Maintainability · 5 of 6

The residual-mix update is written twice

a fast path for hc<=8 and a fallback for larger hc, both computing the same result. A fix to the mixing formula must be made in both branches, and they can drift apart. The column-buffer version works for any hc with a Vec, so the split adds maintenance cost without a clear benefit.

Prompt for your AI agent
File: src/raon/forward.rs
Line: 459
Symbol: rda_step
Issue: The residual-mix update is written twice: a fast path for hc<=8 and a fallback for larger hc, both computing the same result. A fix to the mixing formula must be made in both branches, and they can drift apart. The column-buffer version works for any hc with a Vec, so the split adds maintenance cost without a clear benefit.
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/raon/forward.rs
pub fn set_effort(&mut self, effort: Option<&str>, think: bool) {
let next = self.cfg.effort_alpha_for(effort, think);
if (next - self.effort_alpha).abs() > 1e-6 && !self.toks.is_empty() {
// Prefix KV/RDA states were built under a different steering alpha; invalidate cache.

@aletheore aletheore Bot Nov 24, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 42636b5e9662.


🔵 Low · Performance · 6 of 6

Changing effort mid-conversation resets the whole KV and RDA prefix cache, forcing a full re-prefill of the history. A user alternates effort levels between turns. Each change calls reset(), so the entire conversation prefix is recomputed on every turn, even though only the steering alpha changed.

Prompt for your AI agent
File: src/raon/forward.rs
Line: 434
Symbol: hc_pre
Issue: Changing effort mid-conversation resets the whole KV and RDA prefix cache, forcing a full re-prefill of the history. A user alternates effort levels between turns. Each change calls reset(), so the entire conversation prefix is recomputed on every turn, even though only the steering alpha changed.
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
for i in 0..ne {
p.be.gemv(self.weight(p, &gs[i], &mut owned)?, p.x.addr(), at(i * 2 * nf)).ok()?;
p.be.gemv(self.weight(p, &us[i], &mut owned)?, p.x.addr(), at(i * 2 * nf + nf)).ok()?;
}

@aletheore aletheore Bot Nov 24, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 42636b5e9662.


🟠 High · Correctness · 1 of 7

situ_experts_split returns None mid-loop after queuing device work If self.weight(...) returns None on a later expert, the function returns None after gemv/situ commands for earlier experts were already queued against the shared p.y and p.x buffers. The caller then runs the fallback matvec_many_opt or CPU path, which can reuse those buffers while the queued kernels are still running, or read results from a partially written region. Nothing drains or resets the queue on this path.

Prompt for your AI agent
File: src/deepseek/mat.rs
Line: 340
Symbol: rows
Issue: situ_experts_split returns None mid-loop after queuing device work If self.weight(...) returns None on a later expert, the function returns None after gemv/situ commands for earlier experts were already queued against the shared p.y and p.x buffers. The caller then runs the fallback matvec_many_opt or CPU path, which can reuse those buffers while the queued kernels are still running, or read results from a partially written region. Nothing drains or resets the queue on this path.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

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

Comment thread src/deepseek/mat.rs
let mut off = 0;
for m in ms {
if m.gpu.is_some() || m.cols != cols || (!m.cpu && m.rows < 512) || cols % m.ty.block_elems() != 0 {
return None;

@aletheore aletheore Bot Nov 24, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 42636b5e9662.


🟠 High · Correctness · 2 of 7

matvec_many_cpu threshold changed from per-matrix to total rows The old code rejected the integer path when any non-cpu matrix had fewer than 512 rows. The new code checks total_rows instead, so a group of small experts whose summed rows reach 512 is routed to the quantized integer dot. That changes numerical output versus Mat::matvec and can move decode results away from the reference without any visible error.

Prompt for your AI agent
File: src/deepseek/mat.rs
Line: 560
Symbol: matvec_rows
Issue: matvec_many_cpu threshold changed from per-matrix to total rows The old code rejected the integer path when any non-cpu matrix had fewer than 512 rows. The new code checks total_rows instead, so a group of small experts whose summed rows reach 512 is routed to the quantized integer dot. That changes numerical output versus Mat::matvec and can move decode results away from the reference without any visible error.
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
if let Some(y) = matvec_many_cpu(ms, &slices) { return y; }
}
let mut y = vec![0f32; ms.iter().map(|m| m.rows).sum()];
if xs == 0 && ms.len() > 1 && std::env::var_os("STRATA_CPU_REF").is_none() {

@aletheore aletheore Bot Nov 24, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 42636b5e9662.


🔵 Low · Performance · 3 of 7

Environment variable read on every matvec call in hot path matvec_many, matvec_many_cpu and matvec_many_cpu_shared each call std::env::var_os("STRATA_CPU_REF") on every invocation. During decode this runs for every layer and every projection, adding syscall-free but locked environment lookups to the token loop. Reading it once into a OnceLock or a field on the model removes the cost.

Prompt for your AI agent
File: src/deepseek/mat.rs
Line: 506
Symbol: matvec_many_cpu
Issue: Environment variable read on every matvec call in hot path matvec_many, matvec_many_cpu and matvec_many_cpu_shared each call std::env::var_os("STRATA_CPU_REF") on every invocation. During decode this runs for every layer and every projection, adding syscall-free but locked environment lookups to the token loop. Reading it once into a OnceLock or a field on the model removes the cost.
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/raon/forward.rs
(all[..r].to_vec(), Some(all[r..].to_vec()))
} else {
let mut logits = vec![0.0f32; gate_inp.rows];
gate_inp.matvec(cur, &mut logits);

@aletheore aletheore Bot Nov 24, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 42636b5e9662.


🔵 Low · Performance · 4 of 7

STRATA_RAON_EVICT env var read per token per MoE layer ffn_step reads std::env::var_os("STRATA_RAON_EVICT") on every token for every MoE layer, and the batched prefill path reads it again per chunk. The value never changes during a run, so this adds repeated lookups in the hot path. Hoisting it to model construction removes the cost.

Prompt for your AI agent
File: src/raon/forward.rs
Line: 660
Symbol: step_opt
Issue: STRATA_RAON_EVICT env var read per token per MoE layer ffn_step reads std::env::var_os("STRATA_RAON_EVICT") on every token for every MoE layer, and the batched prefill path reads it again per chunk. The value never changes during a run, so this adds repeated lookups in the hot path. Hoisting it to model construction removes the cost.
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/raon/forward.rs
let gu = matvec_rows_sets(&[(*gate, 0), (*up, 0)], &normed_flat, nt);
let half = nt * gate.rows;
let gy: Vec<f32> = (0..half).map(|i| situ_glu(gu[i], gu[half + i], gb, vb)).collect();
let grefs: Vec<&[f32]> = gy.chunks_exact(gate.rows).collect();

@aletheore aletheore Bot Nov 24, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 42636b5e9662.


🔵 Low · Maintainability · 5 of 7

Debug and profiling env toggles left in production forward path STRATA_RAON_PROF instrumentation with Instant timers on every layer, STRATA_RAON_EVICT, and STRATA_CPU_REF branches are compiled into the release forward path. They add per-layer timing overhead and can silently change the execution path (CPU vs GPU, eviction) if the variables are set in a user environment. These belong behind a debug feature or a config option, not environment variables read during inference.

Prompt for your AI agent
File: src/raon/forward.rs
Line: 960
Symbol: prefill
Issue: Debug and profiling env toggles left in production forward path STRATA_RAON_PROF instrumentation with Instant timers on every layer, STRATA_RAON_EVICT, and STRATA_CPU_REF branches are compiled into the release forward path. They add per-layer timing overhead and can silently change the execution path (CPU vs GPU, eviction) if the variables are set in a user environment. These belong behind a debug feature or a config option, not environment variables read during inference.
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
});
Some(y)
}

@aletheore aletheore Bot Nov 24, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 42636b5e9662.


🔵 Low · Maintainability · 6 of 7

matvec_many_cpu_shared duplicates matvec_many_cpu logic matvec_many_cpu_shared repeats the validation, dot-selection, starts-table and Rayon chunk loop of matvec_many_cpu. The two already disagree: the shared version applies the 512-row guard per matrix while matvec_many_cpu uses total_rows. Any future fix to one must be mirrored by hand, and the divergence means the two functions can select different code paths for equivalent inputs. matvec_many_cpu could be expressed as the shared version applied per input.

Prompt for your AI agent
File: src/deepseek/mat.rs
Line: 580
Symbol: matvec_rows_many
Issue: matvec_many_cpu_shared duplicates matvec_many_cpu logic matvec_many_cpu_shared repeats the validation, dot-selection, starts-table and Rayon chunk loop of matvec_many_cpu. The two already disagree: the shared version applies the 512-row guard per matrix while matvec_many_cpu uses total_rows. Any future fix to one must be mirrored by hand, and the divergence means the two functions can select different code paths for equivalent inputs. matvec_many_cpu could be expressed as the shared version applied per input.
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
});
return;
}
if self.ty == GgmlType::F32 {

@aletheore aletheore Bot Nov 24, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 42636b5e9662.


🔵 Low · Maintainability · 7 of 7

F32 and BF16 matvec branches copy the row-parallel dispatch The new F32 and BF16 branches each define a near-identical closure, the same rows<=64 serial/parallel split, and the same early return. Every change to the dispatch threshold or the scale handling must be made in three places, and the copies can drift. A single helper taking a per-row dot function would remove the duplication.

Prompt for your AI agent
File: src/deepseek/mat.rs
Line: 870
Issue: F32 and BF16 matvec branches copy the row-parallel dispatch The new F32 and BF16 branches each define a near-identical closure, the same rows<=64 serial/parallel split, and the same early return. Every change to the dispatch threshold or the scale handling must be made in three places, and the copies can drift. A single helper taking a per-row dot function would remove the duplication.
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/cpu_moe.rs
GgmlType::IQ4NL => Some(avx512::dot4_iq4nl),
GgmlType::IQ4XS => Some(avx512::dot4_iq4xs),
GgmlType::Q6K => Some(avx512::dot4_q6k),
_ => None,

@aletheore aletheore Bot Nov 24, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 42636b5e9662.


🟠 High · Correctness · 1 of 6

AVX-512 dispatch returns None for every other quant type instead of falling back to the existing int_dot4 path. With STRATA_AVX512 set, any expert or matrix of a type other than Q8_0, IQ4NL, IQ4XS or Q6K hits _ => None and returns before the AVX2 branch runs, so int_dot4 yields None where it used to return a working kernel. The caller then errors or takes a slow path for those tensors.

Prompt for your AI agent
File: src/cpu_moe.rs
Line: 1635
Symbol: batch_rows_match_individual_matvecs
Issue: AVX-512 dispatch returns None for every other quant type instead of falling back to the existing int_dot4 path. With STRATA_AVX512 set, any expert or matrix of a type other than Q8_0, IQ4NL, IQ4XS or Q6K hits `_ => None` and returns before the AVX2 branch runs, so int_dot4 yields None where it used to return a working kernel. The caller then errors or takes a slow path for those tensors.
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/raon/chat.rs
logits = next_logits;
for t in accepted {
out.push(t);
if !emit(&out, &mut shown) { return (out, false); }

@aletheore aletheore Bot Nov 24, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 42636b5e9662.


🟠 High · Correctness · 2 of 6

Early return (out, false) skips whatever the function did after the loop, unlike the original break. When the consumer's piece callback returns false during an accepted speculative token, the function returns immediately. Code that used to run after the old break (final flush or state reporting) is skipped, so the caller sees a truncated result or a wrong completion flag.

Prompt for your AI agent
File: src/raon/chat.rs
Line: 170
Symbol: generate
Issue: Early `return (out, false)` skips whatever the function did after the loop, unlike the original `break`. When the consumer's piece callback returns false during an accepted speculative token, the function returns immediately. Code that used to run after the old `break` (final flush or state reporting) is skipped, so the caller sees a truncated result or a wrong completion flag.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

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

Comment thread src/raon/forward.rs
.enumerate()
.for_each(|(h, ((((gh, sh), ((q0, q1), q2)), ((k0, k1), k2)), ((v0, v1), v2)))| {
let off = h * hd;
let mut q = [0.0f32; 128];

@aletheore aletheore Bot Nov 24, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 42636b5e9662.


🟠 High · Correctness · 3 of 6

Per-head stack buffers are hard-coded to 128 elements, but head_dim is a runtime config value. A Raon config with head_dim above 128 makes q[j] = qv or out_h[vi] = o index past the end of the fixed array inside the parallel closure, panicking mid-decode. Nothing checks hd against 128 at load time.

Prompt for your AI agent
File: src/raon/forward.rs
Line: 558
Symbol: rda_step
Issue: Per-head stack buffers are hard-coded to 128 elements, but head_dim is a runtime config value. A Raon config with head_dim above 128 makes `q[j] = qv` or `out_h[vi] = o` index past the end of the fixed array inside the parallel closure, panicking mid-decode. Nothing checks hd against 128 at load time.
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/raon/forward.rs Outdated
}
let out = rda_recurrent_step(&q, &k, &v, &log_alpha, &beta, &mut st.state, nh, hd);
if capture_snaps {
rda_snaps[t][il] = Some(st.clone());

@aletheore aletheore Bot Nov 24, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of aedf4c3292c8.


🔵 Low · Performance · 4 of 6

verify path clones the full RDA state for every token and every RDA layer, even though only one snapshot is ever used. Each draft verify copies nt × n_rda_layers × n_head × hd × hd floats. Only snaps[j] is used on mismatch, so most of those copies are wasted work and memory traffic on every speculative step.

Prompt for your AI agent
File: src/raon/forward.rs
Line: 917
Symbol: prefill_chunk
Issue: verify path clones the full RDA state for every token and every RDA layer, even though only one snapshot is ever used. Each draft verify copies nt × n_rda_layers × n_head × hd × hd floats. Only snaps[j] is used on mismatch, so most of those copies are wasted work and memory traffic on every speculative step.
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/cpu_moe.rs
/// four sums do not wait for each other. None where no such kernel exists; the caller then uses `int_dot`.
pub fn int_dot4(ty: GgmlType) -> Option<fn(&[u8], [&[Q8K]; 4]) -> [f32; 4]> {
#[cfg(all(target_arch = "x86_64", target_feature = "avx512f", target_feature = "avx512bw", target_feature = "avx512vnni", target_feature = "avx512vbmi"))]
if std::env::var_os("STRATA_SCALAR").is_none() && std::env::var_os("STRATA_AVX512").is_some() {

@aletheore aletheore Bot Nov 24, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 42636b5e9662.


🔵 Low · Performance · 5 of 6

int_dot4 reads environment variables on every call, including the STRATA_AVX512 toggle. int_dot4 runs for each matvec in the hot decode path. Each call does std::env::var_os lookups, which take a lock and allocate. That adds avoidable per-token overhead, and the dispatch decision could be made once and cached.

Prompt for your AI agent
File: src/cpu_moe.rs
Line: 1629
Symbol: batch_rows_match_individual_matvecs
Issue: int_dot4 reads environment variables on every call, including the STRATA_AVX512 toggle. int_dot4 runs for each matvec in the hot decode path. Each call does `std::env::var_os` lookups, which take a lock and allocate. That adds avoidable per-token overhead, and the dispatch decision could be made once and cached.
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/raon/forward.rs
.enumerate()
.for_each(|(h, ((((gh, sh), ((q0, q1), q2)), ((k0, k1), k2)), ((v0, v1), v2)))| {
let off = h * hd;
let mut q = [0.0f32; 128];

@aletheore aletheore Bot Nov 24, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 42636b5e9662.


🔵 Low · Maintainability · 6 of 6

The fused per-head decode pass reimplements the conv, L2-norm, decay and delta-rule recurrence that rda_recurrent_step and conv1d_step_silu already do. Prefill still goes through rda_recurrent_step while decode uses this copy. A future fix to one path, such as a decay or gate change, will silently leave the other path producing different results, and the two are hard to keep bit-identical.

Prompt for your AI agent
File: src/raon/forward.rs
Line: 558
Symbol: rda_step
Issue: The fused per-head decode pass reimplements the conv, L2-norm, decay and delta-rule recurrence that rda_recurrent_step and conv1d_step_silu already do. Prefill still goes through rda_recurrent_step while decode uses this copy. A future fix to one path, such as a decay or gate change, will silently leave the other path producing different results, and the two are hard to keep bit-identical.
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/raon/dflash.rs
for s in &mut scores { *s = (*s - mx).exp(); sum += *s; }
let inv = 1.0 / sum;
for (si, &s) in scores[..n_ctx].iter().enumerate() {
let w = s * inv;

@aletheore aletheore Bot Nov 24, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 42636b5e9662.


🟠 High · Correctness · 1 of 6

Argmax fallback unwraps partial_cmp, so any NaN logit panics the decode. If the target lm_head produces a NaN logit for some draft position, partial_cmp(...).unwrap() returns None and the process panics mid-generation, aborting the generate/chat run. Using total_cmp, as the selector branch already does, avoids this.

Prompt for your AI agent
File: src/raon/dflash.rs
Line: 345
Issue: Argmax fallback unwraps partial_cmp, so any NaN logit panics the decode. If the target lm_head produces a NaN logit for some draft position, `partial_cmp(...).unwrap()` returns None and the process panics mid-generation, aborting the `generate`/`chat` run. Using `total_cmp`, as the selector branch already does, avoids this.
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/raon/chat.rs
dflash.commit_ctx(&feats);
let t1 = std::time::Instant::now();
let blk = std::env::var("STRATA_DFLASH_BLOCK")
.ok()

@aletheore aletheore Bot Nov 24, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 42636b5e9662.


🟠 High · Correctness · 2 of 6

clamp(2, block_size) panics when the GGUF block_size is below 2. usize::clamp panics when min > max. If the drafter GGUF sets dflash.block_size to 0 or 1 (the loader defaults only when the key is missing), or STRATA_DFLASH_BLOCK is set and block_size is small, the first decode step panics. The bound should be guarded, for example .max(2).min(block_size.max(2)), or validated once at load.

Prompt for your AI agent
File: src/raon/chat.rs
Line: 176
Symbol: decode
Issue: clamp(2, block_size) panics when the GGUF block_size is below 2. `usize::clamp` panics when min > max. If the drafter GGUF sets `dflash.block_size` to 0 or 1 (the loader defaults only when the key is missing), or STRATA_DFLASH_BLOCK is set and block_size is small, the first decode step panics. The bound should be guarded, for example `.max(2).min(block_size.max(2))`, or validated once at load.
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/raon/chat.rs
if let Some(dflash) = df.as_deref_mut() && rem >= 2 {
let t0 = std::time::Instant::now();
let feats = m.take_pending_feats();
dflash.commit_ctx(&feats);

@aletheore aletheore Bot Nov 24, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 42636b5e9662.


🔵 Low · Performance · 3 of 6

STRATA_DFLASH_BLOCK env var is parsed on every decode step. std::env::var plus parse runs once per generated speculative step, adding string and allocation work to the hot decode loop. The value is constant for the process, so it should be read once in generate/chat and stored in RaonDFlash or passed in.

Prompt for your AI agent
File: src/raon/chat.rs
Line: 173
Symbol: decode
Issue: STRATA_DFLASH_BLOCK env var is parsed on every decode step. `std::env::var` plus parse runs once per generated speculative step, adding string and allocation work to the hot decode loop. The value is constant for the process, so it should be read once in `generate`/`chat` and stored in `RaonDFlash` or passed 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/raon/dflash.rs
let mut att = vec![0.0f32; b_len * nh * hd];
att.par_chunks_mut(hd).enumerate().for_each(|(idx, oh)| {
let (t, qh) = (idx / nh, idx % nh);
let kh = qh / gqa;

@aletheore aletheore Bot Nov 24, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 42636b5e9662.


🔵 Low · Performance · 4 of 6

Candidate array rebuilt over the full vocabulary for every draft position. For each of the up to k_eff positions, cands is cleared and refilled with all ~260k vocabulary entries before selection, costing O(vocab) memory writes per position on every drafting step. Selecting top-k directly from the row slice, or reusing one buffer with select_nth_unstable on indices, would cut that work.

Prompt for your AI agent
File: src/raon/dflash.rs
Line: 325
Issue: Candidate array rebuilt over the full vocabulary for every draft position. For each of the up to k_eff positions, `cands` is cleared and refilled with all ~260k vocabulary entries before selection, costing O(vocab) memory writes per position on every drafting step. Selecting top-k directly from the row slice, or reusing one buffer with `select_nth_unstable` on indices, would cut that 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/raon/dflash.rs
eps,
rope_base,
conv_k,
conv_gs,

@aletheore aletheore Bot Nov 24, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 42636b5e9662.


🔵 Low · Performance · 5 of 6

Per-layer full clone of the hidden buffer in draft_block. When the conv path is absent, (h.clone(), None) allocates a new b_len * n_embd buffer for every layer and FFN sub-block on every drafting step, when the conv branch could write into a reusable scratch buffer. This adds allocation churn in the speculative loop.

Prompt for your AI agent
File: src/raon/dflash.rs
Line: 200
Issue: Per-layer full clone of the hidden buffer in draft_block. When the conv path is absent, `(h.clone(), None)` allocates a new `b_len * n_embd` buffer for every layer and FFN sub-block on every drafting step, when the conv branch could write into a reusable scratch buffer. This adds allocation churn in the speculative 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.

Comment thread src/raon/dflash.rs
pub fn reset(&mut self) {
for k in &mut self.k_cache { k.clear(); }
for v in &mut self.v_cache { v.clear(); }
self.ctx_len = 0;

@aletheore aletheore Bot Nov 24, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 42636b5e9662.


🔵 Low · Maintainability · 6 of 6

Q/K per-head RMSNorm and RoPE loops duplicated between commit_ctx and draft_block. The per-head rms_norm_w + rope_neox_inplace pattern for K appears in both commit_ctx and draft_block, with the same eps and rope base. A change to one (for example the norm placement or rope base) can silently diverge the cached context keys from the block keys. A shared helper would keep them consistent.

Prompt for your AI agent
File: src/raon/dflash.rs
Line: 216
Issue: Q/K per-head RMSNorm and RoPE loops duplicated between commit_ctx and draft_block. The per-head `rms_norm_w` + `rope_neox_inplace` pattern for K appears in both `commit_ctx` and `draft_block`, with the same eps and rope base. A change to one (for example the norm placement or rope base) can silently diverge the cached context keys from the block keys. A shared helper would keep them consistent.
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

Copy link
Copy Markdown
Member

Hi, ty for this, it's a big one! I merged it with main on my side and fixed some things: two changes in deepseek/mat.rs changed the CPU math for the other models (the 512 rows check and the bf16 sum), so I put them back, and a few panics on bad input in the raon code. On my 3060 with IQ4_XS it loads and check is ok, bench gives 76.6 / 26.1 tok/s prefill / decode at 512 and 56.3 / 18.9 at 4096. Two things I want to check before merge: the gating func from the file is never read (always sigmoid), and the effort steering (alpha * ffn_effort_steer) is not in the krafton llama.cpp graph. Do you know if the default alpha is 0? If it's not, the output will differ from llama.cpp. After a parity run I will merge it

Comment thread src/raon/forward.rs
let d_inner = nh * hd;
// Run heavy Q/K/V/G on GPU (or 1-shot CPU) while tiny BF16 beta/rda/f_a/f_b overlap on CPU.
let (qkvg, (beta_raw, rda_delta, mut decay)) = rayon::join(
|| matvec_many(&[r.wq, r.wk, r.wv, r.g], cur, 0),

@aletheore aletheore Bot Nov 25, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 42636b5e9662.


🟠 High · Correctness · 1 of 5

rayon::join runs GPU matvec_many on a worker thread while CPU matvecs run on another; GPU backend state may be thread-affine or not Send/Sync. If the GPU backend's handles or command queue are thread-local or not Send/Sync, the closure capturing r.wq/r.wk/r.wv/r.g will fail to compile, or submitting GPU work from a rayon worker can use the wrong context and produce corrupt or hung results at runtime.

Prompt for your AI agent
File: src/raon/forward.rs
Line: 559
Symbol: rda_step
Issue: rayon::join runs GPU matvec_many on a worker thread while CPU matvecs run on another; GPU backend state may be thread-affine or not Send/Sync. If the GPU backend's handles or command queue are thread-local or not Send/Sync, the closure capturing r.wq/r.wk/r.wv/r.g will fail to compile, or submitting GPU work from a rayon worker can use the wrong context and produce corrupt or hung results at runtime.
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/raon/forward.rs
let hcw = |p: &str| -> Result<Hcw<'a>> {
Ok(Hcw {
// Tiny [10240, 17] BF16 hyper-connection projections: faster on CPU (0.07 ms, zero GPU syncs).
f: Mat::load_host(g, &format!("{p}_fn.weight"))?,

@aletheore aletheore Bot Nov 25, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 42636b5e9662.


🟠 High · Correctness · 2 of 5

Hcw.f switched to host-only Mat; any caller that dispatches it through the GPU path may now fail. If hc_pre or hc_post call Mat::matvec expecting a device buffer, a host-only Mat either panics or silently reads an unset device pointer, breaking the Raon-mHC mixing for every layer.

Prompt for your AI agent
File: src/raon/forward.rs
Line: 374
Symbol: new
Issue: Hcw.f switched to host-only Mat; any caller that dispatches it through the GPU path may now fail. If hc_pre or hc_post call Mat::matvec expecting a device buffer, a host-only Mat either panics or silently reads an unset device pointer, breaking the Raon-mHC mixing for every layer.
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/raon/forward.rs
let (nh, hd) = (self.cfg.n_head, self.cfg.rda_hd);
let d_inner = nh * hd;
let nrefs: Vec<&[f32]> = normed_flat.chunks_exact(n).collect();
let (qkvg, (b_all, d_all, fb_all)) = rayon::join(

@aletheore aletheore Bot Nov 25, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 42636b5e9662.


🔵 Low · Performance · 3 of 5

Prefill now runs beta/rda/f_a/f_b CPU matvecs serially inside the join, so the join gives little overlap while adding a second dispatch path. For long prompts the CPU branch computes four matvec_rows passes sequentially while the GPU branch is idle at the join, so prefill time is about the same as before but with extra complexity.

Prompt for your AI agent
File: src/raon/forward.rs
Line: 932
Symbol: prefill_chunk_opt
Issue: Prefill now runs beta/rda/f_a/f_b CPU matvecs serially inside the join, so the join gives little overlap while adding a second dispatch path. For long prompts the CPU branch computes four matvec_rows passes sequentially while the GPU branch is idle at the join, so prefill time is about the same as before but with extra complexity.
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/raon/forward.rs
}
Ffn::Moe { gate_inp, bias, gexps, uexps, dexps, shared, effort_steer } => {
let nrefs: Vec<&[f32]> = normed_flat.chunks_exact(n).collect();
let (logits_all, shared_gu) = if let Some((sg, su, _)) = shared {

@aletheore aletheore Bot Nov 25, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 42636b5e9662.


🔵 Low · Maintainability · 4 of 5

nrefs is rebuilt from normed_flat in the MoE block though an identical vector was already built in the attention block of the same forward pass. Each prefill layer allocates and fills the same Vec of slice references twice, a small but avoidable per-layer cost that should be computed once and reused.

Prompt for your AI agent
File: src/raon/forward.rs
Line: 1092
Symbol: prefill_chunk_opt
Issue: nrefs is rebuilt from normed_flat in the MoE block though an identical vector was already built in the attention block of the same forward pass. Each prefill layer allocates and fills the same Vec of slice references twice, a small but avoidable per-layer cost that should be computed once and reused.
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/raon/forward.rs
let (qkvg, (beta_raw, rda_delta, mut decay)) = rayon::join(
|| matvec_many(&[r.wq, r.wk, r.wv, r.g], cur, 0),
|| {
let mut br = vec![0.0f32; r.beta.rows];

@aletheore aletheore Bot Nov 25, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No longer detected as of 42636b5e9662.


🔵 Low · Performance · 5 of 5

Decode now spawns a rayon join per layer for sub-0.1 ms CPU matvecs, adding task overhead on the per-token hot path. With 25 layers per token, the scheduling cost of the join and the CPU closures can match or exceed the saved time on the tiny matvecs, so per-token latency does not improve as the comment claims.

Prompt for your AI agent
File: src/raon/forward.rs
Line: 561
Symbol: rda_step
Issue: Decode now spawns a rayon join per layer for sub-0.1 ms CPU matvecs, adding task overhead on the per-token hot path. With 25 layers per token, the scheduling cost of the join and the CPU closures can match or exceed the saved time on the tiny matvecs, so per-token latency does not improve as the comment claims.
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.

Volt added 6 commits November 25, 2026 20:37
… parse_calls resilience, precomputed MLA groups & zero-alloc hc_post)
…py F32/BF16 & mixed-type matvec_many_cpu (+69% decode, +47% prefill)
…head RDA, and lossless N-gram verify_greedy (31.4 tok/s pp / 11.0 tok/s tg)
…tor), 1-pass parallel-over-experts CPU MoE & pooled RDA snapshots (33.8 tok/s pp, up to 16.8 tok/s decode)
…en) + concurrent CPU/GPU overlap in RDA & MoE
Comment thread src/deepseek/mat.rs
pub fn matvec_many_cpu_shared<'a>(ms: &[Mat<'a>], x: &[f32]) -> Option<Vec<f32>> {
if ms.is_empty() || std::env::var_os("STRATA_CPU_REF").is_some() { return None; }
let cols = x.len();
let mut dots = Vec::with_capacity(ms.len());

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

matvec_many_cpu_shared duplicates matvec_many_cpu almost line for line The eligibility loop, starts/dots build and parallel row loop are copied between matvec_many_cpu_shared and matvec_many_cpu, so a fix to one (for example the total_rows rule) is easily missed in the other and the two drift apart.

Prompt for your AI agent
File: src/deepseek/mat.rs
Line: 655
Symbol: load_groups
Issue: matvec_many_cpu_shared duplicates matvec_many_cpu almost line for line The eligibility loop, starts/dots build and parallel row loop are copied between matvec_many_cpu_shared and matvec_many_cpu, so a fix to one (for example the total_rows rule) is easily missed in the other and the two drift apart.
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
Ok(Mat { data, ty, rows, cols, cpu, gpu, scale })
}

/// Load a tensor strictly on the host mmap (never uploaded to VRAM, e.g. `token_embd.weight` read only via `row_into`).

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

Mat::load_host repeats Mat::load's parsing and scale lookup The dims, dtype and .scale lookup are re-implemented here, so a future change to how Mat::load reads scales or shapes will not reach load_host and the two loaders can disagree on the same tensor.

Prompt for your AI agent
File: src/deepseek/mat.rs
Line: 862
Issue: Mat::load_host repeats Mat::load's parsing and scale lookup The dims, dtype and .scale lookup are re-implemented here, so a future change to how Mat::load reads scales or shapes will not reach load_host and the two loaders can disagree on the same tensor.
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/raon/chat.rs
print!("{}", crate::term::prompt());
std::io::stdout().flush()?;
let mut line = String::new();
if stdin.lock().read_line(&mut line)? == 0 { break; }

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

chat() keeps the KV prefix but never resyncs the DFlash context, so draft positions drift. On a follow-up turn where the prefix is kept, df is not reset. Generated tokens from the previous turn were never committed to df, so df.ctx_len lags m.toks. New prompt features are then appended with shifted RoPE positions. Drafts are still verified, so output stays correct, but acceptance collapses and the speedup is lost silently.

Prompt for your AI agent
File: src/raon/chat.rs
Line: 262
Issue: chat() keeps the KV prefix but never resyncs the DFlash context, so draft positions drift. On a follow-up turn where the prefix is kept, df is not reset. Generated tokens from the previous turn were never committed to df, so df.ctx_len lags m.toks. New prompt features are then appended with shifted RoPE positions. Drafts are still verified, so output stays correct, but acceptance collapses and the speedup is lost silently.
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/raon/chat.rs
let start = from + text[from..].find(CALL_TAG)?;
let mut calls = Vec::new();
for block in text[start..].split(CALL_TAG).skip(1) {
let Some(inner) = block.split("</tool_call>").next() else { continue; };

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

decode re-detokenizes the whole output on every emitted token. emit() calls tok.decode(out) over all generated ids every step. For a 4k-token reply this is about 8M token-decodes in total, which adds visible latency to streaming and slows long generations.

Prompt for your AI agent
File: src/raon/chat.rs
Line: 128
Issue: decode re-detokenizes the whole output on every emitted token. emit() calls tok.decode(out) over all generated ids every step. For a 4k-token reply this is about 8M token-decodes in total, which adds visible latency to streaming and slows long generations.
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/raon/dflash.rs
let inv_freq = base.powf(-2.0 * i as f32 / hd as f32);
let ang = p * inv_freq;
let (si, co) = ang.sin_cos();
let (a, b) = (s[i], s[i + half]);

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

rope_neox_inplace recomputes base.powf per head and per position. The inv_freq powf sits inside the head loop, so each call does n_heads*half transcendental calls for the same frequencies. draft_block and commit_ctx call it per token, per layer, so a single block does tens of thousands of powf calls. A precomputed table of half entries would remove this.

Prompt for your AI agent
File: src/raon/dflash.rs
Line: 80
Issue: rope_neox_inplace recomputes base.powf per head and per position. The inv_freq powf sits inside the head loop, so each call does n_heads*half transcendental calls for the same frequencies. draft_block and commit_ctx call it per token, per layer, so a single block does tens of thousands of powf calls. A precomputed table of half entries would remove this.
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/raon/dflash.rs
let mut scores = Vec::with_capacity(total_kv);
let mut mx = f32::NEG_INFINITY;
for p in ctx_start..start {
let kv = &k_ctx[p * kv_dim + kh * hd..p * kv_dim + (kh + 1) * hd];

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Low · Performance

Selector scoring builds a full (index, logit) vector over the vocabulary at each position. For vocab around 250k, each draft position pushes about 250k (usize, f32) pairs and runs select_nth over them to keep 16. That allocation and pass repeats for every block position, which is wasteful next to the 16 candidates actually scored.

Prompt for your AI agent
File: src/raon/dflash.rs
Line: 330
Issue: Selector scoring builds a full (index, logit) vector over the vocabulary at each position. For vocab around 250k, each draft position pushes about 250k (usize, f32) pairs and runs select_nth over them to keep 16. That allocation and pass repeats for every block position, which is wasteful next to the 16 candidates actually scored.
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 cf45cda into RustingStudio:main Nov 26, 2026
5 checks passed
@Vasyl-Trefilov

Copy link
Copy Markdown
Member

Merged to main, big ty for this, it is a lot of work and Raon runs well here, on my 3060 it says Paris right away :) I added two small fixes on top bc of the shared CPU code: matvec_many_cpu takes the int dot per matrix again like Mat::matvec does, and the BF16 rows use the old one accumulator sum, so DeepSeek, GLM and others keep the same numbers as before. Also the greedy picks use ops::argmax now so a NaN logit does not panic, and a zero count in metadata is an error. The gating func is sigmoid in the file so that is fine. One thing I saw: the effort steering default is high (alpha 0.05) and the krafton llama.cpp graph does not have it, so our output can differ from llama.cpp a bit, if you know what the HF model does by default tell me pls. Ty again!

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