Files
leleka/crates/cpu-sys/tests/multi.rs
T
Pavlo RatushnyiandClaude Opus 5.5 87637c2b0b perf: multi-activation kernels make the CPU small-batch pass cheaper, bit-identical (STRA-220)
Profiling the speculative verification pass (batch_cost, position 900) showed its extra cost is compute in the
int8 weight products, not expert bytes: distinct experts per layer rise only from 4 to 9.5 at 9 tokens, while the
Q8_0 projections, whose weights every token shares, cost 3.6-4x a single step. Each (row, token) dot redid the
MXFP4 decode and scale work.

cpu-sys gains multi-activation kernels (portable, AVX2, AVX-VNNI) for MXFP4 and Q8_0 rows: the row is decoded once
per 64-block segment and up to 16 activations run over it with exactly the one-token kernel's accumulators and
final reduction, so every output is bit for bit the one-token kernel's (tests/multi.rs: every level, 1-16
activations, 13 row lengths). run_region uses them for jobs with two or more activations (speculative batches and
prefill chunks); one-token decode keeps its kernel. A new synthetic test checks a 20-token batch at every level
against feeding tokens one at a time. Model::set_multi_activation(false) restores the per-token path for paired
measurements; Profile counts the expert sets read.

batch_cost gains a per-size phase breakdown and an `ab` mode that runs every pass without and with the new kernels
back to back and checks the logits are identical. Paired, 9 rounds, real model: identical logits in all 90 paired
passes; time ratio with/without 1.01 (1 token), 0.98, 0.92, 0.90, 0.83, 0.81, 0.77, 0.79, 0.76 (2..9 tokens).
MEASURED_COST becomes 0.737 + 0.421 n (was 0.30 + 0.631 n). ab_speculation (3 pairs, outputs identical in all 24
runs) gave 1.34 / 1.04 / 0.97 / 0.94, within the pair-to-pair spread of the run before the change; replaying the
outputs through the drafter predicts 1.59 / 1.15 / 1.00 / 0.99, so the serving loop loses time the pass-cost model
does not see. Prefill also uses the kernels (bit-identical); its speed was not measured.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 13:07:38 +02:00

185 lines
5.7 KiB
Rust

//! The multi-activation kernels: for every row length and every number of activations, each output is
//! bit for bit the value of the one-activation kernel the decoder uses at the same level (the MXFP4 "q8r4"
//! kernel, and the Q8_0 x Q8_0 kernel fed the activation's Q8_0 blocks).
use leleka_cpu_sys as sys;
use leleka_cpu_sys::simd;
struct Rng(u64);
impl Rng {
fn next(&mut self) -> u64 {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
self.0
}
}
/// An activation in both layouts: Q8_0 blocks and the "q8r" form (half scales converted to f32).
struct Act {
blocks: Vec<u8>,
scales: Vec<f32>,
quants: Vec<i8>,
}
fn act(rng: &mut Rng, blocks: usize) -> Act {
let mut out = Act {
blocks: Vec::new(),
scales: Vec::new(),
quants: Vec::new(),
};
for _ in 0..blocks {
let half = simd::f32_to_f16(0.0005 + (rng.next() % 1000) as f32 * 1e-5);
out.blocks.extend_from_slice(&half.to_le_bytes());
out.scales.push(simd::f16_to_f32(half));
for _ in 0..32 {
let q = ((rng.next() % 255) as i64 - 127) as i8;
out.blocks.push(q as u8);
out.quants.push(q);
}
}
out
}
fn mx_row(rng: &mut Rng, blocks: usize) -> Vec<u8> {
let mut v = Vec::new();
for _ in 0..blocks {
v.push(110 + (rng.next() % 30) as u8);
v.extend((0..16).map(|_| rng.next() as u8));
}
v
}
fn q8_row(rng: &mut Rng, blocks: usize) -> Vec<u8> {
let mut v = Vec::new();
for _ in 0..blocks {
let scale = 0.001 + (rng.next() % 1000) as f32 * 1e-5;
v.extend_from_slice(&simd::f32_to_f16(scale).to_le_bytes());
v.extend((0..32).map(|_| rng.next() as u8)); // any int8 weight, -128 included
}
v
}
type Multi = fn(&[u8], &[sys::Q8rRef], &mut [f32]) -> Result<(), sys::KernelError>;
type OneMx = fn(&[u8], &[f32], &[i8]) -> Result<f32, sys::KernelError>;
type OneQ8 = fn(&[u8], &[u8]) -> Result<f32, sys::KernelError>;
/// Row lengths around the four-block groups and the 64-block segments, and the model's 90 and 128.
const BLOCKS: [usize; 13] = [1, 2, 3, 4, 5, 7, 8, 63, 64, 65, 90, 128, 131];
fn check(multi_mx: Multi, one_mx: OneMx, multi_q8: Multi, one_q8: OneQ8, label: &str) {
let mut rng = Rng(0x9E37_79B9_7F4A_7C15);
for blocks in BLOCKS {
let acts: Vec<Act> = (0..sys::MULTI_MAX).map(|_| act(&mut rng, blocks)).collect();
let refs: Vec<sys::Q8rRef> = acts
.iter()
.map(|a| sys::Q8rRef {
scales: &a.scales,
quants: &a.quants,
})
.collect();
let (mx, q8) = (mx_row(&mut rng, blocks), q8_row(&mut rng, blocks));
for n in 1..=sys::MULTI_MAX {
let mut out = vec![0f32; n];
multi_mx(&mx, &refs[..n], &mut out).unwrap();
for (a, got) in out.iter().enumerate() {
let want = one_mx(&mx, &acts[a].scales, &acts[a].quants).unwrap();
assert_eq!(
got.to_bits(),
want.to_bits(),
"{label} MXFP4: {blocks} blocks, {n} activations, activation {a}: {got} vs {want}"
);
}
multi_q8(&q8, &refs[..n], &mut out).unwrap();
for (a, got) in out.iter().enumerate() {
let want = one_q8(&q8, &acts[a].blocks).unwrap();
assert_eq!(
got.to_bits(),
want.to_bits(),
"{label} Q8_0: {blocks} blocks, {n} activations, activation {a}: {got} vs {want}"
);
}
}
}
}
#[test]
fn portable_multi_kernels_equal_the_one_activation_kernels() {
check(
sys::dot_mxfp4_q8r_multi_scalar,
sys::dot_mxfp4_q8r_scalar,
sys::dot_q8_0_q8r_multi_scalar,
sys::dot_q8_0_q8_0_scalar,
"portable",
);
}
#[cfg(target_arch = "x86_64")]
#[test]
fn avx2_multi_kernels_equal_the_one_activation_kernels() {
if !sys::avx2_available() {
eprintln!("skipped: no AVX2");
return;
}
check(
sys::dot_mxfp4_q8r4_multi_avx2,
sys::dot_mxfp4_q8r4_avx2,
sys::dot_q8_0_q8r_multi_avx2,
sys::dot_q8_0_q8_0_avx2,
"AVX2",
);
}
#[cfg(target_arch = "x86_64")]
#[test]
fn avxvnni_multi_kernels_equal_the_one_activation_kernels() {
if !sys::avxvnni_available() {
eprintln!("skipped: no AVX-VNNI");
return;
}
check(
sys::dot_mxfp4_q8r4_multi_avxvnni,
sys::dot_mxfp4_q8r4_avxvnni,
sys::dot_q8_0_q8r_multi_avxvnni,
sys::dot_q8_0_q8_0_avxvnni,
"AVX-VNNI",
);
}
#[test]
fn bad_counts_and_lengths_are_refused() {
let mut rng = Rng(5);
let a = act(&mut rng, 3);
let row = mx_row(&mut rng, 3);
let one = sys::Q8rRef {
scales: &a.scales,
quants: &a.quants,
};
assert_eq!(
sys::dot_mxfp4_q8r_multi_scalar(&row, &[], &mut []),
Err(sys::KernelError::ActivationCount)
);
let too_many = vec![one; sys::MULTI_MAX + 1];
assert_eq!(
sys::dot_mxfp4_q8r_multi_scalar(&row, &too_many, &mut [0.0; sys::MULTI_MAX + 1]),
Err(sys::KernelError::ActivationCount)
);
assert_eq!(
sys::dot_mxfp4_q8r_multi_scalar(&row, &[one], &mut [0.0; 2]),
Err(sys::KernelError::LengthMismatch)
);
let short = sys::Q8rRef {
scales: &a.scales,
quants: &a.quants[..64],
};
assert_eq!(
sys::dot_mxfp4_q8r_multi_scalar(&row, &[short], &mut [0.0]),
Err(sys::KernelError::LengthMismatch)
);
assert_eq!(
sys::dot_q8_0_q8r_multi_scalar(&row[..50], &[one], &mut [0.0]),
Err(sys::KernelError::LengthMismatch)
);
}