Skip to content

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

Open
ybenyedder wants to merge 5 commits into
RustingStudio:mainfrom
ybenyedder:feat/raon-1-mini
Open

ybenyedder wants to merge 5 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["model.rs"]
    n27["ngram.rs"]
    n28["serve.rs"]
    n29["preflight.rs"]
    n30["weights.rs"]
    n31["tests/cpu_moe.rs"]
    n32["tests/gguf.rs"]
    n33["quant.rs"]
    n34["vision.rs"]
    n0 --> n16
    n0 --> n26
    n0 --> n30
    n0 --> n32
    n0 --> n33
    n1 --> n5
    n1 --> n11
    n1 --> n31
    n1 --> n33
    n2 --> n8
    n2 --> n9
    n2 --> n11
    n2 --> n14
    n2 --> n19
    n2 --> n22
    n2 --> n23
    n2 --> n24
    n2 --> n33
    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 --> n27
    n3 --> n28
    n3 --> n29
    n3 --> n30
    n4 --> n12
    n4 --> n15
    n4 --> n27
    n4 --> n34
    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
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 · 4 other dependents
  • src/deepseek/mat.rs · modified · +173/-13 · +4 functions · 9 other dependents
  • src/lib.rs · modified · +1/-0 · 18 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 · +1452/-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: 5

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

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

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

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

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

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

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 · 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 pull request adds a DFlash2 block-diffusion drafter for KRAFTON Raon-1 mini and wires it into the generate and chat commands as an optional draft_model for speculative decoding. The shown diff covers only the drafter and its CLI plumbing, though the title also claims mHC, RDA, gated NoPE MLA, SiTU-GLU MoE, and effort steering, which are not visible in the excerpt. The change affects users of the raon1 model path who pass a draft model, while serve continues to decode without speculation.

Merge confidence Review effort Merge risk
2 / 5 4 / 5 Medium
Area Files Lines
src/raon 4 +716 −22
src 1 +2 −2

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

# Severity Category Where
1 🟠 High Correctness dflash.rs:345 Argmax fallback unwraps partial_cmp, so any NaN logit panics the decode. If the target lm_head produces a NaN…
2 🟠 High Correctness chat.rs:176 clamp(2, block_size) panics when the GGUF block_size is below 2. usize::clamp panics when min > max. If the…
3 🔵 Low Performance chat.rs:173 STRATA_DFLASH_BLOCK env var is parsed on every decode step. std::env::var plus parse runs once per…
4 🔵 Low Performance dflash.rs:325 Candidate array rebuilt over the full vocabulary for every draft position. For each of the up to k_eff…
5 🔵 Low Performance dflash.rs:200 Per-layer full clone of the hidden buffer in draft_block. When the conv path is absent, (h.clone(), None)…
6 🔵 Low Maintainability dflash.rs:216 Q/K per-head RMSNorm and RoPE loops duplicated between commit_ctx and draft_block. The per-head rms_norm_w…
- 🟠 High Correctness chat.rs:216 Earlier finding, still open
- 🟠 High Correctness chat.rs:266 Earlier finding, still open
- 🔵 Low Performance chat.rs:193 Earlier finding, still open
- 🔵 Low Maintainability forward.rs:663 Earlier finding, still open
- 🔵 Low Performance forward.rs:538 Earlier finding, still open
- 🔵 Low Performance forward.rs:443 Earlier finding, still open
- 🟠 High Correctness chat.rs:129 Earlier finding, still open
- 🟠 High Correctness chat.rs:206 Earlier finding, still open
- 🔵 Low Maintainability forward.rs:366 Earlier finding, still open
- 🟡 Medium Correctness forward.rs:355 Earlier finding, still open
- 🔵 Low Maintainability forward.rs:459 Earlier finding, still open
- 🔵 Low Performance forward.rs:434 Earlier finding, still open
- 🟠 High Correctness mat.rs:340 Earlier finding, still open
- 🟠 High Correctness mat.rs:560 Earlier finding, still open
- 🔵 Low Performance mat.rs:506 Earlier finding, still open
- 🔵 Low Performance forward.rs:660 Earlier finding, still open
- 🔵 Low Maintainability forward.rs:960 Earlier finding, still open
- 🔵 Low Maintainability mat.rs:580 Earlier finding, still open
- 🔵 Low Maintainability mat.rs:870 Earlier finding, still open
- 🟠 High Correctness cpu_moe.rs:1635 Earlier finding, still open
- 🟠 High Correctness chat.rs:170 Earlier finding, still open
- 🟠 High Correctness forward.rs:558 Earlier finding, still open
- 🔵 Low Performance cpu_moe.rs:1629 Earlier finding, still open
- 🔵 Low Maintainability forward.rs:558 Earlier finding, still open
Review details

Reviewed 5 file(s); skipped 0. Dismissed 0; outside PR diff 0. Grounding: 6 of 6 proposed finding(s).

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

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.

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.

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.

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.

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.
Blast radius: 50 other file(s) depend on what this PR changes (2 directly, 48 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/raon/mod.rs is imported by src/config.rs, src/lib.rs

Indirectly affected: examples/gguf_dump.rs, src/backend.rs, src/chat.rs, src/cpu_moe.rs, src/cpu_worker.rs, src/cuda/mod.rs (+42 more)

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

… parse_calls resilience, precomputed MLA groups & zero-alloc hc_post)
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; };

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

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

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

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,

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

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

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

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

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.

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

…py F32/BF16 & mixed-type matvec_many_cpu (+69% decode, +47% prefill)
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()?;
}

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

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 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() {

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

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

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

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

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

…head RDA, and lossless N-gram verify_greedy (31.4 tok/s pp / 11.0 tok/s tg)
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,

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

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

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

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

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 · 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() {

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

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

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.

…tor), 1-pass parallel-over-experts CPU MoE & pooled RDA snapshots (33.8 tok/s pp, up to 16.8 tok/s decode)
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;

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

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

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

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

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

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

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,

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

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

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

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