diff --git a/crates/cpu-kernels/examples/bench_tiles.rs b/crates/cpu-kernels/examples/bench_tiles.rs new file mode 100644 index 00000000..bce2ddc9 --- /dev/null +++ b/crates/cpu-kernels/examples/bench_tiles.rs @@ -0,0 +1,179 @@ +//! EXPERIMENT: paired comparison of the register-tiled MXFP4 kernels with the one-row kernel. +//! +//! Two regimes: ACTS=1 (decode: memory-bound, every weight byte used once) and ACTS=8 (prefill: each +//! weight row is used against 8 activations, so compute matters). Variants are interleaved inside every +//! repeat in a rotating order and compared as paired ratios against the first variant. Kernel +//! throughput only, never an inference result. +//! +//! Run: `cargo run --release -p leleka-cpu-kernels --example bench_tiles -- [MiB] [repeats] [acts]` + +use leleka_cpu_sys as sys; +use std::time::Instant; + +const BLOCKS_PER_ROW: usize = 90; +const MXFP4: usize = 17; + +struct Acts { + ys: Vec>, + yq: Vec>, +} + +/// Processes weight rows `lo..hi` against all activations; returns a checksum. +type Variant<'a> = Box f32 + Sync + 'a>; + +fn one_row_loop(vnni: bool) -> Variant<'static> { + Box::new(move |w, lo, hi, acts| { + let mut sum = 0f32; + for r in lo..hi { + let row = &w[r * BLOCKS_PER_ROW * MXFP4..(r + 1) * BLOCKS_PER_ROW * MXFP4]; + for a in 0..acts.ys.len() { + sum += if vnni { + sys::dot_mxfp4_q8r4_avxvnni(row, &acts.ys[a], &acts.yq[a]).unwrap() + } else { + sys::dot_mxfp4_q8r4_avx2(row, &acts.ys[a], &acts.yq[a]).unwrap() + }; + } + } + sum + }) +} + +fn tiled(vnni: bool, tr: usize, ta: usize) -> Variant<'static> { + Box::new(move |w, lo, hi, acts| { + let mut sum = 0f32; + let na = acts.ys.len(); + let rb = BLOCKS_PER_ROW * MXFP4; + let mut out = vec![0f32; tr * ta]; + let mut r = lo; + while r < hi { + let nr = tr.min(hi - r); + let rows: Vec<&[u8]> = (0..nr) + .map(|i| &w[(r + i) * rb..(r + i + 1) * rb]) + .collect(); + let mut a = 0; + while a < na { + let nta = ta.min(na - a); + let ys: Vec<&[f32]> = (a..a + nta).map(|i| acts.ys[i].as_slice()).collect(); + let yq: Vec<&[i8]> = (a..a + nta).map(|i| acts.yq[i].as_slice()).collect(); + let o = &mut out[..nr * nta]; + if vnni { + sys::mxfp4_q8r_tile_avxvnni(&rows, &ys, &yq, o).unwrap(); + } else { + sys::mxfp4_q8r_tile_avx2(&rows, &ys, &yq, o).unwrap(); + } + sum += o.iter().sum::(); + a += nta; + } + r += nr; + } + sum + }) +} + +fn main() { + let args: Vec = std::env::args().collect(); + let mib: usize = args.get(1).and_then(|s| s.parse().ok()).unwrap_or(768); + let repeats: usize = args.get(2).and_then(|s| s.parse().ok()).unwrap_or(9); + let n_acts: usize = args.get(3).and_then(|s| s.parse().ok()).unwrap_or(1); + let row_bytes = BLOCKS_PER_ROW * MXFP4; + let rows = (mib << 20) / row_bytes; + + let mut state = 0x1234_5678_9ABC_DEF0u64; + let mut next = move || { + state = state + .wrapping_mul(6364136223846793005) + .wrapping_add(1442695040888963407); + (state >> 33) as u32 + }; + let mut weights = vec![0u8; rows * row_bytes]; + for block in weights.as_chunks_mut::().0.iter_mut() { + block[0] = 112 + (next() % 16) as u8; + for b in &mut block[1..] { + *b = next() as u8; + } + } + let acts = Acts { + ys: (0..n_acts) + .map(|_| vec![0.0625f32; BLOCKS_PER_ROW]) + .collect(), + yq: (0..n_acts) + .map(|_| { + (0..BLOCKS_PER_ROW * 32) + .map(|_| ((next() % 255) as i64 - 127) as i8) + .collect() + }) + .collect(), + }; + + let vnni = sys::avxvnni_available(); + let mut variants: Vec<(String, Variant)> = vec![( + format!( + "one-row q8r4, {} loop over acts", + if vnni { "vnni" } else { "avx2" } + ), + one_row_loop(vnni), + )]; + for (tr, ta) in [ + (1, 1), + (2, 1), + (4, 1), + (1, 4), + (2, 2), + (2, 4), + (4, 2), + (4, 4), + ] { + if ta > n_acts && ta > 1 { + continue; + } + variants.push((format!("tile {tr}x{ta}"), tiled(vnni, tr, ta))); + } + + println!( + "buffer {} MiB = {rows} rows, {n_acts} activation(s); {repeats} interleaved repeats; ratios are paired against the first variant", + weights.len() >> 20 + ); + for threads in [1usize, 10] { + let mut samples: Vec> = vec![Vec::new(); variants.len()]; + for rep in 0..repeats { + for k in 0..variants.len() { + let idx = (k + rep) % variants.len(); + let kernel = &variants[idx].1; + let start = Instant::now(); + std::thread::scope(|s| { + let per = rows.div_ceil(threads); + for t in 0..threads { + let (w, a) = (&weights, &acts); + s.spawn(move || { + let (lo, hi) = (t * per, ((t + 1) * per).min(rows)); + std::hint::black_box(kernel(w, lo, hi, a)); + }); + } + }); + // weight GB/s read, and block-dot rate (rows x activations x blocks) + samples[idx].push(weights.len() as f64 / start.elapsed().as_secs_f64() / 1e9); + } + } + println!( + "-- {threads} thread(s); weight GB/s (each byte used against {n_acts} activation(s))" + ); + for (i, (name, _)) in variants.iter().enumerate() { + let mut s = samples[i].clone(); + s.sort_by(|a, b| a.total_cmp(b)); + let mut ratios: Vec = samples[i] + .iter() + .zip(&samples[0]) + .map(|(a, b)| a / b) + .collect(); + ratios.sort_by(|a, b| a.total_cmp(b)); + println!( + "{:<36} {:>7.1} GB/s ratio {:>6.3} [{:.3} .. {:.3}]", + name, + s[s.len() / 2], + ratios[ratios.len() / 2], + ratios[0], + ratios[ratios.len() - 1] + ); + } + } +} diff --git a/crates/cpu-sys/src/lib.rs b/crates/cpu-sys/src/lib.rs index 2dc9b497..becb3b90 100644 --- a/crates/cpu-sys/src/lib.rs +++ b/crates/cpu-sys/src/lib.rs @@ -42,6 +42,8 @@ pub enum KernelError { 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, } impl fmt::Display for KernelError { @@ -50,6 +52,7 @@ impl fmt::Display for KernelError { 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", }) } } @@ -352,6 +355,110 @@ pub fn q8_0_q8_0_isums_avxvnni(x: &[u8], y: &[u8], out: &mut [i32]) -> Result<() with_avxvnni!(simd::x86::q8_0_q8_0_isums_avxvnni(x, y, out)) } +// ------------------------------------------------------------------------------- tiles ----------- + +/// Largest number of rows or activations in one tile. +pub const TILE_MAX: usize = 4; + +/// Checks a tile: `x.len()` rows of `block_bytes`-byte blocks against `ys.len()` activations in the +/// "q8r" layout, and an output of `rows * activations` values. +fn check_tile( + x: &[&[u8]], + ys: &[&[f32]], + yq: &[&[i8]], + out: &[f32], + block_bytes: usize, +) -> Result<(), KernelError> { + let (rows, acts) = (x.len(), ys.len()); + if rows == 0 || rows > TILE_MAX || acts == 0 || acts > TILE_MAX || yq.len() != acts { + return Err(KernelError::TileShape); + } + let blocks = x[0].len() / block_bytes; + let ok = x.iter().all(|r| r.len() == blocks * block_bytes) + && ys.iter().all(|s| s.len() == blocks) + && yq.iter().all(|q| q.len() == blocks * BLOCK_ELEMS) + && out.len() == rows * acts; + if ok { + Ok(()) + } else { + Err(KernelError::LengthMismatch) + } +} + +/// A tile of MXFP4 weight rows against "q8r" activations, portable reference. `out[r * A + a]` is the +/// dot of row `r` with activation `a`; each value equals the 1x1 tile (and the SIMD levels) up to float +/// summation order. +pub fn mxfp4_q8r_tile_scalar( + x: &[&[u8]], + ys: &[&[f32]], + yq: &[&[i8]], + out: &mut [f32], +) -> Result<(), KernelError> { + check_tile(x, ys, yq, out, MXFP4_BLOCK_BYTES)?; + simd::mxfp4_q8r_tile_scalar(x, ys, yq, out); + Ok(()) +} + +/// A tile of Q8_0 weight rows against "q8r" activations, portable reference. +pub fn q8_q8r_tile_scalar( + x: &[&[u8]], + ys: &[&[f32]], + yq: &[&[i8]], + out: &mut [f32], +) -> Result<(), KernelError> { + check_tile(x, ys, yq, out, Q8_0_BLOCK_BYTES)?; + simd::q8_q8r_tile_scalar(x, ys, yq, 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]], + ys: &[&[f32]], + yq: &[&[i8]], + out: &mut [f32], +) -> Result<(), KernelError> { + check_tile(x, ys, yq, out, MXFP4_BLOCK_BYTES)?; + with_avx2!(simd::x86::mxfp4_q8r_tile_avx2(x, ys, yq, out)) +} + +/// AVX-VNNI level of [`mxfp4_q8r_tile_scalar`]; bit-identical to the AVX2 level. +#[cfg(target_arch = "x86_64")] +pub fn mxfp4_q8r_tile_avxvnni( + x: &[&[u8]], + ys: &[&[f32]], + yq: &[&[i8]], + out: &mut [f32], +) -> Result<(), KernelError> { + check_tile(x, ys, yq, out, MXFP4_BLOCK_BYTES)?; + with_avxvnni!(simd::x86::mxfp4_q8r_tile_avxvnni(x, ys, yq, out)) +} + +/// AVX2 level of [`q8_q8r_tile_scalar`]. +#[cfg(target_arch = "x86_64")] +pub fn q8_q8r_tile_avx2( + x: &[&[u8]], + ys: &[&[f32]], + yq: &[&[i8]], + out: &mut [f32], +) -> Result<(), KernelError> { + check_tile(x, ys, yq, out, Q8_0_BLOCK_BYTES)?; + with_avx2!(simd::x86::q8_q8r_tile_avx2(x, ys, yq, out)) +} + +/// AVX-VNNI level of [`q8_q8r_tile_scalar`]; bit-identical to the AVX2 level. +#[cfg(target_arch = "x86_64")] +pub fn q8_q8r_tile_avxvnni( + x: &[&[u8]], + ys: &[&[f32]], + yq: &[&[i8]], + out: &mut [f32], +) -> Result<(), KernelError> { + check_tile(x, ys, yq, out, Q8_0_BLOCK_BYTES)?; + with_avxvnni!(simd::x86::q8_q8r_tile_avxvnni(x, ys, yq, 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")] diff --git a/crates/cpu-sys/src/simd.rs b/crates/cpu-sys/src/simd.rs index b0e32ce8..d6a7e666 100644 --- a/crates/cpu-sys/src/simd.rs +++ b/crates/cpu-sys/src/simd.rs @@ -1,4 +1,4 @@ -//! Rust implementations of the CPU kernels, written with `std::arch` intrinsics. +//! Rust implementations of the CPU kernels, written with `std::arch` intrinsics. //! //! They mirror the C kernels in `csrc/` operation for operation (same accumulation structure, same //! horizontal sums, same rounding), so results are bit-identical to them; a differential test checks @@ -143,6 +143,38 @@ pub fn dot_mxfp4_q8r_scalar(x: &[u8], ys: &[f32], yq: &[i8]) -> f32 { sum } +/// Q8_0 weights times an activation in the "q8r" layout. +pub fn dot_q8_q8r_scalar(x: &[u8], ys: &[f32], yq: &[i8]) -> f32 { + let mut sum = 0.0f32; + for (ib, xb) in x.chunks_exact(Q8_0_BYTES).enumerate() { + let isum: i32 = xb[2..] + .iter() + .zip(&yq[ib * 32..ib * 32 + 32]) + .map(|(w, a)| i32::from(*w as i8) * i32::from(*a)) + .sum(); + sum += (f16_to_f32(load_u16(xb)) * ys[ib]) * isum as f32; + } + sum +} + +/// A tile of MXFP4 rows by "q8r" activations, portable: `out[r * ys.len() + a]`. +pub fn mxfp4_q8r_tile_scalar(x: &[&[u8]], ys: &[&[f32]], yq: &[&[i8]], out: &mut [f32]) { + for (r, row) in x.iter().enumerate() { + for a in 0..ys.len() { + out[r * ys.len() + a] = dot_mxfp4_q8r_scalar(row, ys[a], yq[a]); + } + } +} + +/// A tile of Q8_0 rows by "q8r" activations, portable: `out[r * ys.len() + a]`. +pub fn q8_q8r_tile_scalar(x: &[&[u8]], ys: &[&[f32]], yq: &[&[i8]], out: &mut [f32]) { + for (r, row) in x.iter().enumerate() { + for a in 0..ys.len() { + out[r * ys.len() + a] = dot_q8_q8r_scalar(row, ys[a], yq[a]); + } + } +} + /// Quantize floats (a multiple of 32) to Q8_0 blocks: scale = amax / 127 stored as a half, quants /// rounded to nearest even and clamped to `[-127, 127]`. pub fn quantize_q8_0_scalar(x: &[f32], out: &mut [u8]) { @@ -756,6 +788,216 @@ pub mod x86 { } } + // ---- register-tiled kernels: R weight rows against A activations in one pass ---- + // + // Each weight block is decoded once and used against all A activations; each activation block is + // loaded once and used against all R rows. Every output has ONE accumulator that sums blocks in + // order (8 float lanes, reduced at the end), so a tile of any shape gives bit-for-bit the same + // value for a (row, activation) pair as the 1x1 tile. + + /// MXFP4 rows against "q8r" activations. `x[r]` holds `nb` 17-byte blocks, `ys[a]` `nb` scales and + /// `yq[a]` `nb * 32` quants; `out[r * A + a]` receives the dot of row `r` with activation `a`. + #[inline] + #[target_feature(enable = "avx2,fma")] + unsafe fn mxfp4_tile_avx2( + x: [&[u8]; R], + ys: [&[f32]; A], + yq: [&[i8]; A], + out: &mut [f32], + ) { + let nb = x[0].len() / MXFP4_BYTES; + let (table, low, ones) = (mx_table(), _mm_set1_epi8(0x0F), _mm256_set1_epi16(1)); + let mut acc = [[_mm256_setzero_ps(); A]; R]; + for ib in 0..nb { + for r in 0..R { + let xb = x[r].as_ptr().add(ib * MXFP4_BYTES); + let w = mx_values(xb, table, low); + let wabs = _mm256_sign_epi8(w, w); + let e = e8m0_half(*xb); + for a in 0..A { + let xv = _mm256_loadu_si256(yq[a].as_ptr().add(ib * 32) as *const __m256i); + let p16 = _mm256_maddubs_epi16(wabs, _mm256_sign_epi8(xv, w)); + let p = _mm256_madd_epi16(p16, ones); + let s = *ys[a].get_unchecked(ib) * e; + acc[r][a] = + _mm256_fmadd_ps(_mm256_cvtepi32_ps(p), _mm256_set1_ps(s), acc[r][a]); + } + } + } + for r in 0..R { + for a in 0..A { + out[r * A + a] = hsum_ps(acc[r][a]); + } + } + } + + /// As [`mxfp4_tile_avx2`] with AVX-VNNI for the int8 products. + #[inline] + #[target_feature(enable = "avx2,fma,avxvnni")] + unsafe fn mxfp4_tile_avxvnni( + x: [&[u8]; R], + ys: [&[f32]; A], + yq: [&[i8]; A], + out: &mut [f32], + ) { + let nb = x[0].len() / MXFP4_BYTES; + let (table, low) = (mx_table(), _mm_set1_epi8(0x0F)); + let zero = _mm256_setzero_si256(); + let mut acc = [[_mm256_setzero_ps(); A]; R]; + for ib in 0..nb { + for r in 0..R { + let xb = x[r].as_ptr().add(ib * MXFP4_BYTES); + let w = mx_values(xb, table, low); + let wabs = _mm256_sign_epi8(w, w); + let e = e8m0_half(*xb); + for a in 0..A { + let xv = _mm256_loadu_si256(yq[a].as_ptr().add(ib * 32) as *const __m256i); + let p = _mm256_dpbusd_avx_epi32(zero, wabs, _mm256_sign_epi8(xv, w)); + let s = *ys[a].get_unchecked(ib) * e; + acc[r][a] = + _mm256_fmadd_ps(_mm256_cvtepi32_ps(p), _mm256_set1_ps(s), acc[r][a]); + } + } + } + for r in 0..R { + for a in 0..A { + out[r * A + a] = hsum_ps(acc[r][a]); + } + } + } + + /// Q8_0 rows (34-byte blocks with a half scale) against "q8r" activations; same tile contract. + #[inline] + #[target_feature(enable = "avx2,fma,f16c")] + unsafe fn q8_tile_avx2( + x: [&[u8]; R], + ys: [&[f32]; A], + yq: [&[i8]; A], + out: &mut [f32], + ) { + let nb = x[0].len() / Q8_0_BYTES; + let ones = _mm256_set1_epi16(1); + let mut acc = [[_mm256_setzero_ps(); A]; R]; + for ib in 0..nb { + for r in 0..R { + let xb = x[r].as_ptr().add(ib * Q8_0_BYTES); + let w = _mm256_loadu_si256(xb.add(2) as *const __m256i); + let wabs = _mm256_sign_epi8(w, w); + let d = half_to_f32(xb); + for a in 0..A { + let xv = _mm256_loadu_si256(yq[a].as_ptr().add(ib * 32) as *const __m256i); + let p16 = _mm256_maddubs_epi16(wabs, _mm256_sign_epi8(xv, w)); + let p = _mm256_madd_epi16(p16, ones); + let s = *ys[a].get_unchecked(ib) * d; + acc[r][a] = + _mm256_fmadd_ps(_mm256_cvtepi32_ps(p), _mm256_set1_ps(s), acc[r][a]); + } + } + } + for r in 0..R { + for a in 0..A { + out[r * A + a] = hsum_ps(acc[r][a]); + } + } + } + + /// As [`q8_tile_avx2`] with AVX-VNNI for the int8 products. + #[inline] + #[target_feature(enable = "avx2,fma,f16c,avxvnni")] + unsafe fn q8_tile_avxvnni( + x: [&[u8]; R], + ys: [&[f32]; A], + yq: [&[i8]; A], + out: &mut [f32], + ) { + let nb = x[0].len() / Q8_0_BYTES; + let zero = _mm256_setzero_si256(); + let mut acc = [[_mm256_setzero_ps(); A]; R]; + for ib in 0..nb { + for r in 0..R { + let xb = x[r].as_ptr().add(ib * Q8_0_BYTES); + let w = _mm256_loadu_si256(xb.add(2) as *const __m256i); + let wabs = _mm256_sign_epi8(w, w); + let d = half_to_f32(xb); + for a in 0..A { + let xv = _mm256_loadu_si256(yq[a].as_ptr().add(ib * 32) as *const __m256i); + let p = _mm256_dpbusd_avx_epi32(zero, wabs, _mm256_sign_epi8(xv, w)); + let s = *ys[a].get_unchecked(ib) * d; + acc[r][a] = + _mm256_fmadd_ps(_mm256_cvtepi32_ps(p), _mm256_set1_ps(s), acc[r][a]); + } + } + } + for r in 0..R { + for a in 0..A { + out[r * A + a] = hsum_ps(acc[r][a]); + } + } + } + + /// Expands to a `match` over the tile shapes `1..=4` rows by `1..=4` activations. + macro_rules! tile_shapes { + ($generic:ident, $x:ident, $ys:ident, $yq:ident, $out:ident) => { + match ($x.len(), $ys.len()) { + (1, 1) => $generic::<1, 1>(conv($x), conv($ys), conv($yq), $out), + (1, 2) => $generic::<1, 2>(conv($x), conv($ys), conv($yq), $out), + (1, 3) => $generic::<1, 3>(conv($x), conv($ys), conv($yq), $out), + (1, 4) => $generic::<1, 4>(conv($x), conv($ys), conv($yq), $out), + (2, 1) => $generic::<2, 1>(conv($x), conv($ys), conv($yq), $out), + (2, 2) => $generic::<2, 2>(conv($x), conv($ys), conv($yq), $out), + (2, 3) => $generic::<2, 3>(conv($x), conv($ys), conv($yq), $out), + (2, 4) => $generic::<2, 4>(conv($x), conv($ys), conv($yq), $out), + (3, 1) => $generic::<3, 1>(conv($x), conv($ys), conv($yq), $out), + (3, 2) => $generic::<3, 2>(conv($x), conv($ys), conv($yq), $out), + (3, 3) => $generic::<3, 3>(conv($x), conv($ys), conv($yq), $out), + (3, 4) => $generic::<3, 4>(conv($x), conv($ys), conv($yq), $out), + (4, 1) => $generic::<4, 1>(conv($x), conv($ys), conv($yq), $out), + (4, 2) => $generic::<4, 2>(conv($x), conv($ys), conv($yq), $out), + (4, 3) => $generic::<4, 3>(conv($x), conv($ys), conv($yq), $out), + (4, 4) => $generic::<4, 4>(conv($x), conv($ys), conv($yq), $out), + _ => unreachable!("tile shape is checked by the safe wrapper"), + } + }; + } + + /// Slice of exactly `N` elements to an array (the shape was checked by the caller). + #[inline(always)] + fn conv(s: &[T]) -> [T; N] { + s.try_into().expect("tile shape") + } + + /// Largest number of rows or activations in one tile. + pub const TILE_MAX: usize = 4; + + /// MXFP4 tile of `x.len()` rows by `ys.len()` activations (each in `1..=TILE_MAX`). + #[target_feature(enable = "avx2,fma")] + pub unsafe fn mxfp4_q8r_tile_avx2(x: &[&[u8]], ys: &[&[f32]], yq: &[&[i8]], out: &mut [f32]) { + tile_shapes!(mxfp4_tile_avx2, x, ys, yq, out) + } + + /// As [`mxfp4_q8r_tile_avx2`] with AVX-VNNI. + #[target_feature(enable = "avx2,fma,avxvnni")] + pub unsafe fn mxfp4_q8r_tile_avxvnni( + x: &[&[u8]], + ys: &[&[f32]], + yq: &[&[i8]], + out: &mut [f32], + ) { + tile_shapes!(mxfp4_tile_avxvnni, x, ys, yq, out) + } + + /// Q8_0 tile of `x.len()` rows by `ys.len()` activations (each in `1..=TILE_MAX`). + #[target_feature(enable = "avx2,fma,f16c")] + pub unsafe fn q8_q8r_tile_avx2(x: &[&[u8]], ys: &[&[f32]], yq: &[&[i8]], out: &mut [f32]) { + tile_shapes!(q8_tile_avx2, x, ys, yq, out) + } + + /// As [`q8_q8r_tile_avx2`] with AVX-VNNI. + #[target_feature(enable = "avx2,fma,f16c,avxvnni")] + pub unsafe fn q8_q8r_tile_avxvnni(x: &[&[u8]], ys: &[&[f32]], yq: &[&[i8]], out: &mut [f32]) { + tile_shapes!(q8_tile_avxvnni, x, ys, yq, out) + } + /// Float to half with the F16C instruction (to test the portable conversion against). #[target_feature(enable = "f16c")] pub unsafe fn f32_to_f16_f16c(f: f32) -> u16 { diff --git a/crates/cpu-sys/tests/tiles.rs b/crates/cpu-sys/tests/tiles.rs new file mode 100644 index 00000000..e6d40560 --- /dev/null +++ b/crates/cpu-sys/tests/tiles.rs @@ -0,0 +1,193 @@ +//! The register-tiled kernels: every tile shape gives, for each (row, activation) pair, exactly the value +//! of the 1x1 tile at the same level, the AVX2 and AVX-VNNI levels agree bit for bit, and all of them stay +//! within the float summation tolerance of the portable reference. + +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>, + q8_rows: Vec>, + ys: Vec>, + yq: Vec>, + 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 ys = (0..4) + .map(|_| { + (0..blocks) + .map(|_| 0.0005 + (rng.next() % 1000) as f32 * 1e-5) + .collect() + }) + .collect(); + let yq = (0..4) + .map(|_| { + (0..blocks * 32) + .map(|_| ((rng.next() % 255) as i64 - 127) as i8) + .collect() + }) + .collect(); + Data { + mx_rows, + q8_rows, + ys, + yq, + blocks, + } +} + +type TileFn = fn(&[&[u8]], &[&[f32]], &[&[i8]], &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], kernel: TileFn, reference: TileFn, label: &str) { + for nr in 1..=sys::TILE_MAX { + for na in 1..=sys::TILE_MAX { + let x: Vec<&[u8]> = rows[..nr].iter().map(Vec::as_slice).collect(); + let ys: Vec<&[f32]> = d.ys[..na].iter().map(Vec::as_slice).collect(); + let yq: Vec<&[i8]> = d.yq[..na].iter().map(Vec::as_slice).collect(); + let mut tile = vec![0f32; nr * na]; + kernel(&x, &ys, &yq, &mut tile).unwrap(); + let mut portable = vec![0f32; nr * na]; + reference(&x, &ys, &yq, &mut portable).unwrap(); + for r in 0..nr { + for a in 0..na { + let mut one = [0f32; 1]; + kernel(&x[r..=r], &ys[a..=a], &yq[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]); + // each block term is below 2^-3 * 127 * 127 * 32 * the scale product; use the + // portable value's own magnitude plus a generous bound on the largest term + let bound = (d.blocks as f32 + 16.0) * 2f32.powi(-23) * 4000.0; + assert!( + (got - want).abs() <= bound.max(want.abs() * 1e-5), + "{label}: {nr}x{na}, ({r},{a}): {got} vs portable {want}" + ); + } + } + } + } +} + +#[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 ys: Vec<&[f32]> = vec![&d.ys[0]]; + let yq: Vec<&[i8]> = vec![&d.yq[0]]; + let mut out = [0f32; 1]; + assert_eq!( + sys::mxfp4_q8r_tile_scalar(&[], &ys, &yq, &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, &ys, &yq, &mut [0.0; 5]), + Err(sys::KernelError::TileShape) + ); + assert_eq!( + sys::mxfp4_q8r_tile_scalar(&one, &ys, &yq, &mut [0.0; 2]), + Err(sys::KernelError::LengthMismatch) + ); + let short: Vec<&[i8]> = vec![&d.yq[0][..64]]; + assert_eq!( + sys::mxfp4_q8r_tile_scalar(&one, &ys, &short, &mut out), + Err(sys::KernelError::LengthMismatch) + ); +} + +#[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, + sys::mxfp4_q8r_tile_avx2, + sys::mxfp4_q8r_tile_scalar, + "mxfp4 avx2", + ); + check_level( + &d, + &d.q8_rows, + sys::q8_q8r_tile_avx2, + sys::q8_q8r_tile_scalar, + "q8 avx2", + ); + if sys::avxvnni_available() { + check_level( + &d, + &d.mx_rows, + sys::mxfp4_q8r_tile_avxvnni, + sys::mxfp4_q8r_tile_scalar, + "mxfp4 vnni", + ); + check_level( + &d, + &d.q8_rows, + sys::q8_q8r_tile_avxvnni, + sys::q8_q8r_tile_scalar, + "q8 vnni", + ); + // the two levels agree bit for bit + let x: Vec<&[u8]> = d.mx_rows.iter().map(Vec::as_slice).collect(); + let ys: Vec<&[f32]> = d.ys.iter().map(Vec::as_slice).collect(); + let yq: Vec<&[i8]> = d.yq.iter().map(Vec::as_slice).collect(); + let (mut a, mut b) = (vec![0f32; 16], vec![0f32; 16]); + sys::mxfp4_q8r_tile_avx2(&x, &ys, &yq, &mut a).unwrap(); + sys::mxfp4_q8r_tile_avxvnni(&x, &ys, &yq, &mut b).unwrap(); + assert_eq!( + a.iter().map(|v| v.to_bits()).collect::>(), + b.iter().map(|v| v.to_bits()).collect::>() + ); + } + } +} diff --git a/crates/gptoss/examples/run_real.rs b/crates/gptoss/examples/run_real.rs index d9fcc6ff..abd3c0d3 100644 --- a/crates/gptoss/examples/run_real.rs +++ b/crates/gptoss/examples/run_real.rs @@ -21,10 +21,23 @@ fn main() { std::process::exit(2); } let path = Path::new(&args[0]); - let prompt: Vec = args[1] - .split(',') - .map(|s| s.trim().parse().expect("token ids are integers")) - .collect(); + // `synth:N` makes a deterministic pseudo-random prompt of N ids (to time long prefills). + let prompt: Vec = if let Some(n) = args[1].strip_prefix("synth:") { + let mut s = 0x2545_F491_4F6C_DD1Du64; + (0..n.parse::().expect("synth:N")) + .map(|_| { + s ^= s << 13; + s ^= s >> 7; + s ^= s << 17; + 1000 + (s % 60_000) as u32 + }) + .collect() + } else { + args[1] + .split(',') + .map(|s| s.trim().parse().expect("token ids are integers")) + .collect() + }; let new_tokens: usize = args.get(2).and_then(|s| s.parse().ok()).unwrap_or(16); let threads: usize = args .get(3) @@ -48,8 +61,14 @@ fn main() { } let dispatch = Dispatch::from_env().expect("kernel level"); let t0 = Instant::now(); - let model = + let mut model = Model::load(std::sync::Arc::new(map), &gguf, dispatch, threads).expect("load model"); + if let Some(chunk) = std::env::var("LELEKA_PREFILL_CHUNK") + .ok() + .and_then(|s| s.parse().ok()) + { + model.set_prefill_chunk(chunk); + } eprintln!( "loaded in {:.2} s; kernels {}; {threads} threads; context capacity {}", t0.elapsed().as_secs_f64(), @@ -58,17 +77,19 @@ fn main() { ); let mut state = State::new(&model.config, prompt.len() + new_tokens + 1); - let mut next = 0u32; let t_prefill = Instant::now(); - for (pos, token) in prompt.iter().enumerate() { - let t = Instant::now(); - next = model.forward(&mut state, *token, pos).expect("forward"); + let mut next = model + .prefill(&mut state, &prompt, 0) + .expect("prefill") + .expect("a non-empty prompt"); + let prefill_ms = t_prefill.elapsed().as_secs_f64() * 1000.0; + if prompt.len() > 1 { eprintln!( - "prompt position {pos}: {:.0} ms", - t.elapsed().as_secs_f64() * 1000.0 + "prefill chunk {}: {}", + model.prefill_chunk(), + state.profile.report() ); } - let prefill_ms = t_prefill.elapsed().as_secs_f64() * 1000.0; state.profile = Default::default(); // profile the decode steps only // Top-5 log-probabilities of the first generated position (from the last prompt token). diff --git a/crates/gptoss/src/lib.rs b/crates/gptoss/src/lib.rs index 54f8f965..3ad76474 100644 --- a/crates/gptoss/src/lib.rs +++ b/crates/gptoss/src/lib.rs @@ -1,4 +1,4 @@ -//! gpt-oss decoder on the Leleka CPU kernels. One token at a time, f32 KV cache. +//! gpt-oss decoder on the Leleka CPU kernels. Decode runs one token at a time and prefill runs chunks of\n//! tokens through the same code, so every weight row is read once per chunk. f32 KV cache. //! //! Weights stay in the (memory-mapped) model file as ggml blocks and are read in place; only the small //! F32 tensors (norms, biases, router, sinks) are copied. Layer structure and constants follow @@ -18,7 +18,7 @@ use leleka_cpu_kernels::Dispatch; use leleka_gguf::{Gguf, TensorInfo, TensorType}; use pool::{ChunkCounter, Pool}; use std::fmt; -use std::sync::Arc; +use std::sync::{Arc, RwLock}; const BLOCK: usize = 32; const Q8_0_BYTES: usize = 34; @@ -28,6 +28,8 @@ const SWIGLU_ALPHA: f32 = 1.702; const SWIGLU_LIMIT: f32 = 7.0; /// Smallest chunk of rows a participant claims at once. const MIN_CHUNK_ROWS: usize = 16; +/// Tokens per prefill chunk unless changed with [Model::set_prefill_chunk]. +const DEFAULT_PREFILL_CHUNK: usize = 64; /// The bytes of a model file: a memory mapping, or a buffer in tests. pub trait ModelBytes: Send + Sync + 'static { @@ -212,7 +214,7 @@ struct Layer { bk: Arc>, bv: Arc>, bo: Arc>, - sinks: Vec, + sinks: Arc>, post_norm: Vec, router_w: Vec, router_b: Vec, @@ -233,6 +235,7 @@ pub struct Model { layers: Vec, dispatch: Dispatch, pool: Pool, + prefill_chunk: usize, } fn bytes_of( @@ -341,7 +344,12 @@ impl Model { bk: Arc::new(f32_tensor(f, g, &n("attn_k.bias"), &[kw as u64])?), bv: Arc::new(f32_tensor(f, g, &n("attn_v.bias"), &[kw as u64])?), bo: Arc::new(f32_tensor(f, g, &n("attn_output.bias"), &[e as u64])?), - sinks: f32_tensor(f, g, &n("attn_sinks.weight"), &[c.n_head as u64])?, + sinks: Arc::new(f32_tensor( + f, + g, + &n("attn_sinks.weight"), + &[c.n_head as u64], + )?), post_norm: f32_tensor(f, g, &n("post_attention_norm.weight"), &[e as u64])?, router_w: f32_tensor(f, g, &n("ffn_gate_inp.weight"), &[e as u64, ne as u64])?, router_b: f32_tensor(f, g, &n("ffn_gate_inp.bias"), &[ne as u64])?, @@ -390,6 +398,7 @@ impl Model { config: c, dispatch, pool: Pool::new(threads), + prefill_chunk: DEFAULT_PREFILL_CHUNK, }) } @@ -446,11 +455,12 @@ impl Profile { } } -/// Mutable per-sequence state: KV cache and scratch buffers. +/// Mutable per-sequence state: KV cache and scratch buffers. The cache of each layer sits behind a +/// read-write lock so the attention region can read it from pool threads; writes happen between regions. pub struct State { capacity: usize, - k: Vec>, - v: Vec>, + k: Vec>>>, + v: Vec>>>, /// Logits of the last forward pass. pub logits: Vec, /// Phase timings accumulated over all tokens run with this state. @@ -460,10 +470,15 @@ pub struct State { impl State { pub fn new(config: &Config, capacity: usize) -> Self { let per_layer = capacity * config.kv_width(); + let cache = || -> Vec<_> { + (0..config.blocks) + .map(|_| Arc::new(RwLock::new(vec![0.0; per_layer]))) + .collect() + }; Self { capacity, - k: vec![vec![0.0; per_layer]; config.blocks], - v: vec![vec![0.0; per_layer]; config.blocks], + k: cache(), + v: cache(), logits: vec![0.0; config.vocab], profile: Profile::default(), } @@ -514,13 +529,14 @@ struct Act { quants: Vec, } -/// One matrix-vector product inside a region: `rows` rows starting at `first_row` of `matrix`, -/// against the quantized activation `act`, plus an optional bias slice. +/// One product inside a region: `rows` rows starting at `first_row` of `matrix`, each against every +/// quantized activation in `acts` (one for a decoded token, one per token for a prefill chunk), plus an +/// optional bias slice. The output is laid out `[row][activation]`. struct MatvecJob { matrix: QMatrix, first_row: usize, rows: usize, - act: Arc, + acts: Vec>, bias: Option, } @@ -533,9 +549,21 @@ struct Chunk { type ChunkResults = Result)>, ModelError>; +/// Greedy choice: the first index holding the largest value. +fn argmax(values: &[f32]) -> usize { + let mut best = 0usize; + for (i, l) in values.iter().enumerate() { + if *l > values[best] { + best = i; + } + } + best +} + impl Model { /// Run a group of products as ONE parallel region. Participants claim row chunks from a shared /// counter, so the region ends when the slowest chunk ends rather than the slowest thread's share. + /// Each weight row is read once and used against every activation of its job. fn run_region(&self, jobs: Vec) -> Result>, ModelError> { let total: usize = jobs.iter().map(|j| j.rows).sum(); let target_chunks = (self.pool.participants() * 6).max(1); @@ -565,32 +593,37 @@ impl Model { let job = &jobs_in[chunk.job]; let data = job.matrix.data(); let row_bytes = job.matrix.row_bytes(); - let mut out = Vec::with_capacity(chunk.rows); + let mut out = Vec::with_capacity(chunk.rows * job.acts.len()); for r in 0..chunk.rows { let row_index = job.first_row + chunk.start + r; let row = &data[row_index * row_bytes..(row_index + 1) * row_bytes]; - let dot = match job.matrix.kind { - Kind::Q8_0 => dispatch.dot_q8_0_q8_0(row, &job.act.blocks), - Kind::Mxfp4 => { - dispatch.dot_mxfp4_q8r(row, &job.act.scales, &job.act.quants) - } - } - .map_err(|e| ModelError::Invalid(format!("kernel: {e}")))?; let bias = job .bias .as_ref() .map_or(0.0, |b| b.data[b.offset + chunk.start + r]); - out.push(dot + bias); + for act in &job.acts { + let dot = match job.matrix.kind { + Kind::Q8_0 => dispatch.dot_q8_0_q8_0(row, &act.blocks), + Kind::Mxfp4 => dispatch.dot_mxfp4_q8r(row, &act.scales, &act.quants), + } + .map_err(|e| ModelError::Invalid(format!("kernel: {e}")))?; + out.push(dot + bias); + } } done.push((ci, out)); } Ok(done) }); - let mut outputs: Vec> = jobs.iter().map(|j| vec![0.0; j.rows]).collect(); + let mut outputs: Vec> = jobs + .iter() + .map(|j| vec![0.0; j.rows * j.acts.len()]) + .collect(); for part in parts { for (ci, values) in part? { let chunk = &chunks[ci]; - outputs[chunk.job][chunk.start..chunk.start + chunk.rows].copy_from_slice(&values); + let width = jobs[chunk.job].acts.len(); + outputs[chunk.job][chunk.start * width..(chunk.start + chunk.rows) * width] + .copy_from_slice(&values); } } Ok(outputs) @@ -615,15 +648,62 @@ impl Model { } /// Run one token at position `pos`, fill `state.logits` and return the greedy next token. - #[allow(unused_assignments)] // the last `lap!` resets a timer nobody reads pub fn forward(&self, state: &mut State, token: u32, pos: usize) -> Result { - let c = &self.config; - if token as usize >= c.vocab { - return Err(ModelError::TokenOutOfRange(token)); + Ok(self + .forward_chunk(state, &[token], pos, true)? + .expect("logits were requested")) + } + + /// Feed `tokens` at positions `pos0..` in chunks of [`Model::prefill_chunk`] tokens, so every weight + /// row is read once per chunk instead of once per token. The results (KV cache, logits) are bit for + /// bit what feeding the tokens one at a time gives. Returns the greedy token after the last one. + pub fn prefill( + &self, + state: &mut State, + tokens: &[u32], + pos0: usize, + ) -> Result, ModelError> { + let mut next = None; + let mut done = 0; + while done < tokens.len() { + let end = (done + self.prefill_chunk).min(tokens.len()); + next = + self.forward_chunk(state, &tokens[done..end], pos0 + done, end == tokens.len())?; + done = end; } - if pos >= state.capacity { + Ok(next) + } + + /// Tokens per prefill chunk. + pub fn prefill_chunk(&self) -> usize { + self.prefill_chunk + } + + pub fn set_prefill_chunk(&mut self, tokens: usize) { + self.prefill_chunk = tokens.max(1); + } + + /// Run `tokens` (positions `pos0..`) through all layers as one batch. With `want_logits` the logits + /// of the last token are computed into `state.logits` and its greedy successor is returned. + #[allow(unused_assignments)] // the last `lap!` resets a timer nobody reads + fn forward_chunk( + &self, + state: &mut State, + tokens: &[u32], + pos0: usize, + want_logits: bool, + ) -> Result, ModelError> { + let c = &self.config; + let n = tokens.len(); + if n == 0 { + return Ok(None); + } + if let Some(bad) = tokens.iter().find(|t| **t as usize >= c.vocab) { + return Err(ModelError::TokenOutOfRange(*bad)); + } + if pos0 + n > state.capacity { return Err(ModelError::ContextFull { - position: pos, + position: pos0 + n - 1, capacity: state.capacity, }); } @@ -631,18 +711,27 @@ impl Model { let (qw, kw) = (c.q_width(), c.kv_width()); let group = c.n_head / c.n_head_kv; - let mut x = vec![0.0f32; e]; let row_bytes = self.embd.row_bytes(); - dequantize_q8_0_row( - &self.embd.data()[token as usize * row_bytes..(token as usize + 1) * row_bytes], - &mut x, - ); - - let mut rotation = vec![(0.0f32, 0.0f32); hd / 2]; - c.yarn.rotation(pos as u32, hd, &mut rotation); + let mut xs: Vec> = tokens + .iter() + .map(|token| { + let mut x = vec![0.0f32; e]; + dequantize_q8_0_row( + &self.embd.data() + [*token as usize * row_bytes..(*token as usize + 1) * row_bytes], + &mut x, + ); + x + }) + .collect(); + let rotations: Vec> = (0..n) + .map(|t| { + let mut r = vec![(0.0f32, 0.0f32); hd / 2]; + c.yarn.rotation((pos0 + t) as u32, hd, &mut r); + r + }) + .collect(); let mut h = vec![0.0f32; e]; - let mut scores = vec![0.0f32; pos + 1]; - let mut attn = vec![0.0f32; qw]; let mut lap_start = std::time::Instant::now(); macro_rules! lap { ($field:ident) => { @@ -652,14 +741,17 @@ impl Model { } for (l, layer) in self.layers.iter().enumerate() { - // --- attention: region 1 computes Q, K and V together --- - ops::rms_norm(&x, &layer.attn_norm, c.rms_eps, &mut h); - let hq = self.quantize(&h)?; + // --- attention: region 1 computes Q, K and V of every token together --- + let mut hqs = Vec::with_capacity(n); + for x in &xs { + ops::rms_norm(x, &layer.attn_norm, c.rms_eps, &mut h); + hqs.push(self.quantize(&h)?); + } let job = |m: &QMatrix, bias: &Arc>| MatvecJob { matrix: m.clone(), first_row: 0, rows: m.rows, - act: hq.clone(), + acts: hqs.clone(), bias: Some(Bias { data: bias.clone(), offset: 0, @@ -672,82 +764,147 @@ impl Model { job(&layer.wv, &layer.bv), ])? .into_iter(); - let (mut q, mut k, v) = ( + let (q_out, k_out, v_out) = ( qkv.next().unwrap(), qkv.next().unwrap(), qkv.next().unwrap(), ); lap!(qkv_region); - for head in q.chunks_exact_mut(hd) { - ops::rope_neox(head, &rotation); + let mut qs = vec![0.0f32; n * qw]; + { + let mut kc = state.k[l].write().expect("KV cache lock"); + let mut vc = state.v[l].write().expect("KV cache lock"); + for t in 0..n { + let q_t = &mut qs[t * qw..(t + 1) * qw]; + for (r, slot) in q_t.iter_mut().enumerate() { + *slot = q_out[r * n + t]; + } + for head in q_t.chunks_exact_mut(hd) { + ops::rope_neox(head, &rotations[t]); + } + let p = pos0 + t; + let k_t = &mut kc[p * kw..(p + 1) * kw]; + let v_t = &mut vc[p * kw..(p + 1) * kw]; + for r in 0..kw { + k_t[r] = k_out[r * n + t]; + v_t[r] = v_out[r * n + t]; + } + for head in k_t.chunks_exact_mut(hd) { + ops::rope_neox(head, &rotations[t]); + } + } } - for head in k.chunks_exact_mut(hd) { - ops::rope_neox(head, &rotation); - } - state.k[l][pos * kw..(pos + 1) * kw].copy_from_slice(&k); - state.v[l][pos * kw..(pos + 1) * kw].copy_from_slice(&v); - let first = if c.is_sliding(l) { - (pos + 1).saturating_sub(c.sliding_window) - } else { - 0 - }; - let (kc, vc) = (&state.k[l], &state.v[l]); - for (head, out) in attn.chunks_exact_mut(hd).enumerate() { - let kvh = head / group; - ops::attend_with_sink( - ops::Head { - query: &q[head * hd..(head + 1) * hd], - scale: 1.0 / (hd as f32).sqrt(), - sink: layer.sinks[head], - }, - |p| &kc[p * kw + kvh * hd..p * kw + (kvh + 1) * hd], - |p| &vc[p * kw + kvh * hd..p * kw + (kvh + 1) * hd], - first..pos + 1, - &mut scores, - out, - ); + // region 2: attention, one work item per (token, KV head); the query heads that share a KV + // head are computed together + let qs = Arc::new(qs); + let (kc, vc) = (state.k[l].clone(), state.v[l].clone()); + let sinks = layer.sinks.clone(); + let counter = ChunkCounter::new(n * c.n_head_kv); + let (n_head_kv, window, sliding) = (c.n_head_kv, c.sliding_window, c.is_sliding(l)); + let parts: Vec)>> = self.pool.broadcast(move |_| { + let kc = kc.read().expect("KV cache lock"); + let vc = vc.read().expect("KV cache lock"); + let mut done = Vec::new(); + let mut scores = Vec::new(); + while let Some(item) = counter.claim() { + let (t, kvh) = (item / n_head_kv, item % n_head_kv); + let pos = pos0 + t; + let first = if sliding { + (pos + 1).saturating_sub(window) + } else { + 0 + }; + scores.resize(pos + 1, 0.0f32); + let mut out = vec![0.0f32; group * hd]; + for g in 0..group { + let head = kvh * group + g; + ops::attend_with_sink( + ops::Head { + query: &qs[t * qw + head * hd..t * qw + (head + 1) * hd], + scale: 1.0 / (hd as f32).sqrt(), + sink: sinks[head], + }, + |p| &kc[p * kw + kvh * hd..p * kw + (kvh + 1) * hd], + |p| &vc[p * kw + kvh * hd..p * kw + (kvh + 1) * hd], + first..pos + 1, + &mut scores, + &mut out[g * hd..(g + 1) * hd], + ); + } + done.push((t, kvh, out)); + } + done + }); + let mut attns = vec![vec![0.0f32; qw]; n]; + for (t, kvh, out) in parts.into_iter().flatten() { + attns[t][kvh * group * hd..(kvh + 1) * group * hd].copy_from_slice(&out); } lap!(attention); - let aq = self.quantize(&attn)?; + let aqs = attns + .iter() + .map(|a| self.quantize(a)) + .collect::, _>>()?; let proj = self .run_region(vec![MatvecJob { matrix: layer.wo.clone(), first_row: 0, rows: e, - act: aq, + acts: aqs, bias: Some(Bias { data: layer.bo.clone(), offset: 0, }), }])? .remove(0); - for (xi, p) in x.iter_mut().zip(&proj) { - *xi += p; + for (t, x) in xs.iter_mut().enumerate() { + for (r, xi) in x.iter_mut().enumerate() { + *xi += proj[r * n + t]; + } } lap!(o_region); - // --- mixture of experts --- - ops::rms_norm(&x, &layer.post_norm, c.rms_eps, &mut h); - let mut logits = vec![0.0f32; c.n_expert]; - for (ex, slot) in logits.iter_mut().enumerate() { - let w = &layer.router_w[ex * e..(ex + 1) * e]; - let mut dot = 0.0f32; - for (a, b) in w.iter().zip(&h) { - dot += a * b; + // --- mixture of experts: tokens are grouped by expert so each expert is read once --- + let mut hqs = Vec::with_capacity(n); + let mut chosen: Vec> = Vec::with_capacity(n); + for x in &xs { + ops::rms_norm(x, &layer.post_norm, c.rms_eps, &mut h); + let mut logits = vec![0.0f32; c.n_expert]; + for (ex, slot) in logits.iter_mut().enumerate() { + let w = &layer.router_w[ex * e..(ex + 1) * e]; + let mut dot = 0.0f32; + for (a, b) in w.iter().zip(&h) { + dot += a * b; + } + *slot = dot + layer.router_b[ex]; } - *slot = dot + layer.router_b[ex]; + chosen.push(ops::route_top_k(&logits, c.n_expert_used)); + hqs.push(self.quantize(&h)?); } - let chosen = ops::route_top_k(&logits, c.n_expert_used); - let hq = self.quantize(&h)?; - // region 3: gate and up of every chosen expert + // (token, slot) pairs routed to each expert, and each pair's index within its expert + let mut per_expert: Vec> = vec![Vec::new(); c.n_expert]; + let mut index_in_expert = vec![vec![0usize; c.n_expert_used]; n]; + for (t, picks) in chosen.iter().enumerate() { + for (slot, (ex, _)) in picks.iter().enumerate() { + index_in_expert[t][slot] = per_expert[*ex].len(); + per_expert[*ex].push((t, slot)); + } + } + let active: Vec = (0..c.n_expert) + .filter(|ex| !per_expert[*ex].is_empty()) + .collect(); + // region 3: gate and up of every active expert, for the tokens routed to it let mut jobs = Vec::new(); - for (ex, _) in &chosen { + for ex in &active { + let acts: Vec> = per_expert[*ex] + .iter() + .map(|(t, _)| hqs[*t].clone()) + .collect(); for (m, b) in [(&layer.gate, &layer.gate_b), (&layer.up, &layer.up_b)] { jobs.push(MatvecJob { matrix: m.clone(), first_row: ex * c.n_ff, rows: c.n_ff, - act: hq.clone(), + acts: acts.clone(), bias: Some(Bias { data: b.clone(), offset: ex * c.n_ff, @@ -758,20 +915,30 @@ impl Model { lap!(router); let gu = self.run_region(jobs)?; lap!(gateup_region); - // activation per expert, then region 4: all down projections + // activation per (expert, token), then region 4: all down projections let mut down_jobs = Vec::new(); - for (i, (ex, _)) in chosen.iter().enumerate() { + for (i, ex) in active.iter().enumerate() { let (gate, up) = (&gu[2 * i], &gu[2 * i + 1]); - let act: Vec = gate - .iter() - .zip(up) - .map(|(g, u)| ops::swiglu_oai(*g, *u, SWIGLU_ALPHA, SWIGLU_LIMIT)) - .collect(); + let na = per_expert[*ex].len(); + let mut acts = Vec::with_capacity(na); + for a in 0..na { + let act: Vec = (0..c.n_ff) + .map(|r| { + ops::swiglu_oai( + gate[r * na + a], + up[r * na + a], + SWIGLU_ALPHA, + SWIGLU_LIMIT, + ) + }) + .collect(); + acts.push(self.quantize(&act)?); + } down_jobs.push(MatvecJob { matrix: layer.down.clone(), first_row: ex * e, rows: e, - act: self.quantize(&act)?, + acts, bias: Some(Bias { data: layer.down_b.clone(), offset: ex * e, @@ -780,38 +947,45 @@ impl Model { } lap!(activation); let downs = self.run_region(down_jobs)?; - let mut moe = vec![0.0f32; e]; - for ((_, weight), down) in chosen.iter().zip(&downs) { - for (m, dv) in moe.iter_mut().zip(down) { - *m += weight * dv; - } + let mut active_slot = vec![usize::MAX; c.n_expert]; + for (i, ex) in active.iter().enumerate() { + active_slot[*ex] = i; } - for (xi, m) in x.iter_mut().zip(&moe) { - *xi += m; + for (t, x) in xs.iter_mut().enumerate() { + let mut moe = vec![0.0f32; e]; + for (slot, (ex, weight)) in chosen[t].iter().enumerate() { + let down = &downs[active_slot[*ex]]; + let na = per_expert[*ex].len(); + let a = index_in_expert[t][slot]; + for (r, m) in moe.iter_mut().enumerate() { + *m += weight * down[r * na + a]; + } + } + for (xi, m) in x.iter_mut().zip(&moe) { + *xi += m; + } } lap!(down_region); } - ops::rms_norm(&x, &self.output_norm, c.rms_eps, &mut h); - let hq = self.quantize(&h)?; - state.logits = self - .run_region(vec![MatvecJob { - matrix: self.output.clone(), - first_row: 0, - rows: c.vocab, - act: hq, - bias: None, - }])? - .remove(0); - let mut best = 0usize; - for (i, l) in state.logits.iter().enumerate() { - if *l > state.logits[best] { - best = i; - } + let mut next = None; + if want_logits { + ops::rms_norm(&xs[n - 1], &self.output_norm, c.rms_eps, &mut h); + let hq = self.quantize(&h)?; + state.logits = self + .run_region(vec![MatvecJob { + matrix: self.output.clone(), + first_row: 0, + rows: c.vocab, + acts: vec![hq], + bias: None, + }])? + .remove(0); + next = Some(argmax(&state.logits) as u32); } lap!(lm_head); - state.profile.tokens += 1; - Ok(best as u32) + state.profile.tokens += n as u32; + Ok(next) } /// Feed `prompt` and then generate up to `max_new` tokens greedily, stopping early on `stop`. @@ -822,10 +996,7 @@ impl Model { max_new: usize, stop: &[u32], ) -> Result, ModelError> { - let mut next = 0; - for (pos, token) in prompt.iter().enumerate() { - next = self.forward(state, *token, pos)?; - } + let mut next = self.prefill(state, prompt, 0)?.unwrap_or(0); let mut out = Vec::new(); let mut pos = prompt.len(); while out.len() < max_new && !prompt.is_empty() { diff --git a/crates/gptoss/tests/synthetic_model.rs b/crates/gptoss/tests/synthetic_model.rs index 6ca52093..87cd6767 100644 --- a/crates/gptoss/tests/synthetic_model.rs +++ b/crates/gptoss/tests/synthetic_model.rs @@ -640,6 +640,80 @@ fn context_overflow_and_bad_tokens_are_errors() { )); } +#[test] +fn chunked_prefill_is_bit_identical_to_feeding_tokens_one_at_a_time() { + let w = build_world(8); + let gguf = Gguf::read(&w.file[..], w.file.len() as u64).unwrap(); + let tokens = [5u32, 17, 3, 42, 9, 60, 11, 30, 2, 71, 8]; + for threads in [1usize, 3] { + let mut model = Model::load( + std::sync::Arc::new(w.file.clone()), + &gguf, + Dispatch::best(), + threads, + ) + .unwrap(); + let mut seq = State::new(&model.config, 16); + let mut seq_next = 0; + for (pos, t) in tokens.iter().enumerate() { + seq_next = model.forward(&mut seq, *t, pos).unwrap(); + } + // the continuation after the prompt exercises the cache the prefill filled + let seq_after = model.forward(&mut seq, 13, tokens.len()).unwrap(); + for chunk in [1usize, 2, 3, 4, 11, 64] { + model.set_prefill_chunk(chunk); + let mut st = State::new(&model.config, 16); + let next = model.prefill(&mut st, &tokens, 0).unwrap(); + assert_eq!(next, Some(seq_next), "chunk {chunk} threads {threads}"); + let prefill_logits = st.logits.clone(); + let after = model.forward(&mut st, 13, tokens.len()).unwrap(); + assert_eq!(after, seq_after, "chunk {chunk} threads {threads}"); + assert_eq!( + st.logits.iter().map(|v| v.to_bits()).collect::>(), + seq.logits.iter().map(|v| v.to_bits()).collect::>(), + "logits after the continuation, chunk {chunk} threads {threads}" + ); + // logits right after the prefill, against a fresh sequential run of the same tokens + let mut again = State::new(&model.config, 16); + for (pos, t) in tokens.iter().enumerate() { + model.forward(&mut again, *t, pos).unwrap(); + } + assert_eq!( + prefill_logits + .iter() + .map(|v| v.to_bits()) + .collect::>(), + again.logits.iter().map(|v| v.to_bits()).collect::>(), + "logits after the prefill, chunk {chunk} threads {threads}" + ); + } + } +} + +#[test] +fn prefill_can_resume_after_an_earlier_prefix() { + let w = build_world(10); + let gguf = Gguf::read(&w.file[..], w.file.len() as u64).unwrap(); + let model = Model::load( + std::sync::Arc::new(w.file.clone()), + &gguf, + Dispatch::best(), + 2, + ) + .unwrap(); + let tokens = [4u32, 9, 22, 31, 6, 18, 55, 3]; + let mut whole = State::new(&model.config, 16); + model.prefill(&mut whole, &tokens, 0).unwrap(); + let mut split = State::new(&model.config, 16); + model.prefill(&mut split, &tokens[..5], 0).unwrap(); + model.prefill(&mut split, &tokens[5..], 5).unwrap(); + assert_eq!( + whole.logits.iter().map(|v| v.to_bits()).collect::>(), + split.logits.iter().map(|v| v.to_bits()).collect::>() + ); + assert_eq!(model.prefill(&mut whole, &[], 8).unwrap(), None); +} + #[test] fn greedy_generation_is_deterministic_and_respects_stop_tokens() { let w = build_world(6);