State now records which tokens its KV cache holds. Model::prefill_reuse keeps the longest common prefix with a new prompt (always recomputing the last token, whose logits are needed) and prefills only the rest. A position that would leave a gap after the cached tokens is refused. Tests check that the result equals a fresh prefill bit for bit for identical, extended, diverging and unrelated prompts. The experimental AVX-VNNI tile kernels now use unsigned weights (w + 128, no sign instruction), start each block's accumulation from -128 * sum(x) in lane 0, and read pre-broadcast activation scales (PreparedAct / ActRef in cpu-sys). Tests bound the difference to the portable reference by (blocks + 16) * 2^-23 * sum of |terms| computed with absolute weights and activations. In bench_tiles this is not measurably faster than the sign-based tile (4x4 tile for 8 activations: 1.30x the one-row kernel at 10 threads, against 1.35x before; run-to-run noise on this laptop is about 10%), so the tiles stay unused by the decoder. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
230 lines
7.5 KiB
Rust
230 lines
7.5 KiB
Rust
//! The register-tiled kernels: every tile shape gives, for each (row, activation) pair, exactly the value
|
|
//! of the 1x1 tile at the same level, and all of them stay
|
|
//! within the float summation tolerance of the portable reference. (AVX2 and AVX-VNNI differ from each\n//! other only in float rounding: they group the integer products into lanes differently.)
|
|
|
|
use leleka_cpu_sys as sys;
|
|
use leleka_cpu_sys::simd;
|
|
|
|
struct Rng(u64);
|
|
|
|
impl Rng {
|
|
fn next(&mut self) -> u64 {
|
|
self.0 ^= self.0 << 13;
|
|
self.0 ^= self.0 >> 7;
|
|
self.0 ^= self.0 << 17;
|
|
self.0
|
|
}
|
|
}
|
|
|
|
struct Data {
|
|
mx_rows: Vec<Vec<u8>>,
|
|
q8_rows: Vec<Vec<u8>>,
|
|
acts: Vec<sys::PreparedAct>,
|
|
blocks: usize,
|
|
}
|
|
|
|
fn make(rng: &mut Rng, blocks: usize) -> Data {
|
|
let mx_rows = (0..4)
|
|
.map(|_| {
|
|
let mut v = Vec::new();
|
|
for _ in 0..blocks {
|
|
v.push(110 + (rng.next() % 30) as u8);
|
|
v.extend((0..16).map(|_| rng.next() as u8));
|
|
}
|
|
v
|
|
})
|
|
.collect();
|
|
let q8_rows = (0..4)
|
|
.map(|_| {
|
|
let mut v = Vec::new();
|
|
for _ in 0..blocks {
|
|
let scale = 0.001 + (rng.next() % 1000) as f32 * 1e-5;
|
|
v.extend_from_slice(&simd::f32_to_f16(scale).to_le_bytes());
|
|
v.extend((0..32).map(|_| rng.next() as u8)); // any int8 weight is allowed
|
|
}
|
|
v
|
|
})
|
|
.collect();
|
|
let acts = (0..4)
|
|
.map(|_| {
|
|
let scales = (0..blocks)
|
|
.map(|_| 0.0005 + (rng.next() % 1000) as f32 * 1e-5)
|
|
.collect();
|
|
let quants = (0..blocks * 32)
|
|
.map(|_| ((rng.next() % 255) as i64 - 127) as i8)
|
|
.collect();
|
|
sys::PreparedAct::new(scales, quants).unwrap()
|
|
})
|
|
.collect();
|
|
Data {
|
|
mx_rows,
|
|
q8_rows,
|
|
acts,
|
|
blocks,
|
|
}
|
|
}
|
|
|
|
/// MXFP4 row with every value made non-negative (clear the sign bit of each nibble).
|
|
fn abs_mx(row: &[u8]) -> Vec<u8> {
|
|
row.as_chunks::<17>()
|
|
.0
|
|
.iter()
|
|
.flat_map(|b| std::iter::once(b[0]).chain(b[1..].iter().map(|v| v & 0x77)))
|
|
.collect()
|
|
}
|
|
|
|
/// Q8_0 row with every quant made non-negative (saturating, so -128 becomes 127: still an upper bound
|
|
/// up to one unit, which the tolerance absorbs).
|
|
fn abs_q8(row: &[u8]) -> Vec<u8> {
|
|
row.as_chunks::<34>()
|
|
.0
|
|
.iter()
|
|
.flat_map(|b| {
|
|
b[..2]
|
|
.iter()
|
|
.copied()
|
|
.chain(b[2..].iter().map(|v| (*v as i8).saturating_abs() as u8))
|
|
})
|
|
.collect()
|
|
}
|
|
type TileFn = fn(&[&[u8]], &[sys::ActRef], &mut [f32]) -> Result<(), sys::KernelError>;
|
|
|
|
/// Run `kernel` for every shape and compare with the 1x1 tile and the portable reference.
|
|
fn check_level(
|
|
d: &Data,
|
|
rows: &[Vec<u8>],
|
|
abs_row: fn(&[u8]) -> Vec<u8>,
|
|
kernel: TileFn,
|
|
reference: TileFn,
|
|
label: &str,
|
|
) {
|
|
let abs_rows: Vec<Vec<u8>> = rows.iter().map(|r| abs_row(r)).collect();
|
|
let abs_prepared: Vec<sys::PreparedAct> = d
|
|
.acts
|
|
.iter()
|
|
.map(|a| {
|
|
let q = a.quants.iter().map(|v| v.saturating_abs()).collect();
|
|
sys::PreparedAct::new(a.scales.clone(), q).unwrap()
|
|
})
|
|
.collect();
|
|
let abs_acts: Vec<sys::ActRef> = abs_prepared.iter().map(|a| a.view()).collect();
|
|
for nr in 1..=sys::TILE_MAX {
|
|
for na in 1..=sys::TILE_MAX {
|
|
let abs_x: Vec<&[u8]> = abs_rows[..nr].iter().map(Vec::as_slice).collect();
|
|
let x: Vec<&[u8]> = rows[..nr].iter().map(Vec::as_slice).collect();
|
|
let acts: Vec<sys::ActRef> = d.acts[..na].iter().map(|a| a.view()).collect();
|
|
let mut tile = vec![0f32; nr * na];
|
|
kernel(&x, &acts, &mut tile).unwrap();
|
|
let mut portable = vec![0f32; nr * na];
|
|
reference(&x, &acts, &mut portable).unwrap();
|
|
for r in 0..nr {
|
|
for a in 0..na {
|
|
let mut one = [0f32; 1];
|
|
kernel(&x[r..=r], &acts[a..=a], &mut one).unwrap();
|
|
assert_eq!(
|
|
tile[r * na + a].to_bits(),
|
|
one[0].to_bits(),
|
|
"{label}: {nr}x{na} tile, pair ({r},{a}), {} blocks",
|
|
d.blocks
|
|
);
|
|
let (got, want) = (tile[r * na + a], portable[r * na + a]);
|
|
// float summation order: (blocks + 16) * 2^-23 * sum of |terms|, with the sum of
|
|
// |terms| bounded by the same dot over absolute weights and activations
|
|
let mut abs_dot = [0f32; 1];
|
|
reference(&abs_x[r..=r], &abs_acts[a..=a], &mut abs_dot).unwrap();
|
|
let bound = (d.blocks as f32 + 16.0) * 2f32.powi(-23) * abs_dot[0];
|
|
assert!(
|
|
(got - want).abs() <= bound,
|
|
"{label}: {nr}x{na}, ({r},{a}): {got} vs portable {want} (bound {bound})"
|
|
);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn bad_shapes_and_lengths_are_refused() {
|
|
let mut rng = Rng(5);
|
|
let d = make(&mut rng, 3);
|
|
let one: Vec<&[u8]> = vec![&d.mx_rows[0]];
|
|
let acts = vec![d.acts[0].view()];
|
|
let mut out = [0f32; 1];
|
|
assert_eq!(
|
|
sys::mxfp4_q8r_tile_scalar(&[], &acts, &mut out),
|
|
Err(sys::KernelError::TileShape)
|
|
);
|
|
assert_eq!(
|
|
sys::mxfp4_q8r_tile_scalar(&one, &[], &mut out),
|
|
Err(sys::KernelError::TileShape)
|
|
);
|
|
let five: Vec<&[u8]> = (0..5).map(|_| d.mx_rows[0].as_slice()).collect();
|
|
assert_eq!(
|
|
sys::mxfp4_q8r_tile_scalar(&five, &acts, &mut [0.0; 5]),
|
|
Err(sys::KernelError::TileShape)
|
|
);
|
|
assert_eq!(
|
|
sys::mxfp4_q8r_tile_scalar(&one, &acts, &mut [0.0; 2]),
|
|
Err(sys::KernelError::LengthMismatch)
|
|
);
|
|
let mut short = d.acts[0].view();
|
|
short.quants = &short.quants[..64];
|
|
assert_eq!(
|
|
sys::mxfp4_q8r_tile_scalar(&one, &[short], &mut out),
|
|
Err(sys::KernelError::LengthMismatch)
|
|
);
|
|
let mut no_corr = d.acts[0].view();
|
|
no_corr.corr = &no_corr.corr[..8];
|
|
assert_eq!(
|
|
sys::mxfp4_q8r_tile_scalar(&one, &[no_corr], &mut out),
|
|
Err(sys::KernelError::LengthMismatch)
|
|
);
|
|
assert!(sys::PreparedAct::new(vec![1.0], vec![0; 31]).is_err());
|
|
}
|
|
#[cfg(target_arch = "x86_64")]
|
|
#[test]
|
|
fn tiles_match_the_one_by_one_tile_and_the_portable_reference() {
|
|
if !sys::avx2_available() {
|
|
eprintln!("skipped: no AVX2");
|
|
return;
|
|
}
|
|
let mut rng = Rng(77);
|
|
for blocks in [1usize, 2, 3, 5, 8, 90] {
|
|
let d = make(&mut rng, blocks);
|
|
check_level(
|
|
&d,
|
|
&d.mx_rows,
|
|
abs_mx,
|
|
sys::mxfp4_q8r_tile_avx2,
|
|
sys::mxfp4_q8r_tile_scalar,
|
|
"mxfp4 avx2",
|
|
);
|
|
check_level(
|
|
&d,
|
|
&d.q8_rows,
|
|
abs_q8,
|
|
sys::q8_q8r_tile_avx2,
|
|
sys::q8_q8r_tile_scalar,
|
|
"q8 avx2",
|
|
);
|
|
if sys::avxvnni_available() {
|
|
check_level(
|
|
&d,
|
|
&d.mx_rows,
|
|
abs_mx,
|
|
sys::mxfp4_q8r_tile_avxvnni,
|
|
sys::mxfp4_q8r_tile_scalar,
|
|
"mxfp4 vnni",
|
|
);
|
|
check_level(
|
|
&d,
|
|
&d.q8_rows,
|
|
abs_q8,
|
|
sys::q8_q8r_tile_avxvnni,
|
|
sys::q8_q8r_tile_scalar,
|
|
"q8 vnni",
|
|
);
|
|
}
|
|
}
|
|
}
|