Files
leleka/crates/cpu-kernels/tests/q8.rs
T
Pavlo RatushnyiandClaude Sonnet 5.5 fa921a2ced feat: add Q8_0 activation quantizer and Q8_0 x Q8_0 dot kernels (STRA-211)
Completes the Q8_0 side of the CPU runtime's kernel set: a float-to-Q8_0
quantizer (scale = amax / 127 as a half, quants rounded to nearest even and
clamped to [-127, 127]) and the Q8_0 x Q8_0 dot, each at scalar, AVX2 and AVX-VNNI
(the quantizer shares the AVX2 code). Tests: the quantizer is bit-identical across
levels and equal to the vendored ggml reference except on exact .5 ties; per-block
integer sums are exact; float results are within the stated tolerance of an f64
reference built from ggml's dequantizer; the portable half conversion equals the
F16C instruction on over a million values. Windows MSVC and Linux GCC, debug and
release. Replaces _cvtss_sh (not available in MSVC) with the packed conversion.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 16:01:32 +02:00

304 lines
11 KiB
Rust

//! Q8_0 kernels (activation quantizer and Q8_0 x Q8_0 dot) against the pinned ggml reference code
//! (llama.cpp commit 3cf03257f219afbe7334045ff7c6a06ac68c627d via the test-only `ggml-oracle` feature).
//!
//! Rules written before the kernels were run:
//! * Quantizer: every SIMD level is bit-identical to the scalar level. Against ggml's portable
//! reference, the half scale is exactly equal and each quant is equal except where the scaled value
//! is an exact .5 tie (ggml's reference rounds ties away from zero, llama.cpp's x86 SIMD path and this
//! quantizer round to even); there the difference is at most 1.
//! * Dot: per-block integer sums exactly equal at every level and to a naive computation; the float
//! result within (blocks + 16) * 2^-23 * sum|term| of an f64 reference from ggml's dequantizers.
//! * Float to half conversion: the portable code equals the F16C instruction for every tested value.
use leleka_cpu_kernels::{Dispatch, Isa, KernelError};
use leleka_cpu_sys::oracle;
use leleka_cpu_sys::{BLOCK_ELEMS, Q8_0_BLOCK_BYTES};
struct Lcg(u64);
impl Lcg {
fn next(&mut self) -> u64 {
self.0 = self
.0
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
self.0 >> 11
}
fn unit(&mut self) -> f64 {
(self.next() as f64 + 0.5) / (1u64 << 53) as f64
}
fn gauss(&mut self) -> f32 {
let (a, b) = (self.unit(), self.unit());
((-2.0 * a.ln()).sqrt() * (2.0 * std::f64::consts::PI * b).cos()) as f32
}
}
fn levels() -> Vec<Dispatch> {
Isa::ALL
.iter()
.filter_map(|isa| Dispatch::with_isa(*isa).ok())
.collect()
}
fn data_sets(rng: &mut Lcg, blocks: usize) -> Vec<(&'static str, Vec<f32>)> {
let n = blocks * BLOCK_ELEMS;
let gauss =
|rng: &mut Lcg, scale: f32| (0..n).map(|_| rng.gauss() * scale).collect::<Vec<f32>>();
let mut spike = vec![0.0f32; n];
if n > 0 {
spike[n / 2] = 3.5;
}
vec![
("unit gaussian", gauss(rng, 1.0)),
("small", gauss(rng, 1e-3)),
("large", gauss(rng, 3.0e4)),
("tiny near subnormal", gauss(rng, 1e-30)),
("all zero", vec![0.0; n]),
("single spike", spike),
]
}
fn block_scale_bits(q: &[u8], block: usize) -> u16 {
u16::from_le_bytes([q[block * Q8_0_BLOCK_BYTES], q[block * Q8_0_BLOCK_BYTES + 1]])
}
#[test]
fn portable_half_conversion_equals_the_f16c_instruction() {
if leleka_cpu_sys::f32_to_f16_bits_f16c(1.0).is_none() {
return;
}
let mut rng = Lcg(0x16);
let mut values: Vec<f32> = vec![
0.0,
-0.0,
1.0,
-1.0,
65504.0,
65519.99,
65520.0,
65536.0,
1e30,
-1e30,
5.960_464_5e-8, // smallest half subnormal
2.980_232_2e-8, // half of it: a tie that rounds to even (zero)
2.980_233e-8,
6.097_555e-5, // largest half subnormal
6.103_515_6e-5, // smallest half normal
1e-8,
f32::MIN_POSITIVE,
f32::INFINITY,
f32::NEG_INFINITY,
];
// Every half value, its midpoints with the next value, and values a hair either side.
for h in 0..0x7C00u32 {
let lo = f32::from_bits(half_bits_to_f32_bits(h as u16));
let hi = f32::from_bits(half_bits_to_f32_bits((h + 1) as u16));
let mid = (f64::from(lo) + f64::from(hi)) / 2.0;
values.push(lo);
values.push(mid as f32);
values.push(f32::from_bits((mid as f32).to_bits() + 1));
values.push(f32::from_bits((mid as f32).to_bits() - 1));
}
for _ in 0..400_000 {
let bits = (rng.next() as u32) & 0x7FFF_FFFF;
let v = f32::from_bits(bits);
if v.is_finite() {
values.push(v);
values.push(-v);
}
}
for v in values {
let a = leleka_cpu_sys::f32_to_f16_bits_scalar(v);
let b = leleka_cpu_sys::f32_to_f16_bits_f16c(v).unwrap();
assert_eq!(a, b, "value {v:e} (bits {:08x})", v.to_bits());
}
}
/// Exact conversion of a half bit pattern (finite, non-negative) to f32 bits, independent of the code
/// under test.
fn half_bits_to_f32_bits(h: u16) -> u32 {
let exp = u32::from((h >> 10) & 0x1F);
let man = u32::from(h & 0x3FF);
if exp == 0 {
if man == 0 {
return 0;
}
let value = man as f32 * 2f32.powi(-24);
return value.to_bits();
}
((exp + 112) << 23) | (man << 13)
}
#[test]
fn quantizer_levels_are_bit_identical_and_match_ggml_except_on_ties() {
let mut rng = Lcg(0x08);
for blocks in [0usize, 1, 2, 3, 7, 90, 181] {
for (name, x) in data_sets(&mut rng, blocks) {
let mut scalar = vec![0u8; blocks * Q8_0_BLOCK_BYTES];
Dispatch::with_isa(Isa::Scalar)
.unwrap()
.quantize_q8_0(&x, &mut scalar)
.unwrap();
for d in levels() {
let mut got = vec![0u8; blocks * Q8_0_BLOCK_BYTES];
d.quantize_q8_0(&x, &mut got).unwrap();
assert_eq!(got, scalar, "level {} {name} blocks {blocks}", d.isa());
}
let reference = oracle::quantize_q8_0(&x);
assert_eq!(reference.len(), scalar.len());
for b in 0..blocks {
assert_eq!(
block_scale_bits(&scalar, b),
block_scale_bits(&reference, b),
"{name} block {b} scale"
);
let d = leleka_half_to_f32(block_scale_bits(&reference, b));
// The reference derives its multiplier from the unrounded scale; recompute it the same way.
let amax = x[b * 32..(b + 1) * 32]
.iter()
.fold(0f32, |m, v| m.max(v.abs()));
let unrounded = amax / 127.0;
let id = if unrounded != 0.0 {
1.0 / unrounded
} else {
0.0
};
let _ = d;
for j in 0..32 {
let ours = scalar[b * Q8_0_BLOCK_BYTES + 2 + j] as i8;
let theirs = reference[b * Q8_0_BLOCK_BYTES + 2 + j] as i8;
let scaled = x[b * 32 + j] * id;
let tie = (scaled - scaled.trunc()).abs() == 0.5;
if tie {
assert!(
(i32::from(ours) - i32::from(theirs)).abs() <= 1,
"{name} tie {scaled}"
);
} else {
assert_eq!(ours, theirs, "{name} block {b} element {j} scaled {scaled}");
}
assert!(ours >= -127, "quant -128 must never be produced");
}
}
}
}
}
fn leleka_half_to_f32(bits: u16) -> f32 {
f32::from_bits(half_bits_to_f32_bits(bits & 0x7FFF))
* if bits & 0x8000 != 0 { -1.0 } else { 1.0 }
}
#[test]
fn quantizer_rounds_exact_ties_to_even() {
// amax = 127 gives scale 1.0 exactly, so the inputs are their own scaled values.
let mut x = vec![0.0f32; 32];
x[0] = 127.0;
x[1] = 0.5; // tie -> 0
x[2] = 1.5; // tie -> 2
x[3] = 2.5; // tie -> 2
x[4] = -0.5; // tie -> 0
x[5] = -2.5; // tie -> -2
for d in levels() {
let mut out = vec![0u8; Q8_0_BLOCK_BYTES];
d.quantize_q8_0(&x, &mut out).unwrap();
let q: Vec<i8> = out[2..8].iter().map(|v| *v as i8).collect();
assert_eq!(q, vec![127, 0, 2, 2, 0, -2], "level {}", d.isa());
}
}
fn naive_isums(x: &[u8], y: &[u8]) -> Vec<i32> {
x.as_chunks::<Q8_0_BLOCK_BYTES>()
.0
.iter()
.zip(y.as_chunks::<Q8_0_BLOCK_BYTES>().0)
.map(|(a, b)| {
(0..32)
.map(|j| i32::from(a[2 + j] as i8) * i32::from(b[2 + j] as i8))
.sum()
})
.collect()
}
fn reference(x: &[u8], y: &[u8]) -> (f64, f64) {
let w = oracle::dequantize_q8_0(x);
let a = oracle::dequantize_q8_0(y);
let mut sum = 0f64;
let mut abs = 0f64;
for (wv, av) in w.iter().zip(&a) {
let t = f64::from(*wv) * f64::from(*av);
sum += t;
abs += t.abs();
}
(sum, abs)
}
#[test]
fn q8_dot_is_exact_per_block_and_within_tolerance_overall() {
let mut rng = Lcg(0x88);
for blocks in [0usize, 1, 2, 3, 4, 5, 8, 9, 90, 91, 180, 2000] {
let n = blocks * BLOCK_ELEMS;
let w: Vec<f32> = (0..n).map(|_| rng.gauss() * 0.05).collect();
let a: Vec<f32> = (0..n).map(|_| rng.gauss()).collect();
// Weights quantized by ggml's reference (as they would be in a GGUF); activations by ours.
let wq = oracle::quantize_q8_0(&w);
let mut aq = vec![0u8; blocks * Q8_0_BLOCK_BYTES];
Dispatch::best().quantize_q8_0(&a, &mut aq).unwrap();
let expected_sums = naive_isums(&wq, &aq);
let (expected, abs_sum) = reference(&wq, &aq);
let tol = (blocks as f64 + 16.0) * 2f64.powi(-23) * abs_sum;
for d in levels() {
let mut sums = vec![i32::MIN; blocks];
d.q8_0_q8_0_block_sums(&wq, &aq, &mut sums).unwrap();
assert_eq!(sums, expected_sums, "level {} blocks {blocks}", d.isa());
let got = f64::from(d.dot_q8_0_q8_0(&wq, &aq).unwrap());
assert!(
(got - expected).abs() <= tol,
"level {} blocks {blocks}: got {got}, expected {expected}, tol {tol}",
d.isa()
);
}
}
}
#[test]
fn weights_may_use_the_full_int8_range_but_not_activations_minus_128() {
// A weight of -128 is fine; this is the documented contract in leleka_cpu.h.
let mut w = vec![0u8; Q8_0_BLOCK_BYTES];
w[..2].copy_from_slice(&0x3C00u16.to_le_bytes());
w[2..].fill((-128i8) as u8);
let mut a = vec![0u8; Q8_0_BLOCK_BYTES];
a[..2].copy_from_slice(&0x3C00u16.to_le_bytes());
a[2..].fill(127);
for d in levels() {
let mut sums = [0i32; 1];
d.q8_0_q8_0_block_sums(&w, &a, &mut sums).unwrap();
assert_eq!(sums[0], -128 * 127 * 32, "level {}", d.isa());
}
}
#[test]
fn bad_shapes_are_refused_at_every_level() {
for d in levels() {
assert_eq!(
d.dot_q8_0_q8_0(&[0; 34], &[0; 68]),
Err(KernelError::LengthMismatch)
);
assert_eq!(
d.dot_q8_0_q8_0(&[0; 33], &[0; 33]),
Err(KernelError::LengthMismatch)
);
assert_eq!(d.dot_q8_0_q8_0(&[], &[]), Ok(0.0));
let mut out = vec![0u8; 34];
assert_eq!(
d.quantize_q8_0(&[0.0; 31], &mut out),
Err(KernelError::LengthMismatch)
);
assert_eq!(
d.quantize_q8_0(&[0.0; 32], &mut [0u8; 33]),
Err(KernelError::LengthMismatch)
);
assert_eq!(d.quantize_q8_0(&[], &mut []), Ok(()));
}
}