Files
leleka/crates/cpu-kernels/src/lib.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

465 lines
18 KiB
Rust

//! Run-time ISA dispatch for the Leleka CPU runtime's kernels (no `unsafe` here).
//!
//! One binary serves every x86-64 CPU: [`Dispatch::best`] picks the highest level the CPU and OS
//! support, and the `LELEKA_CPU_ISA` environment variable can force a lower one (see
//! [`Dispatch::from_env`]). The chosen level is reported by [`Dispatch::isa`] so status endpoints
//! and benchmark records can state which kernels actually ran.
use std::fmt;
pub use leleka_cpu_sys::{KernelError, MAX_DOT_LEN, MULTI_MAX, Q8rRef};
/// Name of the environment variable that forces a kernel level.
pub const ISA_ENV: &str = "LELEKA_CPU_ISA";
/// Kernel levels, ordered from the portable reference to the widest supported instruction set.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum Isa {
/// Portable C reference; accepts every int8 value.
Scalar,
/// 256-bit AVX2.
Avx2,
/// AVX2 plus VEX-encoded AVX-VNNI (`vpdpbusd`), as on Arrow Lake and Alder Lake class CPUs.
AvxVnni,
}
impl Isa {
pub const ALL: [Isa; 3] = [Isa::Scalar, Isa::Avx2, Isa::AvxVnni];
pub fn name(self) -> &'static str {
match self {
Self::Scalar => "scalar",
Self::Avx2 => "avx2",
Self::AvxVnni => "avx-vnni",
}
}
pub fn parse(text: &str) -> Option<Self> {
match text.trim().to_ascii_lowercase().as_str() {
"scalar" => Some(Self::Scalar),
"avx2" => Some(Self::Avx2),
"avx-vnni" | "avxvnni" => Some(Self::AvxVnni),
_ => None,
}
}
/// Whether this level can run here: CPU and OS support, and compiled into this build.
pub fn supported(self) -> bool {
match self {
Self::Scalar => true,
#[cfg(target_arch = "x86_64")]
Self::Avx2 => leleka_cpu_sys::avx2_available(),
#[cfg(target_arch = "x86_64")]
Self::AvxVnni => leleka_cpu_sys::avxvnni_available(),
#[cfg(not(target_arch = "x86_64"))]
Self::Avx2 | Self::AvxVnni => false,
}
}
/// The highest supported level.
pub fn detect_best() -> Self {
Self::ALL
.iter()
.rev()
.copied()
.find(|isa| isa.supported())
.unwrap_or(Self::Scalar)
}
}
impl fmt::Display for Isa {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
/// Why a [`Dispatch`] could not be built.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum DispatchError {
/// The requested level is not available on this CPU, OS or build.
Unsupported(Isa),
/// The environment value is not a known level name.
UnknownLevel(String),
}
impl fmt::Display for DispatchError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Unsupported(isa) => write!(f, "kernel level {isa} is not supported here"),
Self::UnknownLevel(text) => {
write!(
f,
"unknown value {text:?} for {ISA_ENV} (use scalar, avx2 or avx-vnni)"
)
}
}
}
}
impl std::error::Error for DispatchError {}
type DotI8 = fn(&[i8], &[i8]) -> Result<i32, KernelError>;
type DotI4 = fn(&[u8], &[i8]) -> Result<i32, KernelError>;
type DotMx = fn(&[u8], &[u8]) -> Result<f32, KernelError>;
type IsumsMx = fn(&[u8], &[u8], &mut [i32]) -> Result<(), KernelError>;
type QuantQ8 = fn(&[f32], &mut [u8]) -> Result<(), KernelError>;
type DotMxR = fn(&[u8], &[f32], &[i8]) -> Result<f32, KernelError>;
type DotMulti = fn(&[u8], &[Q8rRef], &mut [f32]) -> Result<(), KernelError>;
type AttnScores =
fn(&[f32], usize, &[u16], usize, usize, f32, &mut [f32]) -> Result<(), KernelError>;
type AttnSum = fn(&[f32], usize, usize, &[u16], usize, &mut [f32]) -> Result<(), KernelError>;
type ToHalf = fn(&[f32], &mut [u16]) -> Result<(), KernelError>;
type FromHalf = fn(&[u16], &mut [f32]) -> Result<(), KernelError>;
type RowsDot = fn(&[f32], &[f32], usize, usize, &mut [f32]) -> Result<(), KernelError>;
type Swiglu = fn(&[f32], &[f32], f32, f32, &mut [f32]) -> Result<(), KernelError>;
type ExpSum = fn(&mut [f32], f32) -> Result<f32, KernelError>;
/// A resolved set of kernels for one level. Cheap to copy; resolve once at startup.
#[derive(Clone, Copy)]
pub struct Dispatch {
isa: Isa,
dot_i8i8: DotI8,
dot_i4i8: DotI4,
dot_mxfp4_q8_0: DotMx,
isums_mxfp4_q8_0: IsumsMx,
quantize_q8_0: QuantQ8,
dot_mxfp4_q8r: DotMxR,
dot_q8_0_q8_0: DotMx,
isums_q8_0_q8_0: IsumsMx,
dot_mxfp4_q8r_multi: DotMulti,
dot_q8_0_q8r_multi: DotMulti,
attn_scores: AttnScores,
attn_weighted_sum: AttnSum,
exp_shift_sum: ExpSum,
f32_to_f16: ToHalf,
f16_to_f32: FromHalf,
rows_dot: RowsDot,
swiglu_oai: Swiglu,
}
impl fmt::Debug for Dispatch {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Dispatch").field("isa", &self.isa).finish()
}
}
impl Dispatch {
/// The highest level this CPU, OS and build support.
pub fn best() -> Self {
Self::with_isa(Isa::detect_best()).expect("a detected level is supported")
}
/// A specific level, refused when it cannot run here.
pub fn with_isa(isa: Isa) -> Result<Self, DispatchError> {
if !isa.supported() {
return Err(DispatchError::Unsupported(isa));
}
Ok(match isa {
Isa::Scalar => Self {
isa,
dot_i8i8: leleka_cpu_sys::dot_i8i8_scalar,
dot_i4i8: leleka_cpu_sys::dot_i4i8_scalar,
dot_mxfp4_q8_0: leleka_cpu_sys::dot_mxfp4_q8_0_scalar,
isums_mxfp4_q8_0: leleka_cpu_sys::mxfp4_q8_0_isums_scalar,
quantize_q8_0: leleka_cpu_sys::quantize_q8_0_scalar,
dot_mxfp4_q8r: leleka_cpu_sys::dot_mxfp4_q8r_scalar,
dot_q8_0_q8_0: leleka_cpu_sys::dot_q8_0_q8_0_scalar,
isums_q8_0_q8_0: leleka_cpu_sys::q8_0_q8_0_isums_scalar,
dot_mxfp4_q8r_multi: leleka_cpu_sys::dot_mxfp4_q8r_multi_scalar,
dot_q8_0_q8r_multi: leleka_cpu_sys::dot_q8_0_q8r_multi_scalar,
attn_scores: leleka_cpu_sys::attn_scores_f16_scalar,
attn_weighted_sum: leleka_cpu_sys::attn_weighted_sum_f16_scalar,
f32_to_f16: leleka_cpu_sys::f32_to_f16_slice_scalar,
f16_to_f32: leleka_cpu_sys::f16_to_f32_slice_scalar,
rows_dot: |q, rows, stride, n, out| {
leleka_cpu_sys::attn_scores_scalar(q, 1, rows, stride, n, 1.0, out)
},
swiglu_oai: leleka_cpu_sys::swiglu_oai_scalar,
exp_shift_sum: leleka_cpu_sys::exp_shift_sum_scalar,
},
#[cfg(target_arch = "x86_64")]
Isa::Avx2 => Self {
isa,
dot_i8i8: leleka_cpu_sys::dot_i8i8_avx2,
dot_i4i8: leleka_cpu_sys::dot_i4i8_avx2,
dot_mxfp4_q8_0: leleka_cpu_sys::dot_mxfp4_q8_0_avx2,
isums_mxfp4_q8_0: leleka_cpu_sys::mxfp4_q8_0_isums_avx2,
quantize_q8_0: leleka_cpu_sys::quantize_q8_0_avx2,
dot_mxfp4_q8r: leleka_cpu_sys::dot_mxfp4_q8r4_avx2,
dot_q8_0_q8_0: leleka_cpu_sys::dot_q8_0_q8_0_avx2,
isums_q8_0_q8_0: leleka_cpu_sys::q8_0_q8_0_isums_avx2,
dot_mxfp4_q8r_multi: leleka_cpu_sys::dot_mxfp4_q8r4_multi_avx2,
dot_q8_0_q8r_multi: leleka_cpu_sys::dot_q8_0_q8r_multi_avx2,
attn_scores: leleka_cpu_sys::attn_scores_f16_avx2,
attn_weighted_sum: leleka_cpu_sys::attn_weighted_sum_f16_avx2,
f32_to_f16: leleka_cpu_sys::f32_to_f16_slice_avx2,
f16_to_f32: leleka_cpu_sys::f16_to_f32_slice_avx2,
rows_dot: |q, rows, stride, n, out| {
leleka_cpu_sys::attn_scores_avx2(q, 1, rows, stride, n, 1.0, out)
},
swiglu_oai: leleka_cpu_sys::swiglu_oai_avx2,
exp_shift_sum: leleka_cpu_sys::exp_shift_sum_avx2,
},
#[cfg(target_arch = "x86_64")]
Isa::AvxVnni => Self {
isa,
dot_i8i8: leleka_cpu_sys::dot_i8i8_avxvnni,
dot_i4i8: leleka_cpu_sys::dot_i4i8_avxvnni,
dot_mxfp4_q8_0: leleka_cpu_sys::dot_mxfp4_q8_0_avxvnni,
isums_mxfp4_q8_0: leleka_cpu_sys::mxfp4_q8_0_isums_avxvnni,
// The quantizer has no VNNI variant: it needs no dot-product instruction.
quantize_q8_0: leleka_cpu_sys::quantize_q8_0_avx2,
dot_mxfp4_q8r: leleka_cpu_sys::dot_mxfp4_q8r4_avxvnni,
dot_q8_0_q8_0: leleka_cpu_sys::dot_q8_0_q8_0_avxvnni,
isums_q8_0_q8_0: leleka_cpu_sys::q8_0_q8_0_isums_avxvnni,
dot_mxfp4_q8r_multi: leleka_cpu_sys::dot_mxfp4_q8r4_multi_avxvnni,
dot_q8_0_q8r_multi: leleka_cpu_sys::dot_q8_0_q8r_multi_avxvnni,
// attention and softmax are float work: the VNNI level shares the AVX2 + FMA kernels
attn_scores: leleka_cpu_sys::attn_scores_f16_avx2,
attn_weighted_sum: leleka_cpu_sys::attn_weighted_sum_f16_avx2,
f32_to_f16: leleka_cpu_sys::f32_to_f16_slice_avx2,
f16_to_f32: leleka_cpu_sys::f16_to_f32_slice_avx2,
rows_dot: |q, rows, stride, n, out| {
leleka_cpu_sys::attn_scores_avx2(q, 1, rows, stride, n, 1.0, out)
},
swiglu_oai: leleka_cpu_sys::swiglu_oai_avx2,
exp_shift_sum: leleka_cpu_sys::exp_shift_sum_avx2,
},
#[cfg(not(target_arch = "x86_64"))]
Isa::Avx2 | Isa::AvxVnni => return Err(DispatchError::Unsupported(isa)),
})
}
/// Resolve from an optional request string (the value of [`ISA_ENV`]): `None` or empty means
/// the best level; a name forces exactly that level and fails if it cannot run, so a forced
/// level never silently becomes another one.
pub fn from_request(request: Option<&str>) -> Result<Self, DispatchError> {
match request.map(str::trim) {
None | Some("") => Ok(Self::best()),
Some(text) => match Isa::parse(text) {
Some(isa) => Self::with_isa(isa),
None => Err(DispatchError::UnknownLevel(text.to_owned())),
},
}
}
/// Resolve from the process environment ([`ISA_ENV`]).
pub fn from_env() -> Result<Self, DispatchError> {
Self::from_request(std::env::var(ISA_ENV).ok().as_deref())
}
/// The level these kernels run at.
pub fn isa(&self) -> Isa {
self.isa
}
/// Exact `sum(w[i] * x[i])`; activations must be in `[-127, 127]` for SIMD levels to equal the
/// scalar level (see the kernel contract in `leleka_cpu.h`).
pub fn dot_i8i8(&self, w: &[i8], x: &[i8]) -> Result<i32, KernelError> {
(self.dot_i8i8)(w, x)
}
/// Exact dot of packed int4 weights (`value = nibble - 8`, element `2k` in the low nibble of
/// byte `k`) with int8 activations.
pub fn dot_i4i8(&self, w4: &[u8], x: &[i8]) -> Result<i32, KernelError> {
(self.dot_i4i8)(w4, x)
}
/// MXFP4 weights (`x`: 17-byte ggml blocks) times Q8_0 activations (`y`: 34-byte ggml blocks).
/// The per-block integer sums are exact at every level; blocks are combined in float, so levels
/// differ only by float summation order (see `csrc/leleka_cpu.h`).
pub fn dot_mxfp4_q8_0(&self, x: &[u8], y: &[u8]) -> Result<f32, KernelError> {
(self.dot_mxfp4_q8_0)(x, y)
}
/// Quantize activations (floats, a multiple of 32) to Q8_0 blocks: scale = amax / 127 as a half,
/// quants rounded to nearest even in `[-127, 127]`. Output is identical at every level.
pub fn quantize_q8_0(&self, x: &[f32], out: &mut [u8]) -> Result<(), KernelError> {
(self.quantize_q8_0)(x, out)
}
/// MXFP4 weights times an activation in the "q8r" layout: f32 scales (the Q8_0 half scales converted
/// once) and contiguous int8 quants. Same maths as [`Dispatch::dot_mxfp4_q8_0`]; the SIMD levels use
/// four blocks and four accumulators per iteration, so results differ from it only in float summation
/// order, and the AVX2 and AVX-VNNI levels are bit-identical to each other.
pub fn dot_mxfp4_q8r(&self, x: &[u8], ys: &[f32], yq: &[i8]) -> Result<f32, KernelError> {
(self.dot_mxfp4_q8r)(x, ys, yq)
}
/// Q8_0 weights times Q8_0 activations (both 34-byte ggml blocks); integer sums per block are
/// exact at every level, float combination differs only in summation order.
pub fn dot_q8_0_q8_0(&self, x: &[u8], y: &[u8]) -> Result<f32, KernelError> {
(self.dot_q8_0_q8_0)(x, y)
}
/// One MXFP4 row against 1 to [`MULTI_MAX`] activations in the "q8r" layout, the row decoded once:
/// `out[a]` is bit for bit [`Dispatch::dot_mxfp4_q8r`] of `acts[a]` at this level.
pub fn dot_mxfp4_q8r_multi(
&self,
x: &[u8],
acts: &[Q8rRef],
out: &mut [f32],
) -> Result<(), KernelError> {
(self.dot_mxfp4_q8r_multi)(x, acts, out)
}
/// One Q8_0 row against 1 to [`MULTI_MAX`] activations in the "q8r" layout: `out[a]` is bit for bit
/// [`Dispatch::dot_q8_0_q8_0`] of the Q8_0 blocks of `acts[a]` (the same quants, scales as halves).
pub fn dot_q8_0_q8r_multi(
&self,
x: &[u8],
acts: &[Q8rRef],
out: &mut [f32],
) -> Result<(), KernelError> {
(self.dot_q8_0_q8r_multi)(x, acts, out)
}
/// Attention scores for a group of `heads` query heads sharing the keys (stored as half floats):
/// `out[g * n + i] = scale * dot(q[g * hd ..][..hd], keys[i * stride ..][..hd])`, `hd = q.len() / heads`.
/// SIMD levels differ from the portable one only in float summation order.
// The argument list mirrors the kernel's, which is what its callers and tests read against.
#[allow(clippy::too_many_arguments)]
pub fn attn_scores(
&self,
q: &[f32],
heads: usize,
keys: &[u16],
stride: usize,
n: usize,
scale: f32,
out: &mut [f32],
) -> Result<(), KernelError> {
(self.attn_scores)(q, heads, keys, stride, n, scale, out)
}
/// Weighted value sums for a group of heads:
/// `out[g * hd ..][..hd] = sum_i weights[g * n + i] * values[i * stride ..][..hd]`, `hd = out.len() / heads`.
pub fn attn_weighted_sum(
&self,
weights: &[f32],
heads: usize,
n: usize,
values: &[u16],
stride: usize,
out: &mut [f32],
) -> Result<(), KernelError> {
(self.attn_weighted_sum)(weights, heads, n, values, stride, out)
}
/// `out[i] = dot(q, rows[i * stride ..][..q.len()])` for `i < n` in single precision (the router).
pub fn rows_dot(
&self,
q: &[f32],
rows: &[f32],
stride: usize,
n: usize,
out: &mut [f32],
) -> Result<(), KernelError> {
(self.rows_dot)(q, rows, stride, n, out)
}
/// The gpt-oss expert activation for `gate` and `up` (equal lengths) into `out`.
pub fn swiglu_oai(
&self,
gate: &[f32],
up: &[f32],
alpha: f32,
limit: f32,
out: &mut [f32],
) -> Result<(), KernelError> {
(self.swiglu_oai)(gate, up, alpha, limit, out)
}
/// Floats to half-precision bit patterns (round to nearest even); the slices must be equally long.
pub fn f32_to_f16(&self, src: &[f32], dst: &mut [u16]) -> Result<(), KernelError> {
(self.f32_to_f16)(src, dst)
}
/// Half bit patterns to floats (exact), `dst.len() == src.len()`.
pub fn f16_to_f32(&self, src: &[u16], dst: &mut [f32]) -> Result<(), KernelError> {
(self.f16_to_f32)(src, dst)
}
/// Replaces each `x[i]` by `exp(x[i] - max)` and returns their sum (softmax numerators).
pub fn exp_shift_sum(&self, x: &mut [f32], max: f32) -> Result<f32, KernelError> {
(self.exp_shift_sum)(x, max)
}
/// The exact per-block integer sums behind [`Dispatch::dot_q8_0_q8_0`], for testing.
pub fn q8_0_q8_0_block_sums(
&self,
x: &[u8],
y: &[u8],
out: &mut [i32],
) -> Result<(), KernelError> {
(self.isums_q8_0_q8_0)(x, y, out)
}
/// The exact per-block integer sums behind [`Dispatch::dot_mxfp4_q8_0`], for testing.
pub fn mxfp4_q8_0_block_sums(
&self,
x: &[u8],
y: &[u8],
out: &mut [i32],
) -> Result<(), KernelError> {
(self.isums_mxfp4_q8_0)(x, y, out)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn scalar_is_always_available_and_best_is_supported() {
assert!(Isa::Scalar.supported());
let best = Dispatch::best();
assert!(best.isa().supported());
assert!(
Isa::ALL
.iter()
.all(|isa| *isa <= best.isa() || !isa.supported())
);
}
#[test]
fn requests_force_exactly_the_named_level_or_fail() {
assert_eq!(
Dispatch::from_request(Some("scalar")).unwrap().isa(),
Isa::Scalar
);
assert_eq!(
Dispatch::from_request(Some(" SCALAR ")).unwrap().isa(),
Isa::Scalar
);
assert_eq!(
Dispatch::from_request(None).unwrap().isa(),
Isa::detect_best()
);
assert_eq!(
Dispatch::from_request(Some("")).unwrap().isa(),
Isa::detect_best()
);
assert_eq!(
Dispatch::from_request(Some("avx9000")).unwrap_err(),
DispatchError::UnknownLevel("avx9000".into())
);
for isa in [Isa::Avx2, Isa::AvxVnni] {
let result = Dispatch::from_request(Some(isa.name()));
if isa.supported() {
assert_eq!(result.unwrap().isa(), isa);
} else {
assert_eq!(result.unwrap_err(), DispatchError::Unsupported(isa));
}
}
}
#[test]
fn names_round_trip() {
for isa in Isa::ALL {
assert_eq!(Isa::parse(isa.name()), Some(isa));
}
assert_eq!(Isa::parse("avxvnni"), Some(Isa::AvxVnni));
}
}