Files
leleka/crates/cpu-sys/src/lib.rs
T

153 lines
6.5 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::{AttnShape, MULTI_MAX, Q8rRef, ScoreSpec};
/// 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")
}
// ---------------------------------------------------------------------------- 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 })
}};
}
pub use simd::ActRef;
/// 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;
#[cfg(test)]
mod tests;
mod checks;
use checks::{
check_i4, check_i8, check_multi, check_mx, check_mx_out, check_q8, check_q8r, check_quantize, check_scores,
check_swiglu, check_tile, check_weighted_sum,
};
mod portable;
pub use portable::{
dot_i4i8_scalar, dot_i8i8_scalar, dot_mxfp4_q8_0_scalar, dot_mxfp4_q8r_multi_scalar, dot_mxfp4_q8r_scalar,
dot_q8_0_q8_0_scalar, dot_q8_0_q8r_multi_scalar, f32_to_f16_bits_scalar, mxfp4_q8_0_isums_scalar,
q8_0_q8_0_isums_scalar, quantize_q8_0_scalar,
};
mod x86_dot_kernels;
#[cfg(target_arch = "x86_64")]
pub use x86_dot_kernels::{
dot_i4i8_avx2, dot_i4i8_avxvnni, dot_i8i8_avx2, dot_i8i8_avxvnni, dot_mxfp4_q8_0_avx2, dot_mxfp4_q8_0_avxvnni,
dot_mxfp4_q8r_avx2, dot_mxfp4_q8r4_avx2, dot_mxfp4_q8r4_avxvnni, dot_mxfp4_q8r4_multi_avx2,
dot_mxfp4_q8r4_multi_avxvnni, dot_q8_0_q8_0_avx2, dot_q8_0_q8_0_avxvnni, dot_q8_0_q8r_multi_avx2,
dot_q8_0_q8r_multi_avxvnni, f32_to_f16_bits_f16c, mxfp4_q8_0_isums_avx2, mxfp4_q8_0_isums_avxvnni,
q8_0_q8_0_isums_avx2, q8_0_q8_0_isums_avxvnni, quantize_q8_0_avx2,
};
mod checked_attention_kernels;
#[cfg(target_arch = "x86_64")]
pub use checked_attention_kernels::{
attn_scores_avx2, attn_scores_f16_avx2, attn_weighted_sum_avx2, attn_weighted_sum_f16_avx2, exp_shift_sum_avx2,
f16_to_f32_slice_avx2, f32_to_f16_slice_avx2, swiglu_oai_avx2,
};
pub use checked_attention_kernels::{
attn_scores_f16_scalar, attn_scores_scalar, attn_weighted_sum_f16_scalar, attn_weighted_sum_scalar,
exp_shift_sum_scalar, f16_to_f32_slice_scalar, f32_to_f16_slice_scalar, swiglu_oai_scalar,
};
mod tiles;
pub use tiles::{PreparedAct, TILE_MAX, mxfp4_q8r_tile_scalar, q8_q8r_tile_scalar};
#[cfg(target_arch = "x86_64")]
pub use tiles::{mxfp4_q8r_tile_avx2, mxfp4_q8r_tile_avxvnni, q8_q8r_tile_avx2, q8_q8r_tile_avxvnni};