Files
leleka/crates/cpu-sys/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

1008 lines
35 KiB
Rust

//! The kernels of the Leleka CPU runtime behind checked, safe functions.
//!
//! The kernels themselves are Rust (`simd`, `std::arch` intrinsics). This crate is the only place in
//! the CPU runtime that contains `unsafe`: the intrinsics need it, the file mapping needs it, and the
//! optional C reference needs it. Every public function here is safe: it validates operand lengths and,
//! for SIMD levels, the CPU and OS support at call time, so a caller cannot reach an illegal
//! instruction or an out-of-bounds read.
//!
//! Numeric contract: activations must stay in `[-127, 127]` (the signed-to-unsigned trick used by
//! the SIMD dot products is wrong for `-128`), Q8_0 and "q8r" scales must be finite, and vectors are
//! at most [`MAX_DOT_LEN`] elements.
//!
//! The int8 and int4 dot products are adapted from Colibri `c/idot.h` (Apache-2.0, see
//! `NOTICE.colibri`); the block formats and the MXFP4 table are ggml's (MIT).
//!
//! Feature `c-reference` additionally builds the original C implementation (`csrc/`, module
//! `c_reference`) so the Rust kernels can be compared with it bit for bit; the runtime never enables it.
use std::fmt;
#[cfg(feature = "c-reference")]
pub mod c_reference;
pub mod mapping;
pub mod simd;
pub mod topology;
pub use simd::{MULTI_MAX, Q8rRef};
/// Longest vector the int32 accumulators can hold exactly (`131072 * 128 * 127 < 2^31`).
pub const MAX_DOT_LEN: usize = 131_072;
/// Elements per MXFP4 or Q8_0 block.
pub const BLOCK_ELEMS: usize = 32;
/// Bytes per MXFP4 block: one E8M0 scale byte and 16 bytes of packed nibbles (ggml layout).
pub const MXFP4_BLOCK_BYTES: usize = simd::MXFP4_BYTES;
/// Bytes per Q8_0 block: a little-endian IEEE half scale and 32 int8 values (ggml layout).
pub const Q8_0_BLOCK_BYTES: usize = simd::Q8_0_BYTES;
/// Why a kernel call was refused. Nothing is computed when an error is returned.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum KernelError {
/// Operand lengths do not match (int8 weights and activations, or packed int4 byte count).
LengthMismatch,
/// More than [`MAX_DOT_LEN`] elements.
TooLong,
/// The CPU or OS lacks the instruction set, or this build did not compile it.
Unsupported,
/// A tile with no rows or activations, or more than [`TILE_MAX`] of either.
TileShape,
/// A multi-activation call with no activations or more than [`MULTI_MAX`].
ActivationCount,
}
impl fmt::Display for KernelError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::LengthMismatch => "operand lengths do not match",
Self::TooLong => "vector longer than the exact int32 accumulation limit",
Self::Unsupported => "instruction set not available on this CPU or build",
Self::TileShape => "a tile needs 1 to 4 rows and 1 to 4 activations",
Self::ActivationCount => "a multi-activation call needs 1 to 16 activations",
})
}
}
impl std::error::Error for KernelError {}
/// `true` when the AVX2 level can run: AVX2, FMA and F16C (Haswell and later), with the OS
/// register-state support, as the standard library determines them.
#[cfg(target_arch = "x86_64")]
pub fn avx2_available() -> bool {
std::arch::is_x86_feature_detected!("avx2")
&& std::arch::is_x86_feature_detected!("fma")
&& std::arch::is_x86_feature_detected!("f16c")
}
/// `true` when the AVX-VNNI level (VEX encoded) can run.
#[cfg(target_arch = "x86_64")]
pub fn avxvnni_available() -> bool {
avx2_available() && std::arch::is_x86_feature_detected!("avxvnni")
}
fn check_i8(w: &[i8], x: &[i8]) -> Result<(), KernelError> {
if w.len() != x.len() {
return Err(KernelError::LengthMismatch);
}
if x.len() > MAX_DOT_LEN {
return Err(KernelError::TooLong);
}
Ok(())
}
fn check_i4(w4: &[u8], x: &[i8]) -> Result<(), KernelError> {
if w4.len() != x.len().div_ceil(2) {
return Err(KernelError::LengthMismatch);
}
if x.len() > MAX_DOT_LEN {
return Err(KernelError::TooLong);
}
Ok(())
}
fn check_mx(x: &[u8], y: &[u8]) -> Result<usize, KernelError> {
if !x.len().is_multiple_of(MXFP4_BLOCK_BYTES) || !y.len().is_multiple_of(Q8_0_BLOCK_BYTES) {
return Err(KernelError::LengthMismatch);
}
let blocks = x.len() / MXFP4_BLOCK_BYTES;
if blocks != y.len() / Q8_0_BLOCK_BYTES {
return Err(KernelError::LengthMismatch);
}
Ok(blocks)
}
fn check_mx_out(blocks: usize, out: &[i32]) -> Result<(), KernelError> {
if out.len() == blocks {
Ok(())
} else {
Err(KernelError::LengthMismatch)
}
}
fn check_q8r(x: &[u8], ys: &[f32], yq: &[i8]) -> Result<usize, KernelError> {
let blocks = ys.len();
if yq.len() != blocks * BLOCK_ELEMS || x.len() != blocks * MXFP4_BLOCK_BYTES {
return Err(KernelError::LengthMismatch);
}
Ok(blocks)
}
fn check_q8(x: &[u8], y: &[u8]) -> Result<usize, KernelError> {
if !x.len().is_multiple_of(Q8_0_BLOCK_BYTES) || x.len() != y.len() {
return Err(KernelError::LengthMismatch);
}
Ok(x.len() / Q8_0_BLOCK_BYTES)
}
/// Checks a multi-activation call: one row of `block_bytes`-byte blocks, 1 to [`MULTI_MAX`] activations of
/// as many blocks, and one output per activation.
fn check_multi(
x: &[u8],
acts: &[Q8rRef],
out: &[f32],
block_bytes: usize,
) -> Result<(), KernelError> {
if acts.is_empty() || acts.len() > MULTI_MAX {
return Err(KernelError::ActivationCount);
}
let blocks = x.len() / block_bytes;
let ok = x.len() == blocks * block_bytes
&& acts
.iter()
.all(|a| a.scales.len() == blocks && a.quants.len() == blocks * BLOCK_ELEMS)
&& out.len() == acts.len();
if ok {
Ok(())
} else {
Err(KernelError::LengthMismatch)
}
}
fn check_quantize(x: &[f32], out: &[u8]) -> Result<usize, KernelError> {
if !x.len().is_multiple_of(BLOCK_ELEMS) || out.len() != x.len() / BLOCK_ELEMS * Q8_0_BLOCK_BYTES
{
return Err(KernelError::LengthMismatch);
}
Ok(x.len() / BLOCK_ELEMS)
}
// ---------------------------------------------------------------------- portable level ----------
/// Exact `sum(w[i] * x[i])`, portable reference (accepts every int8 value).
pub fn dot_i8i8_scalar(w: &[i8], x: &[i8]) -> Result<i32, KernelError> {
check_i8(w, x)?;
Ok(simd::dot_i8i8_scalar(w, x))
}
/// Exact dot of packed int4 weights (`value = nibble - 8`) with int8 activations, reference.
/// `w4` must hold `ceil(x.len() / 2)` bytes; element `2k` is the low nibble of byte `k`.
pub fn dot_i4i8_scalar(w4: &[u8], x: &[i8]) -> Result<i32, KernelError> {
check_i4(w4, x)?;
Ok(simd::dot_i4i8_scalar(w4, x))
}
/// MXFP4 weights (`x`, 17-byte ggml blocks) times Q8_0 activations (`y`, 34-byte ggml blocks),
/// portable reference. Per-block integer sums are exact; blocks are added in order in float.
pub fn dot_mxfp4_q8_0_scalar(x: &[u8], y: &[u8]) -> Result<f32, KernelError> {
check_mx(x, y)?;
Ok(simd::dot_mxfp4_q8_0_scalar(x, y))
}
/// The exact integer sum of each block, portable reference (`out.len()` must equal the blocks).
pub fn mxfp4_q8_0_isums_scalar(x: &[u8], y: &[u8], out: &mut [i32]) -> Result<(), KernelError> {
let blocks = check_mx(x, y)?;
check_mx_out(blocks, out)?;
simd::mxfp4_q8_0_isums_scalar(x, y, out);
Ok(())
}
/// Portable reference for the "q8r" activation layout (f32 scales, contiguous int8 quants).
pub fn dot_mxfp4_q8r_scalar(x: &[u8], ys: &[f32], yq: &[i8]) -> Result<f32, KernelError> {
check_q8r(x, ys, yq)?;
Ok(simd::dot_mxfp4_q8r_scalar(x, ys, yq))
}
/// Quantize floats (a multiple of 32) to Q8_0 blocks; scale = amax / 127 as a half, quants rounded
/// to nearest even and clamped to `[-127, 127]`. Non-finite input gives unspecified (but memory safe)
/// output. Portable reference for the SIMD quantizer.
pub fn quantize_q8_0_scalar(x: &[f32], out: &mut [u8]) -> Result<(), KernelError> {
check_quantize(x, out)?;
simd::quantize_q8_0_scalar(x, out);
Ok(())
}
/// Q8_0 weights (`x`) times Q8_0 activations (`y`), portable reference.
pub fn dot_q8_0_q8_0_scalar(x: &[u8], y: &[u8]) -> Result<f32, KernelError> {
check_q8(x, y)?;
Ok(simd::dot_q8_0_q8_0_scalar(x, y))
}
/// One MXFP4 row against 1 to [`MULTI_MAX`] "q8r" activations, portable: `out[a]` equals
/// [`dot_mxfp4_q8r_scalar`] for `acts[a]` bit for bit.
pub fn dot_mxfp4_q8r_multi_scalar(
x: &[u8],
acts: &[Q8rRef],
out: &mut [f32],
) -> Result<(), KernelError> {
check_multi(x, acts, out, MXFP4_BLOCK_BYTES)?;
simd::dot_mxfp4_q8r_multi_scalar(x, acts, out);
Ok(())
}
/// One Q8_0 row against 1 to [`MULTI_MAX`] "q8r" activations, portable: `out[a]` equals
/// [`dot_q8_0_q8_0_scalar`] for the Q8_0 blocks of `acts[a]` (scales as halves) bit for bit.
pub fn dot_q8_0_q8r_multi_scalar(
x: &[u8],
acts: &[Q8rRef],
out: &mut [f32],
) -> Result<(), KernelError> {
check_multi(x, acts, out, Q8_0_BLOCK_BYTES)?;
simd::dot_q8_0_q8r_multi_scalar(x, acts, out);
Ok(())
}
/// Exact per-block integer sums of a Q8_0 x Q8_0 dot, portable reference.
pub fn q8_0_q8_0_isums_scalar(x: &[u8], y: &[u8], out: &mut [i32]) -> Result<(), KernelError> {
let blocks = check_q8(x, y)?;
check_mx_out(blocks, out)?;
simd::q8_0_q8_0_isums_scalar(x, y, out);
Ok(())
}
/// Float to IEEE half bits, round to nearest even (portable implementation).
pub fn f32_to_f16_bits_scalar(value: f32) -> u16 {
simd::f32_to_f16(value)
}
// ---------------------------------------------------------------------------- AVX2 level ---------
/// Runs `$call` (an unsafe kernel call) after checking that the AVX2 level can run.
#[cfg(target_arch = "x86_64")]
macro_rules! with_avx2 {
($call:expr) => {{
if !avx2_available() {
return Err(KernelError::Unsupported);
}
// SAFETY: operand lengths were checked by the caller; AVX2, FMA and F16C verified just above.
Ok(unsafe { $call })
}};
}
/// Runs `$call` (an unsafe kernel call) after checking that the AVX-VNNI level can run.
#[cfg(target_arch = "x86_64")]
macro_rules! with_avxvnni {
($call:expr) => {{
if !avxvnni_available() {
return Err(KernelError::Unsupported);
}
// SAFETY: operand lengths were checked by the caller; AVX2, FMA, F16C and AVX-VNNI verified
// just above.
Ok(unsafe { $call })
}};
}
/// AVX2 version of [`dot_i8i8_scalar`]. Activations must be in `[-127, 127]` to match it.
#[cfg(target_arch = "x86_64")]
pub fn dot_i8i8_avx2(w: &[i8], x: &[i8]) -> Result<i32, KernelError> {
check_i8(w, x)?;
with_avx2!(simd::x86::dot_i8i8_avx2(w, x))
}
/// AVX2 version of [`dot_i4i8_scalar`]. Activations must be in `[-127, 127]` to match it.
#[cfg(target_arch = "x86_64")]
pub fn dot_i4i8_avx2(w4: &[u8], x: &[i8]) -> Result<i32, KernelError> {
check_i4(w4, x)?;
with_avx2!(simd::x86::dot_i4i8_avx2(w4, x))
}
/// AVX2 level of [`dot_mxfp4_q8_0_scalar`]; equal within float summation order.
#[cfg(target_arch = "x86_64")]
pub fn dot_mxfp4_q8_0_avx2(x: &[u8], y: &[u8]) -> Result<f32, KernelError> {
check_mx(x, y)?;
with_avx2!(simd::x86::dot_mxfp4_q8_0_avx2(x, y))
}
/// AVX2 level of [`mxfp4_q8_0_isums_scalar`]; exactly equal.
#[cfg(target_arch = "x86_64")]
pub fn mxfp4_q8_0_isums_avx2(x: &[u8], y: &[u8], out: &mut [i32]) -> Result<(), KernelError> {
let blocks = check_mx(x, y)?;
check_mx_out(blocks, out)?;
with_avx2!(simd::x86::mxfp4_q8_0_isums_avx2(x, y, out))
}
/// EXPERIMENTAL: AVX2 dot with the "q8r" activation layout (f32 scales, contiguous int8 quants).
#[cfg(target_arch = "x86_64")]
pub fn dot_mxfp4_q8r_avx2(x: &[u8], ys: &[f32], yq: &[i8]) -> Result<f32, KernelError> {
check_q8r(x, ys, yq)?;
with_avx2!(simd::x86::dot_mxfp4_q8r_avx2(x, ys, yq))
}
/// EXPERIMENTAL: as [`dot_mxfp4_q8r_avx2`] with four blocks and four accumulators per iteration.
#[cfg(target_arch = "x86_64")]
pub fn dot_mxfp4_q8r4_avx2(x: &[u8], ys: &[f32], yq: &[i8]) -> Result<f32, KernelError> {
check_q8r(x, ys, yq)?;
with_avx2!(simd::x86::dot_mxfp4_q8r4_avx2(x, ys, yq))
}
/// AVX2 quantizer; bit-identical to [`quantize_q8_0_scalar`].
#[cfg(target_arch = "x86_64")]
pub fn quantize_q8_0_avx2(x: &[f32], out: &mut [u8]) -> Result<(), KernelError> {
check_quantize(x, out)?;
with_avx2!(simd::x86::quantize_q8_0_avx2(x, out))
}
/// AVX2 level of [`dot_q8_0_q8_0_scalar`]; equal within float summation order.
#[cfg(target_arch = "x86_64")]
pub fn dot_q8_0_q8_0_avx2(x: &[u8], y: &[u8]) -> Result<f32, KernelError> {
check_q8(x, y)?;
with_avx2!(simd::x86::dot_q8_0_q8_0_avx2(x, y))
}
/// AVX2 level of [`q8_0_q8_0_isums_scalar`]; exactly equal.
#[cfg(target_arch = "x86_64")]
pub fn q8_0_q8_0_isums_avx2(x: &[u8], y: &[u8], out: &mut [i32]) -> Result<(), KernelError> {
let blocks = check_q8(x, y)?;
check_mx_out(blocks, out)?;
with_avx2!(simd::x86::q8_0_q8_0_isums_avx2(x, y, out))
}
/// One MXFP4 row against 1 to [`MULTI_MAX`] activations, decoding the row once: `out[a]` equals
/// [`dot_mxfp4_q8r4_avx2`] for `acts[a]` bit for bit.
#[cfg(target_arch = "x86_64")]
pub fn dot_mxfp4_q8r4_multi_avx2(
x: &[u8],
acts: &[Q8rRef],
out: &mut [f32],
) -> Result<(), KernelError> {
check_multi(x, acts, out, MXFP4_BLOCK_BYTES)?;
with_avx2!(simd::x86::dot_mxfp4_q8r4_multi_avx2(x, acts, out))
}
/// One Q8_0 row against 1 to [`MULTI_MAX`] "q8r" activations: `out[a]` equals [`dot_q8_0_q8_0_avx2`]
/// for the Q8_0 blocks of `acts[a]` (scales as halves) bit for bit.
#[cfg(target_arch = "x86_64")]
pub fn dot_q8_0_q8r_multi_avx2(
x: &[u8],
acts: &[Q8rRef],
out: &mut [f32],
) -> Result<(), KernelError> {
check_multi(x, acts, out, Q8_0_BLOCK_BYTES)?;
with_avx2!(simd::x86::dot_q8_0_q8r_multi_avx2(x, acts, out))
}
/// Float to IEEE half bits with the F16C instruction; `None` if the CPU lacks it.
#[cfg(target_arch = "x86_64")]
pub fn f32_to_f16_bits_f16c(value: f32) -> Option<u16> {
if !avx2_available() {
return None;
}
// SAFETY: F16C verified just above.
Some(unsafe { simd::x86::f32_to_f16_f16c(value) })
}
// ------------------------------------------------------------------------- AVX-VNNI level --------
/// AVX-VNNI version of [`dot_i8i8_scalar`]. Activations must be in `[-127, 127]` to match it.
#[cfg(target_arch = "x86_64")]
pub fn dot_i8i8_avxvnni(w: &[i8], x: &[i8]) -> Result<i32, KernelError> {
check_i8(w, x)?;
with_avxvnni!(simd::x86::dot_i8i8_avxvnni(w, x))
}
/// AVX-VNNI version of [`dot_i4i8_scalar`]. Activations must be in `[-127, 127]` to match it.
#[cfg(target_arch = "x86_64")]
pub fn dot_i4i8_avxvnni(w4: &[u8], x: &[i8]) -> Result<i32, KernelError> {
check_i4(w4, x)?;
with_avxvnni!(simd::x86::dot_i4i8_avxvnni(w4, x))
}
/// AVX-VNNI level of [`dot_mxfp4_q8_0_scalar`]; equal within float summation order.
#[cfg(target_arch = "x86_64")]
pub fn dot_mxfp4_q8_0_avxvnni(x: &[u8], y: &[u8]) -> Result<f32, KernelError> {
check_mx(x, y)?;
with_avxvnni!(simd::x86::dot_mxfp4_q8_0_avxvnni(x, y))
}
/// AVX-VNNI level of [`mxfp4_q8_0_isums_scalar`]; exactly equal.
#[cfg(target_arch = "x86_64")]
pub fn mxfp4_q8_0_isums_avxvnni(x: &[u8], y: &[u8], out: &mut [i32]) -> Result<(), KernelError> {
let blocks = check_mx(x, y)?;
check_mx_out(blocks, out)?;
with_avxvnni!(simd::x86::mxfp4_q8_0_isums_avxvnni(x, y, out))
}
/// AVX-VNNI four-accumulator kernel for the "q8r" layout; bit-identical to [`dot_mxfp4_q8r4_avx2`].
#[cfg(target_arch = "x86_64")]
pub fn dot_mxfp4_q8r4_avxvnni(x: &[u8], ys: &[f32], yq: &[i8]) -> Result<f32, KernelError> {
check_q8r(x, ys, yq)?;
with_avxvnni!(simd::x86::dot_mxfp4_q8r4_avxvnni(x, ys, yq))
}
/// AVX-VNNI level of [`dot_q8_0_q8_0_scalar`]; equal within float summation order.
#[cfg(target_arch = "x86_64")]
pub fn dot_q8_0_q8_0_avxvnni(x: &[u8], y: &[u8]) -> Result<f32, KernelError> {
check_q8(x, y)?;
with_avxvnni!(simd::x86::dot_q8_0_q8_0_avxvnni(x, y))
}
/// AVX-VNNI level of [`q8_0_q8_0_isums_scalar`]; exactly equal.
#[cfg(target_arch = "x86_64")]
pub fn q8_0_q8_0_isums_avxvnni(x: &[u8], y: &[u8], out: &mut [i32]) -> Result<(), KernelError> {
let blocks = check_q8(x, y)?;
check_mx_out(blocks, out)?;
with_avxvnni!(simd::x86::q8_0_q8_0_isums_avxvnni(x, y, out))
}
/// AVX-VNNI level of [`dot_mxfp4_q8r4_multi_avx2`]: `out[a]` equals [`dot_mxfp4_q8r4_avxvnni`] for `acts[a]`.
#[cfg(target_arch = "x86_64")]
pub fn dot_mxfp4_q8r4_multi_avxvnni(
x: &[u8],
acts: &[Q8rRef],
out: &mut [f32],
) -> Result<(), KernelError> {
check_multi(x, acts, out, MXFP4_BLOCK_BYTES)?;
with_avxvnni!(simd::x86::dot_mxfp4_q8r4_multi_avxvnni(x, acts, out))
}
/// AVX-VNNI level of [`dot_q8_0_q8r_multi_avx2`]: `out[a]` equals [`dot_q8_0_q8_0_avxvnni`] for the Q8_0
/// blocks of `acts[a]`.
#[cfg(target_arch = "x86_64")]
pub fn dot_q8_0_q8r_multi_avxvnni(
x: &[u8],
acts: &[Q8rRef],
out: &mut [f32],
) -> Result<(), KernelError> {
check_multi(x, acts, out, Q8_0_BLOCK_BYTES)?;
with_avxvnni!(simd::x86::dot_q8_0_q8r_multi_avxvnni(x, acts, out))
}
// -------------------------------------------------------------------------- attention -----------
/// Largest start offset plus width a strided read may touch, or `None` when it would overflow.
fn strided_extent(count: usize, stride: usize, width: usize) -> Option<usize> {
if count == 0 {
return Some(0);
}
(count - 1).checked_mul(stride)?.checked_add(width)
}
fn check_strided(
count: usize,
stride: usize,
width: usize,
data_len: usize,
) -> Result<(), KernelError> {
if width == 0 || strided_extent(count, stride, width).is_none_or(|need| need > data_len) {
return Err(KernelError::LengthMismatch);
}
Ok(())
}
/// Checks the shapes of a group of `heads` query heads (`q.len() = heads * hd`) over `n` positions.
fn check_scores(
q: &[f32],
heads: usize,
keys_len: usize,
stride: usize,
n: usize,
out: &[f32],
) -> Result<(), KernelError> {
if heads == 0 || q.is_empty() || !q.len().is_multiple_of(heads) {
return Err(KernelError::LengthMismatch);
}
check_strided(n, stride, q.len() / heads, keys_len)?;
if heads.checked_mul(n).is_none_or(|need| out.len() < need) {
return Err(KernelError::LengthMismatch);
}
Ok(())
}
fn check_weighted_sum(
weights: &[f32],
heads: usize,
n: usize,
values_len: usize,
stride: usize,
out: &[f32],
) -> Result<(), KernelError> {
if heads == 0 || out.is_empty() || !out.len().is_multiple_of(heads) {
return Err(KernelError::LengthMismatch);
}
check_strided(n, stride, out.len() / heads, values_len)?;
if heads.checked_mul(n).is_none_or(|need| weights.len() < need) {
return Err(KernelError::LengthMismatch);
}
Ok(())
}
/// Attention scores for a group of `heads` query heads that share the keys:
/// `out[g * n + i] = scale * dot(q[g * hd ..][..hd], keys[i * stride ..][..hd])` with
/// `hd = q.len() / heads` (portable). `keys` must hold every position read.
pub fn attn_scores_scalar(
q: &[f32],
heads: usize,
keys: &[f32],
stride: usize,
n: usize,
scale: f32,
out: &mut [f32],
) -> Result<(), KernelError> {
check_scores(q, heads, keys.len(), stride, n, out)?;
simd::attn_scores_scalar(q, heads, keys, stride, n, scale, out);
Ok(())
}
/// AVX2 + FMA level of [`attn_scores_scalar`]; equal within float summation order.
#[cfg(target_arch = "x86_64")]
pub fn attn_scores_avx2(
q: &[f32],
heads: usize,
keys: &[f32],
stride: usize,
n: usize,
scale: f32,
out: &mut [f32],
) -> Result<(), KernelError> {
check_scores(q, heads, keys.len(), stride, n, out)?;
with_avx2!(simd::x86::attn_scores_avx2(
q, heads, keys, stride, n, scale, out
))
}
/// Weighted sums of the values for a group of heads:
/// `out[g * hd ..][..hd] = sum_i weights[g * n + i] * values[i * stride ..][..hd]` with
/// `hd = out.len() / heads` (portable).
pub fn attn_weighted_sum_scalar(
weights: &[f32],
heads: usize,
n: usize,
values: &[f32],
stride: usize,
out: &mut [f32],
) -> Result<(), KernelError> {
check_weighted_sum(weights, heads, n, values.len(), stride, out)?;
simd::attn_weighted_sum_scalar(weights, heads, n, values, stride, out);
Ok(())
}
/// AVX2 + FMA level of [`attn_weighted_sum_scalar`]; equal within float summation order.
#[cfg(target_arch = "x86_64")]
pub fn attn_weighted_sum_avx2(
weights: &[f32],
heads: usize,
n: usize,
values: &[f32],
stride: usize,
out: &mut [f32],
) -> Result<(), KernelError> {
check_weighted_sum(weights, heads, n, values.len(), stride, out)?;
with_avx2!(simd::x86::attn_weighted_sum_avx2(
weights, heads, n, values, stride, out
))
}
/// As [`attn_scores_scalar`] with the keys stored as IEEE half floats (bit patterns).
pub fn attn_scores_f16_scalar(
q: &[f32],
heads: usize,
keys: &[u16],
stride: usize,
n: usize,
scale: f32,
out: &mut [f32],
) -> Result<(), KernelError> {
check_scores(q, heads, keys.len(), stride, n, out)?;
simd::attn_scores_f16_scalar(q, heads, keys, stride, n, scale, out);
Ok(())
}
/// AVX2 + FMA + F16C level of [`attn_scores_f16_scalar`]; equal within float summation order.
#[cfg(target_arch = "x86_64")]
pub fn attn_scores_f16_avx2(
q: &[f32],
heads: usize,
keys: &[u16],
stride: usize,
n: usize,
scale: f32,
out: &mut [f32],
) -> Result<(), KernelError> {
check_scores(q, heads, keys.len(), stride, n, out)?;
with_avx2!(simd::x86::attn_scores_f16_avx2(
q, heads, keys, stride, n, scale, out
))
}
/// As [`attn_weighted_sum_scalar`] with the values stored as IEEE half floats.
pub fn attn_weighted_sum_f16_scalar(
weights: &[f32],
heads: usize,
n: usize,
values: &[u16],
stride: usize,
out: &mut [f32],
) -> Result<(), KernelError> {
check_weighted_sum(weights, heads, n, values.len(), stride, out)?;
simd::attn_weighted_sum_f16_scalar(weights, heads, n, values, stride, out);
Ok(())
}
/// AVX2 + FMA + F16C level of [`attn_weighted_sum_f16_scalar`]; equal within float summation order.
#[cfg(target_arch = "x86_64")]
pub fn attn_weighted_sum_f16_avx2(
weights: &[f32],
heads: usize,
n: usize,
values: &[u16],
stride: usize,
out: &mut [f32],
) -> Result<(), KernelError> {
check_weighted_sum(weights, heads, n, values.len(), stride, out)?;
with_avx2!(simd::x86::attn_weighted_sum_f16_avx2(
weights, heads, n, values, stride, out
))
}
fn check_swiglu(gate: &[f32], up: &[f32], out: &[f32]) -> Result<(), KernelError> {
if gate.len() == up.len() && gate.len() == out.len() {
Ok(())
} else {
Err(KernelError::LengthMismatch)
}
}
/// The gpt-oss expert activation, element by element (portable):
/// `out = min(g, limit) * sigmoid(alpha * min(g, limit)) * (clamp(u, -limit, limit) + 1)`.
pub fn swiglu_oai_scalar(
gate: &[f32],
up: &[f32],
alpha: f32,
limit: f32,
out: &mut [f32],
) -> Result<(), KernelError> {
check_swiglu(gate, up, out)?;
simd::swiglu_oai_scalar(gate, up, alpha, limit, out);
Ok(())
}
/// AVX2 + FMA level of [`swiglu_oai_scalar`] with a vector `exp` (relative error below about 1e-6).
#[cfg(target_arch = "x86_64")]
pub fn swiglu_oai_avx2(
gate: &[f32],
up: &[f32],
alpha: f32,
limit: f32,
out: &mut [f32],
) -> Result<(), KernelError> {
check_swiglu(gate, up, out)?;
with_avx2!(simd::x86::swiglu_oai_avx2(gate, up, alpha, limit, out))
}
/// Floats to IEEE half bit patterns, round to nearest even (portable). The slices must be equally long.
pub fn f32_to_f16_slice_scalar(src: &[f32], dst: &mut [u16]) -> Result<(), KernelError> {
if src.len() != dst.len() {
return Err(KernelError::LengthMismatch);
}
simd::f32_to_f16_slice_scalar(src, dst);
Ok(())
}
/// F16C level of [`f32_to_f16_slice_scalar`]; bit-identical to it.
#[cfg(target_arch = "x86_64")]
pub fn f32_to_f16_slice_avx2(src: &[f32], dst: &mut [u16]) -> Result<(), KernelError> {
if src.len() != dst.len() {
return Err(KernelError::LengthMismatch);
}
with_avx2!(simd::x86::f32_to_f16_slice_avx2(src, dst))
}
/// IEEE half bit patterns to floats (portable). The slices must be equally long.
pub fn f16_to_f32_slice_scalar(src: &[u16], dst: &mut [f32]) -> Result<(), KernelError> {
if src.len() != dst.len() {
return Err(KernelError::LengthMismatch);
}
simd::f16_to_f32_slice_scalar(src, dst);
Ok(())
}
/// F16C level of [`f16_to_f32_slice_scalar`]; bit-identical to it.
#[cfg(target_arch = "x86_64")]
pub fn f16_to_f32_slice_avx2(src: &[u16], dst: &mut [f32]) -> Result<(), KernelError> {
if src.len() != dst.len() {
return Err(KernelError::LengthMismatch);
}
with_avx2!(simd::x86::f16_to_f32_slice_avx2(src, dst))
}
/// Replaces each `x[i]` by `exp(x[i] - max)` and returns their sum (portable).
pub fn exp_shift_sum_scalar(x: &mut [f32], max: f32) -> Result<f32, KernelError> {
Ok(simd::exp_shift_sum_scalar(x, max))
}
/// AVX2 + FMA level of [`exp_shift_sum_scalar`]: relative error below 3e-7 per element for arguments
/// above -87 (smaller arguments give 0).
#[cfg(target_arch = "x86_64")]
pub fn exp_shift_sum_avx2(x: &mut [f32], max: f32) -> Result<f32, KernelError> {
with_avx2!(simd::x86::exp_shift_sum_avx2(x, max))
}
// ------------------------------------------------------------------------------- tiles -----------
pub use simd::ActRef;
/// Largest number of rows or activations in one tile.
pub const TILE_MAX: usize = 4;
/// An activation row prepared for the tile kernels: the "q8r" scales and quants plus the vector forms
/// the AVX-VNNI level reads (see [`ActRef`]).
#[derive(Clone, Debug)]
pub struct PreparedAct {
pub scales: Vec<f32>,
pub scales_bcast: Vec<f32>,
pub quants: Vec<i8>,
pub corr: Vec<i32>,
}
impl PreparedAct {
/// `scales` has one entry per 32 quants.
pub fn new(scales: Vec<f32>, quants: Vec<i8>) -> Result<Self, KernelError> {
if quants.len() != scales.len() * BLOCK_ELEMS {
return Err(KernelError::LengthMismatch);
}
let mut scales_bcast = vec![0.0; scales.len() * 8];
let mut corr = vec![0; scales.len() * 8];
simd::prepare_act(&scales, &quants, &mut scales_bcast, &mut corr);
Ok(Self {
scales,
scales_bcast,
quants,
corr,
})
}
pub fn view(&self) -> ActRef<'_> {
ActRef {
scales: &self.scales,
scales_bcast: &self.scales_bcast,
quants: &self.quants,
corr: &self.corr,
}
}
}
/// Checks a tile: `x.len()` rows of `block_bytes`-byte blocks against activations, and an output of
/// `rows * activations` values.
fn check_tile(
x: &[&[u8]],
acts: &[ActRef],
out: &[f32],
block_bytes: usize,
) -> Result<(), KernelError> {
let (rows, n_acts) = (x.len(), acts.len());
if rows == 0 || rows > TILE_MAX || n_acts == 0 || n_acts > TILE_MAX {
return Err(KernelError::TileShape);
}
let blocks = x[0].len() / block_bytes;
let ok = x.iter().all(|r| r.len() == blocks * block_bytes)
&& acts.iter().all(|a| {
a.scales.len() == blocks
&& a.scales_bcast.len() == blocks * 8
&& a.quants.len() == blocks * BLOCK_ELEMS
&& a.corr.len() == blocks * 8
})
&& out.len() == rows * n_acts;
if ok {
Ok(())
} else {
Err(KernelError::LengthMismatch)
}
}
/// A tile of MXFP4 weight rows against prepared activations, portable reference. `out[r * A + a]` is
/// the dot of row `r` with activation `a`; the SIMD levels equal it up to float summation order.
pub fn mxfp4_q8r_tile_scalar(
x: &[&[u8]],
acts: &[ActRef],
out: &mut [f32],
) -> Result<(), KernelError> {
check_tile(x, acts, out, MXFP4_BLOCK_BYTES)?;
simd::mxfp4_q8r_tile_scalar(x, acts, out);
Ok(())
}
/// A tile of Q8_0 weight rows against prepared activations, portable reference.
pub fn q8_q8r_tile_scalar(
x: &[&[u8]],
acts: &[ActRef],
out: &mut [f32],
) -> Result<(), KernelError> {
check_tile(x, acts, out, Q8_0_BLOCK_BYTES)?;
simd::q8_q8r_tile_scalar(x, acts, out);
Ok(())
}
/// AVX2 level of [`mxfp4_q8r_tile_scalar`]. Every output is bit-identical to the 1x1 tile at this level.
#[cfg(target_arch = "x86_64")]
pub fn mxfp4_q8r_tile_avx2(
x: &[&[u8]],
acts: &[ActRef],
out: &mut [f32],
) -> Result<(), KernelError> {
check_tile(x, acts, out, MXFP4_BLOCK_BYTES)?;
with_avx2!(simd::x86::mxfp4_q8r_tile_avx2(x, acts, out))
}
/// AVX-VNNI level of [`mxfp4_q8r_tile_scalar`]. Every output is bit-identical to the 1x1 tile at this
/// level; versus AVX2 it differs only in float rounding.
#[cfg(target_arch = "x86_64")]
pub fn mxfp4_q8r_tile_avxvnni(
x: &[&[u8]],
acts: &[ActRef],
out: &mut [f32],
) -> Result<(), KernelError> {
check_tile(x, acts, out, MXFP4_BLOCK_BYTES)?;
with_avxvnni!(simd::x86::mxfp4_q8r_tile_avxvnni(x, acts, out))
}
/// AVX2 level of [`q8_q8r_tile_scalar`].
#[cfg(target_arch = "x86_64")]
pub fn q8_q8r_tile_avx2(x: &[&[u8]], acts: &[ActRef], out: &mut [f32]) -> Result<(), KernelError> {
check_tile(x, acts, out, Q8_0_BLOCK_BYTES)?;
with_avx2!(simd::x86::q8_q8r_tile_avx2(x, acts, out))
}
/// AVX-VNNI level of [`q8_q8r_tile_scalar`].
#[cfg(target_arch = "x86_64")]
pub fn q8_q8r_tile_avxvnni(
x: &[&[u8]],
acts: &[ActRef],
out: &mut [f32],
) -> Result<(), KernelError> {
check_tile(x, acts, out, Q8_0_BLOCK_BYTES)?;
with_avxvnni!(simd::x86::q8_q8r_tile_avxvnni(x, acts, out))
}
/// Test-only access to the pinned ggml reference code (MIT, vendored in the control plane).
/// Present only with the `ggml-oracle` feature; the runtime never enables it.
#[cfg(feature = "ggml-oracle")]
pub mod oracle {
use super::{BLOCK_ELEMS, MXFP4_BLOCK_BYTES, Q8_0_BLOCK_BYTES};
mod ffi {
unsafe extern "C" {
pub fn leleka_oracle_mxfp4_block_bytes() -> u32;
pub fn leleka_oracle_q8_0_block_bytes() -> u32;
pub fn leleka_oracle_dequantize_mxfp4(blocks: *const u8, out: *mut f32, k: i64);
pub fn leleka_oracle_quantize_mxfp4(x: *const f32, blocks: *mut u8, k: i64);
pub fn leleka_oracle_dequantize_q8_0(blocks: *const u8, out: *mut f32, k: i64);
pub fn leleka_oracle_quantize_q8_0(x: *const f32, blocks: *mut u8, k: i64);
}
}
/// Block geometry as the pinned ggml compiled it: `(mxfp4_bytes, q8_0_bytes)`.
pub fn block_bytes() -> (usize, usize) {
// SAFETY: take no arguments and read nothing.
unsafe {
(
ffi::leleka_oracle_mxfp4_block_bytes() as usize,
ffi::leleka_oracle_q8_0_block_bytes() as usize,
)
}
}
/// Copy to storage aligned for ggml's structs (they hold half words).
fn aligned(bytes: &[u8]) -> Vec<u64> {
let mut words = vec![0u64; bytes.len().div_ceil(8)];
for (i, chunk) in bytes.chunks(8).enumerate() {
let mut word = [0u8; 8];
word[..chunk.len()].copy_from_slice(chunk);
words[i] = u64::from_le_bytes(word);
}
words
}
fn unaligned(words: &[u64], len: usize) -> Vec<u8> {
let mut bytes: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
bytes.truncate(len);
bytes
}
/// ggml's `dequantize_row_mxfp4` over whole blocks.
pub fn dequantize_mxfp4(blocks: &[u8]) -> Vec<f32> {
assert_eq!(blocks.len() % MXFP4_BLOCK_BYTES, 0);
let n = blocks.len() / MXFP4_BLOCK_BYTES * BLOCK_ELEMS;
let words = aligned(blocks);
let mut out = vec![0f32; n];
// SAFETY: `words` holds all source bytes with 8-byte alignment; `out` has `n` elements.
unsafe {
ffi::leleka_oracle_dequantize_mxfp4(words.as_ptr().cast(), out.as_mut_ptr(), n as i64)
};
out
}
/// ggml's `quantize_row_mxfp4_ref` of `x.len()` floats (a multiple of 32).
pub fn quantize_mxfp4(x: &[f32]) -> Vec<u8> {
assert_eq!(x.len() % BLOCK_ELEMS, 0);
let len = x.len() / BLOCK_ELEMS * MXFP4_BLOCK_BYTES;
let mut words = vec![0u64; len.div_ceil(8)];
// SAFETY: `words` has at least `len` writable bytes; `x` has `x.len()` floats.
unsafe {
ffi::leleka_oracle_quantize_mxfp4(x.as_ptr(), words.as_mut_ptr().cast(), x.len() as i64)
};
unaligned(&words, len)
}
/// ggml's `dequantize_row_q8_0` over whole blocks.
pub fn dequantize_q8_0(blocks: &[u8]) -> Vec<f32> {
assert_eq!(blocks.len() % Q8_0_BLOCK_BYTES, 0);
let n = blocks.len() / Q8_0_BLOCK_BYTES * BLOCK_ELEMS;
let words = aligned(blocks);
let mut out = vec![0f32; n];
// SAFETY: `words` holds all source bytes with 8-byte alignment; `out` has `n` elements.
unsafe {
ffi::leleka_oracle_dequantize_q8_0(words.as_ptr().cast(), out.as_mut_ptr(), n as i64)
};
out
}
/// ggml's `quantize_row_q8_0_ref` of `x.len()` floats (a multiple of 32).
pub fn quantize_q8_0(x: &[f32]) -> Vec<u8> {
assert_eq!(x.len() % BLOCK_ELEMS, 0);
let len = x.len() / BLOCK_ELEMS * Q8_0_BLOCK_BYTES;
let mut words = vec![0u64; len.div_ceil(8)];
// SAFETY: `words` has at least `len` writable bytes; `x` has `x.len()` floats.
unsafe {
ffi::leleka_oracle_quantize_q8_0(x.as_ptr(), words.as_mut_ptr().cast(), x.len() as i64)
};
unaligned(&words, len)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn scalar_matches_a_hand_computed_value() {
assert_eq!(dot_i8i8_scalar(&[1, -2, 3], &[4, 5, -6]), Ok(4 - 10 - 18));
// nibbles 0x0..0xF in byte pairs: values (n - 8): byte 0x10 -> low 0 => -8, high 1 => -7
assert_eq!(dot_i4i8_scalar(&[0x10], &[1, 1]), Ok(-8 - 7));
// odd length reads only the low nibble of the last byte
assert_eq!(dot_i4i8_scalar(&[0xF8], &[2]), Ok(0));
}
#[test]
fn length_and_size_errors_are_refused_before_any_read() {
assert_eq!(
dot_i8i8_scalar(&[1], &[1, 2]),
Err(KernelError::LengthMismatch)
);
assert_eq!(
dot_i4i8_scalar(&[0, 0], &[1, 2, 3, 4, 5]),
Err(KernelError::LengthMismatch)
);
let big = vec![0i8; MAX_DOT_LEN + 1];
assert_eq!(dot_i8i8_scalar(&big, &big), Err(KernelError::TooLong));
}
#[cfg(target_arch = "x86_64")]
#[test]
fn simd_wrappers_refuse_bad_lengths_before_touching_memory() {
if !avx2_available() {
return;
}
assert_eq!(
dot_i8i8_avx2(&[1], &[1, 2]),
Err(KernelError::LengthMismatch)
);
assert_eq!(
dot_mxfp4_q8_0_avx2(&[0; 16], &[0; 34]),
Err(KernelError::LengthMismatch)
);
assert_eq!(
dot_mxfp4_q8r4_avx2(&[0; 17], &[1.0], &[0; 31]),
Err(KernelError::LengthMismatch)
);
assert_eq!(
quantize_q8_0_avx2(&[0.0; 31], &mut [0; 34]),
Err(KernelError::LengthMismatch)
);
}
}