Files
leleka/crates/cpu-kernels/src/dispatch.rs
T

302 lines
14 KiB
Rust

//! The table of kernel entry points for one level, and the checked calls through it.
#[allow(unused_imports)]
use super::*;
pub(super) type DotI8 = fn(&[i8], &[i8]) -> Result<i32, KernelError>;
pub(super) type DotI4 = fn(&[u8], &[i8]) -> Result<i32, KernelError>;
pub(super) type DotMx = fn(&[u8], &[u8]) -> Result<f32, KernelError>;
pub(super) type IsumsMx = fn(&[u8], &[u8], &mut [i32]) -> Result<(), KernelError>;
pub(super) type QuantQ8 = fn(&[f32], &mut [u8]) -> Result<(), KernelError>;
pub(super) type DotMxR = fn(&[u8], &[f32], &[i8]) -> Result<f32, KernelError>;
pub(super) type DotMulti = fn(&[u8], &[Q8rRef], &mut [f32]) -> Result<(), KernelError>;
pub(super) type AttnScores = fn(&[f32], &[u16], ScoreSpec, &mut [f32]) -> Result<(), KernelError>;
pub(super) type AttnSum = fn(&[f32], &[u16], AttnShape, &mut [f32]) -> Result<(), KernelError>;
pub(super) type ToHalf = fn(&[f32], &mut [u16]) -> Result<(), KernelError>;
pub(super) type FromHalf = fn(&[u16], &mut [f32]) -> Result<(), KernelError>;
pub(super) type RowsDot = fn(&[f32], &[f32], usize, usize, &mut [f32]) -> Result<(), KernelError>;
pub(super) type Swiglu = fn(&[f32], &[f32], f32, f32, &mut [f32]) -> Result<(), KernelError>;
pub(super) type ExpSum = fn(&mut [f32], f32) -> Result<f32, KernelError>;
/// The layout of a `rows_dot` call: `n` rows that lie `stride` floats apart.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct RowsShape {
pub stride: usize,
pub n: usize,
}
/// The two constants of the gpt-oss expert activation.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SwigluOaiParams {
pub alpha: f32,
pub limit: f32,
}
/// A resolved set of kernels for one level. Cheap to copy; resolve once at startup.
#[derive(Clone, Copy)]
pub struct Dispatch {
pub(super) isa: Isa,
pub(super) dot_i8i8: DotI8,
pub(super) dot_i4i8: DotI4,
pub(super) dot_mxfp4_q8_0: DotMx,
pub(super) isums_mxfp4_q8_0: IsumsMx,
pub(super) quantize_q8_0: QuantQ8,
pub(super) dot_mxfp4_q8r: DotMxR,
pub(super) dot_q8_0_q8_0: DotMx,
pub(super) isums_q8_0_q8_0: IsumsMx,
pub(super) dot_mxfp4_q8r_multi: DotMulti,
pub(super) dot_q8_0_q8r_multi: DotMulti,
pub(super) attn_scores: AttnScores,
pub(super) attn_weighted_sum: AttnSum,
pub(super) exp_shift_sum: ExpSum,
pub(super) f32_to_f16: ToHalf,
pub(super) f16_to_f32: FromHalf,
pub(super) rows_dot: RowsDot,
pub(super) 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::scalar_table(isa),
#[cfg(target_arch = "x86_64")]
Isa::Avx2 => Self::avx2_table(isa),
#[cfg(target_arch = "x86_64")]
Isa::AvxVnni => Self::avxvnni_table(isa),
#[cfg(not(target_arch = "x86_64"))]
Isa::Avx2 | Isa::AvxVnni => return Err(DispatchError::Unsupported(isa)),
})
}
fn scalar_table(isa: Isa) -> Self {
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| {
let shape = AttnShape { heads: 1, n, stride };
leleka_cpu_sys::attn_scores_scalar(q, rows, ScoreSpec { shape, scale: 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")]
fn avx2_table(isa: Isa) -> Self {
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| {
let shape = AttnShape { heads: 1, n, stride };
leleka_cpu_sys::attn_scores_avx2(q, rows, ScoreSpec { shape, scale: 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")]
fn avxvnni_table(isa: Isa) -> Self {
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| {
let shape = AttnShape { heads: 1, n, stride };
leleka_cpu_sys::attn_scores_avx2(q, rows, ScoreSpec { shape, scale: 1.0 }, out)
},
swiglu_oai: leleka_cpu_sys::swiglu_oai_avx2,
exp_shift_sum: leleka_cpu_sys::exp_shift_sum_avx2,
}
}
/// 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.
pub fn attn_scores(&self, q: &[f32], keys: &[u16], spec: ScoreSpec, out: &mut [f32]) -> Result<(), KernelError> {
(self.attn_scores)(q, keys, spec, 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],
values: &[u16],
shape: AttnShape,
out: &mut [f32],
) -> Result<(), KernelError> {
(self.attn_weighted_sum)(weights, values, shape, 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], shape: RowsShape, out: &mut [f32]) -> Result<(), KernelError> {
(self.rows_dot)(q, rows, shape.stride, shape.n, out)
}
/// The gpt-oss expert activation for `gate` and `up` (equal lengths) into `out`.
pub fn swiglu_oai(
&self,
gate: &[f32],
up: &[f32],
params: SwigluOaiParams,
out: &mut [f32],
) -> Result<(), KernelError> {
(self.swiglu_oai)(gate, up, params.alpha, params.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)
}
}