Skip to content

Use quantized matvec kernels for CPU generation - #112

Merged
Vasyl-Trefilov merged 2 commits into
RustingStudio:mainfrom
marcomartini97:fix/cpu-quantized-generation
Nov 26, 2026
Merged

Vasyl-Trefilov merged 2 commits into
RustingStudio:mainfrom
marcomartini97:fix/cpu-quantized-generation

Conversation

@marcomartini97

@marcomartini97 marcomartini97 commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Reuse the CPU quantized dot products for generation, chat, serving, and benchmarking. Keep the floating-point reference path for score and perplexity.

What changed and why

CPU generation was especially slow on low-power devices because it dequantized model weights to floating point for every token. This change enables the existing quantized matrix-vector kernels for CPU generate, chat, serve, and bench. CPU score and perplexity still use the reference path for numerical comparisons.

EDIT: Made the quantized CPU generation opt-in: preserve reference logits by default and centralize --fast-cpu selection in the inference loader. Use integer kernels for supported aligned projections and reuse quantized activations across FFN and MTP projections.

Verification

Benchmarked Qwen3.5-4B-Claude-4.6-OS-Auto-Variable-HERETIC-UNCENSORED-THINKING.Q2_K.gguf on an Intel Core i5-8365U with eight CPU threads and identical flags for both binaries.

Went from 0.6tps prefill and 0.4tps decode to 5.7tps and 5.5tps respectively

Checklist

  • Ran the CPU kernel tests and verified the server with the reported model.

Reuse the CPU quantized dot products for generation, chat, serving, and benchmarking. Keep the floating-point reference path for score and perplexity.
Comment thread src/model.rs Outdated
fn mv(&self, t: &Tensor, x: &[f32]) -> Vec<f32> {
let mut y = vec![0f32; t.rows];
if self.fast_matvec {
crate::cpu_moe::matvec(t, x, &mut y);

@aletheore aletheore Bot Nov 26, 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 8f6f6b07e204.


🟠 High · Correctness · 1 of 6

Fast path calls cpu_moe::matvec with no check on dtype or row width, unlike the f32 fallback. Q8_K quantization works on 256-element blocks and k-quant weights. For a tensor whose input width is not a multiple of 256, or whose weight type is F32/F16 (for example an unquantized ssm_alpha or indexer projection), cpu_moe::matvec panics or returns wrong values. The old t.matvec handled these cases, so the same model loads and runs on the old path but fails on CPU after this change.

Prompt for your AI agent
File: src/model.rs
Line: 111
Symbol: load_with_aux
Issue: Fast path calls cpu_moe::matvec with no check on dtype or row width, unlike the f32 fallback. Q8_K quantization works on 256-element blocks and k-quant weights. For a tensor whose input width is not a multiple of 256, or whose weight type is F32/F16 (for example an unquantized ssm_alpha or indexer projection), cpu_moe::matvec panics or returns wrong values. The old t.matvec handled these cases, so the same model loads and runs on the old path but fails on CPU after this change.
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/model.rs Outdated

fn mv(&self, t: &Tensor, x: &[f32]) -> Vec<f32> {
let mut y = vec![0f32; t.rows];
if self.fast_matvec {

@aletheore aletheore Bot Nov 26, 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 8f6f6b07e204.


🔵 Low · Maintainability · 2 of 6

Quantized activations are now the default for every CPU run, with no accuracy check or test. Every CPU generation now quantizes activations to Q8_K for attention, SSM, router, shared expert, MTP and the output head. Logits shift slightly for all models, and greedy decoding can pick different tokens after a few steps. Nothing in the diff adds a regression test or tolerance check that would catch this.

Prompt for your AI agent
File: src/model.rs
Line: 110
Symbol: load_with_lora
Issue: Quantized activations are now the default for every CPU run, with no accuracy check or test. Every CPU generation now quantizes activations to Q8_K for attention, SSM, router, shared expert, MTP and the output head. Logits shift slightly for all models, and greedy decoding can pick different tokens after a few steps. Nothing in the diff adds a regression test or tolerance check that would catch 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/model.rs Outdated
None
};
let mut m = Model { cfg, w, loras: Vec::new(), draft_model, ple };
let mut m = Model { cfg, w, loras: Vec::new(), draft_model, ple, fast_matvec: false };

@aletheore aletheore Bot Nov 26, 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 8f6f6b07e204.


🔵 Low · Maintainability · 3 of 6

Flag is set after construction and after apply_lora, so the fast path is not threaded through loading. The constructor sets fast_matvec: false and apply_lora(loras) runs inside load_with_lora before with_fast_matvec is called. Any matvec during LoRA application therefore uses the slow path. A LoRA model loaded through run() and the same model served through serve_model can then produce different numbers. Any load path that is not updated silently keeps the slow kernel.

Prompt for your AI agent
File: src/model.rs
Line: 294
Symbol: apply_lora
Issue: Flag is set after construction and after apply_lora, so the fast path is not threaded through loading. The constructor sets fast_matvec: false and apply_lora(loras) runs inside load_with_lora before with_fast_matvec is called. Any matvec during LoRA application therefore uses the slow path. A LoRA model loaded through run() and the same model served through serve_model can then produce different numbers. Any load path that is not updated silently keeps the slow kernel.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

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

Comment thread src/main.rs
let m = Model::load_with_aux(&g, aux_g.as_ref(), &engine.lora_specs())?;
let m = Model::load_with_aux(&g, aux_g.as_ref(), &engine.lora_specs())?
.with_fast_matvec(!engine.gpu);
let tok = Tokenizer::from_gguf(&g)?;

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

The same load-then-set-flag chain is copied into four call sites. Each of the four sites (three in run, one in serve_model) repeats load_with_aux followed by .with_fast_matvec(!engine.gpu). A future load site that omits the call silently gets the slow path, and the GPU-to-CPU mapping lives in four places. Passing the flag into Model::load_with_aux once would remove the duplication.

Prompt for your AI agent
File: src/main.rs
Line: 1370
Symbol: run
Issue: The same load-then-set-flag chain is copied into four call sites. Each of the four sites (three in run, one in serve_model) repeats load_with_aux followed by .with_fast_matvec(!engine.gpu). A future load site that omits the call silently gets the slow path, and the GPU-to-CPU mapping lives in four places. Passing the flag into Model::load_with_aux once 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/model.rs Outdated
let mut a = mv(gate, h);
for (x, u) in a.iter_mut().zip(mv(up, h)) { *x = ops::silu(*x) * u; }
let mut y = match rot { Some(r) => mv(down, &r.rotated(&a)), None => mv(down, &a) };
let mut a = self.mv(gate, h);

@aletheore aletheore Bot Nov 26, 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 8f6f6b07e204.


🔵 Low · Performance · 5 of 6

gate and up projections each quantize the same activation h separately. The FFN computes self.mv(gate, h) and then self.mv(up, h). With the fast path, each call quantizes h to Q8_K again, which doubles the quantization work on every FFN layer of every token. Quantizing h once and reusing it for both matvecs would remove the repeat.

Prompt for your AI agent
File: src/model.rs
Line: 820
Symbol: dense_ffn
Issue: gate and up projections each quantize the same activation h separately. The FFN computes self.mv(gate, h) and then self.mv(up, h). With the fast path, each call quantizes h to Q8_K again, which doubles the quantization work on every FFN layer of every token. Quantizing h once and reusing it for both matvecs would remove the repeat.
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/model.rs
@@ -633,15 +644,15 @@ impl<'a> Model<'a> {
let mut hn = vec![0f32; hid.len()];
self.gnorm(hid, &self.f(il, "nextn.hnorm.weight"), &mut hn);
let proj = self.t(il, "nextn.eh_proj.weight");

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

MTP projection runs one matvec per chunk and rebuilds the concatenated input each time. The flat_map calls self.mv once per chunk of hn, and each call allocates a new concatenated [e, h] vector and re-quantizes it on the fast path. With the Q8_K path enabled, the quantization cost scales with chunk count and nothing is shared across chunks. Batching the chunks into one matvec or quantizing e once would reduce the repeated work.

Prompt for your AI agent
File: src/model.rs
Line: 646
Issue: MTP projection runs one matvec per chunk and rebuilds the concatenated input each time. The flat_map calls self.mv once per chunk of hn, and each call allocates a new concatenated [e, h] vector and re-quantizes it on the fast path. With the Q8_K path enabled, the quantization cost scales with chunk count and nothing is shared across chunks. Batching the chunks into one matvec or quantizing e once would reduce the repeated 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.

@aletheore

aletheore Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Aletheore Flash Lite review

What this PR does. This PR adds an opt-in --fast-cpu flag that runs CPU inference matrix-vector products through quantized Q8_K integer kernels, with activations shared across projections and a quantized path for the MTP projection. It also refactors model loading into load_with_matvec and load_inference_model, and moves the make_qwen3 test fixture to module scope. The change affects people running CPU generation, serving, or benchmarking, and developers calling the Model loading API; the default behavior and GPU path are unchanged, but enabling the flag can alter logits and generated tokens.

Merge confidence Review effort Merge risk
3 / 5 3 / 5 Medium
Area Files Lines
src 3 +190 −80

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

# Severity Category Where
1 🟠 High Correctness main.rs:34 New --fast-cpu flag defaults to off, so default CPU generation loses the quantized kernels the PR enables…
2 🔵 Low Maintainability main.rs:4333 CPU parity test returns early and passes silently when the env var is unset. Without STRATA_CPU_PARITY_MODEL…
3 🔵 Low Maintainability main.rs:4350 Final assertion compares two identically configured models, so it checks nothing. expected is built with…
4 🟡 Medium Correctness model.rs:113 New unconditional assert_eq on dimensions in the mv hot path can panic. Any caller that passes an input slice…
- 🔵 Low Maintainability main.rs:1370 Earlier finding, still open
- 🔵 Low Performance model.rs:646 Earlier finding, still open
Review details

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

Fix all with your agent
File: src/main.rs
Line: 34
Symbol: Engine
Issue: New --fast-cpu flag defaults to off, so default CPU generation loses the quantized kernels the PR enables. Before this push, CPU generate/chat/serve/bench used with_fast_matvec(!engine.gpu), so the quantized kernels ran by default. Now load_inference_model only enables them when the bool --fast-cpu is passed. A user running the reported model with the same flags as before gets the floating-point path again, so the claimed 0.6 to 5.7 tps prefill and 0.4 to 5.5 tps decode gain does not occur.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/main.rs
Line: 4333
Symbol: meta
Issue: CPU parity test returns early and passes silently when the env var is unset. Without STRATA_CPU_PARITY_MODEL set, the test returns immediately and reports success. CI never checks that CPU generation logits match the reference path, so a regression in the loader or kernels goes unnoticed.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/main.rs
Line: 4350
Symbol: parsed
Issue: Final assertion compares two identically configured models, so it checks nothing. expected is built with load_with_matvec(..., true) and fast is built from engine.load_inference_model with fast_cpu=true, which is the same configuration. The assertion passes whether or not the engine wiring is correct, so the test does not verify that the flag selects the requested numerics.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/model.rs
Line: 113
Symbol: mv
Issue: New unconditional assert_eq on dimensions in the mv hot path can panic. Any caller that passes an input slice whose length differs from t.cols now panics in release builds. The earlier code did not check this, so a call site that relied on tolerant behaviour now crashes during token generation.
Make the smallest change that fixes this, add a test, and change nothing unrelated.
Blast radius: 60 other file(s) depend on what this PR changes (14 directly, 46 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/model.rs is imported by src/cpu_worker.rs, src/expert_cache.rs, src/gpu_model.rs, src/gpu_model/prefill.rs (+6 more)
  • src/cpu_moe.rs is imported by src/cpu_worker.rs, src/deepseek/mat.rs, src/gemma4/forward.rs, src/gpu_model/prefill.rs (+3 more)

Indirectly affected: examples/gguf_dump.rs, src/backend.rs, src/calibrate.rs, src/chat.rs, src/config.rs, src/cuda/mod.rs (+40 more)

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

@aletheore

aletheore Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

🔍 Aletheore evidence diff

graph LR
    n0["src/cpu_moe.rs"]
    n1["src/model.rs"]
    n2["cpu_worker.rs"]
    n3["mat.rs"]
    n4["expert_cache.rs"]
    n5["forward.rs"]
    n6["src/gpu_model.rs"]
    n7["prefill.rs"]
    n8["lib.rs"]
    n9["prompt.rs"]
    n10["weights.rs"]
    n11["tests/cpu_moe.rs"]
    n12["tests/gpu_model.rs"]
    n13["tests/model.rs"]
    n14["quant.rs"]
    n15["vision.rs"]
    n0 --> n2
    n0 --> n3
    n0 --> n5
    n0 --> n7
    n0 --> n8
    n0 --> n11
    n0 --> n14
    n1 --> n2
    n1 --> n4
    n1 --> n6
    n1 --> n7
    n1 --> n8
    n1 --> n9
    n1 --> n10
    n1 --> n12
    n1 --> n13
    n1 --> n15
    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
    class n14 dependent
    class n15 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/cpu_moe.rs · modified · +6/-2 · +1 function · 7 other dependents
  • src/main.rs · modified · +34/-4 · +2 functions
  • src/model.rs · modified · +184/-91 · +6 functions · 10 other dependents

Aggregate deltas

  • Modules: +0
  • Dependency graph edges: +1
  • Commits: 2

Preserve reference logits by default and centralize --fast-cpu selection in the inference loader. Use integer kernels for supported aligned projections and reuse quantized activations across FFN and MTP projections.

Apply LoRA once during model loading and cover projection fallbacks, activation reuse, and default decode parity with regression tests.
Comment thread src/main.rs
gpu: bool,
/// Accelerate CPU generation using Q8_K activations. This can change logits and generated tokens.
#[arg(long)]
fast_cpu: bool,

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 4

New --fast-cpu flag defaults to off, so default CPU generation loses the quantized kernels the PR enables. Before this push, CPU generate/chat/serve/bench used with_fast_matvec(!engine.gpu), so the quantized kernels ran by default. Now load_inference_model only enables them when the bool --fast-cpu is passed. A user running the reported model with the same flags as before gets the floating-point path again, so the claimed 0.6 to 5.7 tps prefill and 0.4 to 5.5 tps decode gain does not occur.

Prompt for your AI agent
File: src/main.rs
Line: 34
Symbol: Engine
Issue: New --fast-cpu flag defaults to off, so default CPU generation loses the quantized kernels the PR enables. Before this push, CPU generate/chat/serve/bench used with_fast_matvec(!engine.gpu), so the quantized kernels ran by default. Now load_inference_model only enables them when the bool --fast-cpu is passed. A user running the reported model with the same flags as before gets the floating-point path again, so the claimed 0.6 to 5.7 tps prefill and 0.4 to 5.5 tps decode gain does not occur.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

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

Comment thread src/main.rs
#[test]
fn cpu_inference_loader_selects_requested_numerics() {
use super::{Cmd, Gguf, Model, State, ops};
let Some(path) = std::env::var_os("STRATA_CPU_PARITY_MODEL") else { return };

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

CPU parity test returns early and passes silently when the env var is unset. Without STRATA_CPU_PARITY_MODEL set, the test returns immediately and reports success. CI never checks that CPU generation logits match the reference path, so a regression in the loader or kernels goes unnoticed.

Prompt for your AI agent
File: src/main.rs
Line: 4333
Symbol: meta
Issue: CPU parity test returns early and passes silently when the env var is unset. Without STRATA_CPU_PARITY_MODEL set, the test returns immediately and reports success. CI never checks that CPU generation logits match the reference path, so a regression in the loader or kernels goes unnoticed.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

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

Comment thread src/main.rs
engine.fast_cpu = true;
let fast = engine.load_inference_model(&g, None).unwrap();
let expected = Model::load_with_matvec(&g, None, &[], true).unwrap();
assert_eq!(fast.step(&mut State::new(&fast.cfg), token), expected.step(&mut State::new(&expected.cfg), token));

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 4

Final assertion compares two identically configured models, so it checks nothing. expected is built with load_with_matvec(..., true) and fast is built from engine.load_inference_model with fast_cpu=true, which is the same configuration. The assertion passes whether or not the engine wiring is correct, so the test does not verify that the flag selects the requested numerics.

Prompt for your AI agent
File: src/main.rs
Line: 4350
Symbol: parsed
Issue: Final assertion compares two identically configured models, so it checks nothing. expected is built with load_with_matvec(..., true) and fast is built from engine.load_inference_model with fast_cpu=true, which is the same configuration. The assertion passes whether or not the engine wiring is correct, so the test does not verify that the flag selects the requested numerics.
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/model.rs
}

fn mv_cached(&self, t: &Tensor, x: &[f32], activation: &OnceCell<Vec<Q8K>>) -> Vec<f32> {
assert_eq!(t.cols, x.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.

🟡 Medium · Correctness · 4 of 4

New unconditional assert_eq on dimensions in the mv hot path can panic. Any caller that passes an input slice whose length differs from t.cols now panics in release builds. The earlier code did not check this, so a call site that relied on tolerant behaviour now crashes during token generation.

Prompt for your AI agent
File: src/model.rs
Line: 113
Symbol: mv
Issue: New unconditional assert_eq on dimensions in the mv hot path can panic. Any caller that passes an input slice whose length differs from t.cols now panics in release builds. The earlier code did not check this, so a call site that relied on tolerant behaviour now crashes during token generation.
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 dd39986 into RustingStudio:main Nov 26, 2026
4 checks passed
@Vasyl-Trefilov

Copy link
Copy Markdown
Member

Big ty @marcomartini97, this is great work! On my side qwen3.5-2b on CPU went from 4 to 20 tok/s with --fast-cpu, and the default path stays the same, bc it is opt-in. Merged, it will be in the next release

@Vasyl-Trefilov

Copy link
Copy Markdown
Member

OH WAIT @marcomartini97 YOUR PROFILE PICTURE, IT'S INVOKEEEER, I GOT 750 GAMES ON HIM, I FUCKING LOVE HIM, + respect for this

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