Skip to content

inkling2: batch host expert matvecs (with natural-prompt benchmarks) - #80

Merged
Vasyl-Trefilov merged 1 commit into
RustingStudio:mainfrom
sayampy:matvec-batched-host
Nov 23, 2026
Merged

Vasyl-Trefilov merged 1 commit into
RustingStudio:mainfrom
sayampy:matvec-batched-host

Conversation

@sayampy

@sayampy sayampy commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Batch the host experts of one Inkling 2 layer into a single Rayon pass.

run_experts currently calls Mat::matvec once per expert. Each call starts its own nested parallel loop and quantizes the activation again. matvec_many_cpu quantizes once and reads all weight rows in one sweep; the existing per-expert loop remains as a fallback for quant types with no integer dot kernel.

This is the matvec_many_cpu change from PR #74, rebased onto current main and measured on natural prose and a coding task rather than the repeating bench paragraph.

Benchmarks — RTX 3050 Laptop (4 GB), Inkling 2 Mini UD-Q3_K_XL

bench --prompt-file <natural prose> --pp 256 --tg 32 --reps 2, four interleaved A/B/B/A runs (baseline A = current main, B = this PR):

run decode A decode B prefill A prefill B
1a 5.5 7.5 39.9 46.2
1b 5.5 7.0 41.5 45.3
2a 5.6 7.5 41.3 35.3
2b 6.8 7.3 41.2 43.2

Decode improves ~25-36%; prefill is modestly better. Host-only (STRATA_DS_GPU=0) natural prose: decode 4.3 → 5.0 tok/s. A Go coding-task prompt: GPU hybrid decode 7.3 → 7.7 tok/s. The coding-task host-only case was flat (4.1 → 3.8), so the gain is prompt-shape dependent but consistently positive where the hybrid path actually uses host experts.

Quality

generate --temp 0 --seed 1 -n 48 with both the natural prose and Go coding prompts, with and without --gpu: byte-identical output to current main in all four cases (the helper returns the same sums, only the order of the parallel work changes).

Scope

Only src/deepseek/mat.rs (new helper) and src/inkling2/forward.rs (call site). No spec-decoding defaults, no draft-length changes, no KV changes, no docs moved.

Co-authored-by: HY4-Flash

`run_experts` computed each host expert with one `Mat::matvec` call, which
starts a nested Rayon pass per matrix and quantizes the activation once per
expert. `matvec_many_cpu` does all matrices in a single parallel sweep: the
activation is quantized once and the weight rows are read in the same pass.

Measured on RTX 3050 Laptop (4 GB), Inkling 2 Mini UD-Q3_K_XL, natural prose
prompt, `--pp 256 --tg 32`, interleaved A/B/A/B runs:
  GPU hybrid decode 5.5-5.6 -> 7.0-7.5 tok/s (+25-36%)
  GPU hybrid prefill ~40 -> ~45 tok/s
  Host-only natural decode 4.3 -> 5.0 tok/s
Zeros-temperature generation with natural prose and a Go coding task is
byte-identical to HEAD with and without --gpu.

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

aletheore Bot commented Nov 22, 2026

Copy link
Copy Markdown

🔍 Aletheore evidence diff

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

  • src/deepseek/mat.rs · modified · +25/-0 · +1 function · 9 other dependents
  • src/inkling2/forward.rs · modified · +15/-1 · 6 other dependents

No new secrets, vulnerabilities, or layer violations. ✅

Comment thread src/deepseek/mat.rs
}

/// The batched path of `matvec_many`, or None when the matrices cannot share one GPU batch (or batching is off).
/// Host integer dot of several matrices, one activation each, in a single Rayon pass.

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

New fn is inserted between matvec_many_opt's doc comment and its definition, so the doc now describes matvec_many_cpu and matvec_many_opt loses its doc. Rustdoc renders the batched-path description under matvec_many_cpu and leaves matvec_many_opt undocumented. Maintainers reading the docs or hovering in an IDE get the wrong description for both functions.

Prompt for your AI agent
File: src/deepseek/mat.rs
Line: 490
Symbol: matvec_many_opt
Issue: New fn is inserted between matvec_many_opt's doc comment and its definition, so the doc now describes matvec_many_cpu and matvec_many_opt loses its doc. Rustdoc renders the batched-path description under matvec_many_cpu and leaves matvec_many_opt undocumented. Maintainers reading the docs or hovering in an IDE get the wrong description for both functions.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

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

Comment thread src/inkling2/forward.rs
let downs: Vec<Mat> = list.iter().map(|e| e.1).collect();
let gs: Vec<f32> = list.iter().map(|e| e.3).collect();
let gx: Vec<&[f32]> = vec![x; list.len()];
if let Some(y) = matvec_many_cpu(&gus, &gx) {

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

Passing vec![x; n] makes matvec_many_cpu quantize the same activation n times, once per expert. With top-k experts per token, quantize_q8k runs on an identical input k times per layer per token, multiplying the Q8K quantization cost on the decode hot path. Quantizing x once and sharing the result would avoid it.

Prompt for your AI agent
File: src/inkling2/forward.rs
Line: 435
Symbol: run_experts
Issue: Passing vec![x; n] makes matvec_many_cpu quantize the same activation n times, once per expert. With top-k experts per token, quantize_q8k runs on an identical input k times per layer per token, multiplying the Q8K quantization cost on the decode hot path. Quantizing x once and sharing the result 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.

Comment thread src/inkling2/forward.rs
}
}
None => {
let gus: Vec<Mat> = list.iter().map(|e| e.0).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.

🟠 High · Correctness · 3 of 6

list.iter().map(|e| e.0) moves Mat out of a shared reference, which only compiles if Mat is Copy. If Mat is not Copy, the build fails with E0507 (cannot move out of a shared reference). Cloning or borrowing into a Vec<&Mat> would be needed.

Prompt for your AI agent
File: src/inkling2/forward.rs
Line: 431
Symbol: run_experts
Issue: list.iter().map(|e| e.0) moves Mat out of a shared reference, which only compiles if Mat is Copy. If Mat is not Copy, the build fails with E0507 (cannot move out of a shared reference). Cloning or borrowing into a Vec<&Mat> would be needed.
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 r = c * 32 + k;
let i = starts.partition_point(|(s, _)| *s <= r) - 1;
let (s, m) = starts[i];
*o = dot(&m.data[(r - s) * rb..(r - s + 1) * rb], &xq[i]) * m.scale;

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

Row slice m.data[(r-s)rb..] is indexed with no check that data holds rowsrb bytes. A Mat whose data buffer is shorter than rows*row_bytes (for example a truncated mmap or a mismatched cols/ty) makes the Rayon worker panic on an out-of-range slice, which aborts the whole forward pass instead of returning None and falling back.

Prompt for your AI agent
File: src/deepseek/mat.rs
Line: 509
Symbol: matvec_rows
Issue: Row slice m.data[(r-s)*rb..] is indexed with no check that data holds rows*rb bytes. A Mat whose data buffer is shorter than rows*row_bytes (for example a truncated mmap or a mismatched cols/ty) makes the Rayon worker panic on an out-of-range slice, which aborts the whole forward pass instead of returning None and falling back.
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

/// The batched path of `matvec_many`, or None when the matrices cannot share one GPU batch (or batching is off).
/// Host integer dot of several matrices, one activation each, in a single Rayon pass.
pub fn matvec_many_cpu<'a>(ms: &[Mat<'a>], xs: &[&[f32]]) -> Option<Vec<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 · 5 of 6

New integer-dot CPU path has no test comparing it against the float reference path. A wrong row-to-matrix mapping in the partition_point logic, or a scale error, would produce wrong expert outputs with no failing test. The PR title mentions benchmarks, but no correctness test appears in the diff.

Prompt for your AI agent
File: src/deepseek/mat.rs
Line: 491
Symbol: matvec_many_opt
Issue: New integer-dot CPU path has no test comparing it against the float reference path. A wrong row-to-matrix mapping in the partition_point logic, or a scale error, would produce wrong expert outputs with no failing test. The PR title mentions benchmarks, but no correctness test appears in the diff.
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 ty = ms.first()?.ty;
if ms.len() != xs.len() || ms.iter().any(|m| m.ty != ty || m.gpu.is_some() || m.cols != xs[0].len())
|| xs.iter().any(|x| x.len() != xs[0].len()) { return None; }
if std::env::var_os("STRATA_CPU_REF").is_some() || xs[0].len() % ty.block_elems() != 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 · Performance · 6 of 6

std::env::var_os(STRATA_CPU_REF) is read on every call to matvec_many_cpu in the per-token expert path. The environment is queried once per layer per token. Caching the flag in a OnceLock or passing it through the config would remove that repeated lookup.

Prompt for your AI agent
File: src/deepseek/mat.rs
Line: 495
Issue: std::env::var_os(STRATA_CPU_REF) is read on every call to matvec_many_cpu in the per-token expert path. The environment is queried once per layer per token. Caching the flag in a OnceLock or passing it through the config would remove that repeated lookup.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

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

@aletheore

aletheore Bot commented Nov 22, 2026

Copy link
Copy Markdown

Aletheore Flash Lite review

What this PR does. This PR adds a CPU path that computes integer dot products for multiple MoE expert matrices in one Rayon-parallel pass, and wires it into the Inkling2 run_experts fallback for gate/up and down projections. It affects CPU inference for the Inkling2 model and falls back to the existing per-expert loop when STRATA_CPU_REF is set or the types or shapes don't qualify. The title mentions natural-prompt benchmarks, but the diff contains no benchmark code.

Merge confidence Review effort Merge risk
3 / 5 1 / 5 Medium
Area Files Lines
src/deepseek 1 +25 −0
src/inkling2 1 +15 −1

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

# Severity Category Where
1 🟠 High Correctness mat.rs:490 New fn is inserted between matvec_many_opt's doc comment and its definition, so the doc now describes…
2 🔵 Low Performance forward.rs:435 Passing vec![x; n] makes matvec_many_cpu quantize the same activation n times, once per expert. With top-k…
3 🟠 High Correctness forward.rs:431 list.iter().map(|e| e.0) moves Mat out of a shared reference, which only compiles if Mat is Copy. If Mat is…
4 🟡 Medium Correctness mat.rs:509 Row slice m.data[(r-s)rb..] is indexed with no check that data holds rowsrb bytes. A Mat whose data buffer…
5 🔵 Low Maintainability mat.rs:491 New integer-dot CPU path has no test comparing it against the float reference path. A wrong row-to-matrix…
6 🔵 Low Performance mat.rs:495 std::env::var_os(STRATA_CPU_REF) is read on every call to matvec_many_cpu in the per-token expert path. The…
Review details

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

Fix all with your agent
File: src/deepseek/mat.rs
Line: 490
Symbol: matvec_many_opt
Issue: New fn is inserted between matvec_many_opt's doc comment and its definition, so the doc now describes matvec_many_cpu and matvec_many_opt loses its doc. Rustdoc renders the batched-path description under matvec_many_cpu and leaves matvec_many_opt undocumented. Maintainers reading the docs or hovering in an IDE get the wrong description for both functions.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/inkling2/forward.rs
Line: 435
Symbol: run_experts
Issue: Passing vec![x; n] makes matvec_many_cpu quantize the same activation n times, once per expert. With top-k experts per token, quantize_q8k runs on an identical input k times per layer per token, multiplying the Q8K quantization cost on the decode hot path. Quantizing x once and sharing the result would avoid it.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/inkling2/forward.rs
Line: 431
Symbol: run_experts
Issue: list.iter().map(|e| e.0) moves Mat out of a shared reference, which only compiles if Mat is Copy. If Mat is not Copy, the build fails with E0507 (cannot move out of a shared reference). Cloning or borrowing into a Vec<&Mat> would be needed.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/deepseek/mat.rs
Line: 509
Symbol: matvec_rows
Issue: Row slice m.data[(r-s)*rb..] is indexed with no check that data holds rows*rb bytes. A Mat whose data buffer is shorter than rows*row_bytes (for example a truncated mmap or a mismatched cols/ty) makes the Rayon worker panic on an out-of-range slice, which aborts the whole forward pass instead of returning None and falling back.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/deepseek/mat.rs
Line: 491
Symbol: matvec_many_opt
Issue: New integer-dot CPU path has no test comparing it against the float reference path. A wrong row-to-matrix mapping in the partition_point logic, or a scale error, would produce wrong expert outputs with no failing test. The PR title mentions benchmarks, but no correctness test appears in the diff.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/deepseek/mat.rs
Line: 495
Issue: std::env::var_os(STRATA_CPU_REF) is read on every call to matvec_many_cpu in the per-token expert path. The environment is queried once per layer per token. Caching the flag in a OnceLock or passing it through the config would remove that repeated lookup.
Make the smallest change that fixes this, add a test, and change nothing unrelated.
Blast radius: 53 other file(s) depend on what this PR changes (12 directly, 41 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/deepseek/mat.rs is imported by src/deepseek/forward.rs, src/deepseek/mod.rs, src/gemma4/forward.rs, src/glm/forward.rs (+5 more)
  • src/inkling2/forward.rs is imported by src/inkling2/chat.rs, src/inkling2/dspark.rs, src/inkling2/forward/device.rs, src/inkling2/mod.rs (+2 more)

Indirectly affected: examples/gguf_dump.rs, src/backend.rs, src/chat.rs, src/config.rs, src/cpu_moe.rs, src/cpu_worker.rs (+35 more)

@Vasyl-Trefilov
Vasyl-Trefilov merged commit bbd57c2 into RustingStudio:main Nov 23, 2026
5 checks passed
@Vasyl-Trefilov

Copy link
Copy Markdown
Member

Hi, Hi, ty for PR
RTX 3060, Inkling 2 Mini IQ4_NL, warm, same build flags:

  • every expert on the host: decode 10.7-11.1 -> 11.3-11.7 tok/s
  • 40% of the free VRAM for the weights: decode 8.3-10.6 -> 10.4-12.4 tok/s (noisy, but the PR was ahead in each of the three pairs)

Greedy output is byte-identical to main, host-only and with --gpu.

Two things I changed in the merge:

  • matvec_many_cpu sat between the doc comment of matvec_many_opt and the function, so the comment moved to the wrong function. Put it back.
  • added tests/quant.rs::matvec_many_cpu_matches_matvec: three Q8_0 matrices with 5, 40 and 33 rows, the batch must give the same bits as Mat::matvec.
    Ty again!

@sayampy

sayampy commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Hi, Hi, ty for PR RTX 3060, Inkling 2 Mini IQ4_NL, warm, same build flags:

* every expert on the host: decode 10.7-11.1 -> 11.3-11.7 tok/s

* 40% of the free VRAM for the weights: decode 8.3-10.6 -> 10.4-12.4 tok/s (noisy, but the PR was ahead in each of the three pairs)

Greedy output is byte-identical to main, host-only and with --gpu.

Two things I changed in the merge:

* matvec_many_cpu sat between the doc comment of matvec_many_opt and the function, so the comment moved to the wrong function. Put it back.

* added tests/quant.rs::matvec_many_cpu_matches_matvec: three Q8_0 matrices with 5, 40 and 33 rows, the batch must give the same bits as Mat::matvec.
  Ty again!

Thanks to you for pointing those out and fixing it! Kudos

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