Repository navigation
Use quantized matvec kernels for CPU generation - #112
Vasyl-Trefilov merged 2 commits into
Conversation
Reuse the CPU quantized dot products for generation, chat, serving, and benchmarking. Keep the floating-point reference path for score and perplexity.
| 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); |
There was a problem hiding this comment.
✅ 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.
|
|
||
| fn mv(&self, t: &Tensor, x: &[f32]) -> Vec<f32> { | ||
| let mut y = vec![0f32; t.rows]; | ||
| if self.fast_matvec { |
There was a problem hiding this comment.
✅ 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.
| 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 }; |
There was a problem hiding this comment.
✅ 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.
| 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)?; |
There was a problem hiding this comment.
🔵 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.
| 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); |
There was a problem hiding this comment.
✅ 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.
| @@ -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"); | |||
There was a problem hiding this comment.
🔵 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 Flash Lite reviewWhat this PR does. This PR adds an opt-in
4 finding(s) posted as inline review comment(s). 2 earlier finding(s) from previous pushes still open.
Review detailsReviewed 3 file(s); skipped 0. Dismissed 0; outside PR diff 0. Grounding: 4 of 4 proposed finding(s). Fix all with your agentBlast 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.
Indirectly affected: The graph is large; this list is capped and not exhaustive. |
🔍 Aletheore evidence diffgraph 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
What changed
Aggregate deltas
|
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.
| gpu: bool, | ||
| /// Accelerate CPU generation using Q8_K activations. This can change logits and generated tokens. | ||
| #[arg(long)] | ||
| fast_cpu: bool, |
There was a problem hiding this comment.
🟠 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.
| #[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 }; |
There was a problem hiding this comment.
🔵 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.
| 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)); |
There was a problem hiding this comment.
🔵 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.
| } | ||
|
|
||
| fn mv_cached(&self, t: &Tensor, x: &[f32], activation: &OnceCell<Vec<Q8K>>) -> Vec<f32> { | ||
| assert_eq!(t.cols, x.len()); |
There was a problem hiding this comment.
🟡 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.
|
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 |
|
OH WAIT @marcomartini97 YOUR PROFILE PICTURE, IT'S INVOKEEEER, I GOT 750 GAMES ON HIM, I FUCKING LOVE HIM, + respect for this |
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