From 5266c34ce8703fbb7b55e17d90347275c016fad8 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 00:06:59 +0100 Subject: [PATCH 1/2] STRA-338 params p04: experimental-ref (cache, cvec, kv_stream, remote_experts, attn, tests) down to 5 parameters --- .../cuda-driver/src/experimental_gpu_smoke.rs | 18 ++- crates/experimental-ref/src/attn.rs | 14 +- crates/experimental-ref/src/cache.rs | 136 ++++++++++-------- crates/experimental-ref/src/cache/tests.rs | 32 ++++- .../src/cvec/load_control_vectors.rs | 14 +- crates/experimental-ref/src/cvec/tests.rs | 27 ++-- crates/experimental-ref/src/kv_stream.rs | 19 +++ .../src/kv_stream/impl_streammap.rs | 36 +---- .../src/kv_stream/map_bytes.rs | 20 +-- .../experimental-ref/src/kv_stream/tests.rs | 38 +++-- crates/experimental-ref/src/remote_experts.rs | 70 ++++++--- .../src/remote_experts/tests.rs | 71 ++++++--- .../tests/emulated_kernels.rs | 20 +-- .../tests/emulated_kernels/cvec_reduction.rs | 42 +++--- .../emulated_kernels/fwht_and_q4_append.rs | 10 +- .../emulated_kernels/int8_and_k8v4_append.rs | 4 +- .../kv_stream_and_keyless_routing.rs | 3 +- .../emulated_kernels/quantized_attention.rs | 18 ++- .../experimental-ref/tests/remote_golden.rs | 21 ++- crates/experimental-ref/tests/stream_plan.rs | 3 +- 20 files changed, 382 insertions(+), 234 deletions(-) diff --git a/crates/cuda-driver/src/experimental_gpu_smoke.rs b/crates/cuda-driver/src/experimental_gpu_smoke.rs index 5e3d9f84..d1e90f01 100644 --- a/crates/cuda-driver/src/experimental_gpu_smoke.rs +++ b/crates/cuda-driver/src/experimental_gpu_smoke.rs @@ -9,7 +9,7 @@ use super::experimental::{KvShape, Mode, OptIn, Program}; use super::experimental_gpu::{Experimental, Paged, StreamMap}; use super::{Context, DeviceBuffer, Driver}; use leleka_experimental_ref::{ - cache::{PoolSet, append_cell, gather_q4}, + cache::{CellAt, CellKv, PoolSet, PoolTarget, append_cell, gather_q4}, fwht::fwht256, keyless, kv_stream::{CTL_INTS, StreamMap as CpuMap}, @@ -123,7 +123,9 @@ fn matching_model( for (name, c) in [("fused", Contraction::Fused), ("separate", Contraction::Separate)] { let mut m = PoolSet::new(KvFormat::Q4_0, q, p.shape.rows(p.pages)).unwrap(); for (pos, kc, vc) in cells { - append_cell(KvFormat::Q4_0, &mut m, None, table, i64::from(*pos), kc, vc, q, c).unwrap(); + let target = PoolTarget { pools: &mut m, host: None }; + let at = CellAt { table, pos: i64::from(*pos), shapes: q }; + append_cell(KvFormat::Q4_0, target, at, CellKv { k: kc, v: vc }, c).unwrap(); } if m.k_q4 == got.0 && m.v_q4 == got.1 { return (name, m); @@ -308,11 +310,13 @@ fn assert_resolved_like_cpu( let mut cpu = CpuMap::new(STREAM_BLOCKS as usize, STREAM_SLOTS as usize); let report = cpu .resolve( - inputs.0, - inputs.1, - STREAM_QUERIES as usize, - STREAM_CAP as usize, - 4, + leleka_experimental_ref::kv_stream::ResolveBatch { + ids: inputs.0, + steps: inputs.1, + n_q: STREAM_QUERIES as usize, + cap: STREAM_CAP as usize, + page_size: 4, + }, &leleka_experimental_ref::kv_stream::MissOrder::Canonical, ) .expect("cpu resolve"); diff --git a/crates/experimental-ref/src/attn.rs b/crates/experimental-ref/src/attn.rs index e0a203b7..f4b3893d 100644 --- a/crates/experimental-ref/src/attn.rs +++ b/crates/experimental-ref/src/attn.rs @@ -29,9 +29,17 @@ pub fn n_chunks(cap: i64) -> i64 { /// The score scale of the Original (`1.0f / sqrtf((float) HD)`), exactly 1/16. pub const SCALE: f32 = 0.0625; +/// The head counts and the number of attended cells of one reference attention. +#[derive(Clone, Copy, Debug)] +pub struct AttnShape { + pub n_head: usize, + pub n_head_kv: usize, + pub n_ids: usize, +} + /// Softmax GQA attention in f64. `q` is `[n_head][256]`; `k` and `v` are `[n_ids][n_head_kv][256]` /// (dequantized, already in the domain the kernel sees); `n_ids` cells are attended. Returns `[n_head][256]`. -pub fn reference(q: &[f32], k: &[f32], v: &[f32], n_head: usize, n_head_kv: usize, n_ids: usize) -> Vec { +pub fn reference(q: &[f32], k: &[f32], v: &[f32], AttnShape { n_head, n_head_kv, n_ids }: AttnShape) -> Vec { assert_eq!(n_head % n_head_kv, 0); assert_eq!(q.len(), n_head * HD); assert_eq!(k.len(), n_ids * n_head_kv * HD); @@ -96,7 +104,7 @@ mod tests { for j in 0..n { v[j * HD] = (j + 1) as f32; // 1, 2, 3 } - let out = reference(&q, &k, &v, nh, nkv, n); + let out = reference(&q, &k, &v, AttnShape { n_head: nh, n_head_kv: nkv, n_ids: n }); assert!((out[0] - 2.0).abs() < 1e-12 && (out[HD] - 2.0).abs() < 1e-12); } @@ -110,7 +118,7 @@ mod tests { let mut v = vec![0.0f32; n * HD]; v[0] = 5.0; v[HD] = -7.0; - let out = reference(&q, &k, &v, nh, nkv, n); + let out = reference(&q, &k, &v, AttnShape { n_head: nh, n_head_kv: nkv, n_ids: n }); assert!((out[0] - 5.0).abs() < 1e-3); } } diff --git a/crates/experimental-ref/src/cache.rs b/crates/experimental-ref/src/cache.rs index 956821fb..ddfb064b 100644 --- a/crates/experimental-ref/src/cache.rs +++ b/crates/experimental-ref/src/cache.rs @@ -114,13 +114,48 @@ fn write_q4(pool: &mut [u8], row: u64, b: usize, blk: &q4_0::BlockQ4_0, blocks_p pool[at..at + BLOCK_BYTES].copy_from_slice(&blk.to_bytes()); } -fn write_q8(codes: &mut [u8], scales: &mut [u8], row: u64, g: usize, group: &[i8; KV_Q8_GROUP], sbits: u16, hd: usize) { - let at = row as usize * hd + g * KV_Q8_GROUP; - for (i, c) in group.iter().enumerate() { - codes[at + i] = *c as u8; +/// The INT8 code and scale arrays of one half, with the `head_dim` that strides their rows. +pub struct Q8Slabs<'a> { + codes: &'a mut [u8], + scales: &'a mut [u8], + hd: usize, +} + +impl<'a> Q8Slabs<'a> { + pub fn new(codes: &'a mut [u8], scales: &'a mut [u8], s: &QsaShapes) -> Self { + Self { codes, scales, hd: s.head_dim as usize } } - let sat = (row as usize * (hd / KV_Q8_GROUP) + g) * 2; - scales[sat..sat + 2].copy_from_slice(&sbits.to_le_bytes()); + + fn write(&mut self, row: u64, g: usize, group: &[i8; KV_Q8_GROUP], sbits: u16) { + let hd = self.hd; + let at = row as usize * hd + g * KV_Q8_GROUP; + for (i, c) in group.iter().enumerate() { + self.codes[at + i] = *c as u8; + } + let sat = (row as usize * (hd / KV_Q8_GROUP) + g) * 2; + self.scales[sat..sat + 2].copy_from_slice(&sbits.to_le_bytes()); + } +} + +/// Where one cell append lands: the page table, the cell position and the pool geometry. +#[derive(Clone, Copy)] +pub struct CellAt<'a> { + pub table: &'a [i32], + pub pos: i64, + pub shapes: &'a QsaShapes, +} + +/// The already-rotated K and V rows of one cell. +#[derive(Clone, Copy)] +pub struct CellKv<'a> { + pub k: &'a [f32], + pub v: &'a [f32], +} + +/// A pool bundle and its streaming host mirror (`None` when the cache is not streaming). +pub struct PoolTarget<'a> { + pub pools: &'a mut PoolSet, + pub host: Option<&'a mut PoolSet>, } /// Which half a Q4_0 / INT8 append writes (the Original launches z = 0 for K and z = 1 for V; the K8V4 and @@ -140,16 +175,14 @@ fn cell_target(table: &[i32], pos: i64, page_size: i64) -> Result<(usize, i32, u } /// `kv_append_q4_kernel` for one cell and one half: `x` is `[n_head_kv][head_dim]`, already rotated. -#[allow(clippy::too_many_arguments)] pub fn append_q4_half( pool: &mut [u8], host: Option<&mut [u8]>, - table: &[i32], - pos: i64, + at: CellAt, x: &[f32], - s: &QsaShapes, c: Contraction, ) -> Result<(), CacheError> { + let CellAt { table, pos, shapes: s } = at; let (hd, kvh, ps) = (s.head_dim as usize, s.n_head_kv as u64, s.page_size); if hd != 256 || x.len() != kvh as usize * hd { return Err(CacheError::Geometry); @@ -174,16 +207,8 @@ pub fn append_q4_half( /// `kv_append_q8_kernel` for one cell and one half. `k_q`/`k_scale` of a value-only cache are simply never /// passed (the Original passes null pointers and launches z = 1 only). -#[allow(clippy::too_many_arguments)] -pub fn append_q8_half( - codes: &mut [u8], - scales: &mut [u8], - host: Option<(&mut [u8], &mut [u8])>, - table: &[i32], - pos: i64, - x: &[f32], - s: &QsaShapes, -) -> Result<(), CacheError> { +pub fn append_q8_half(mut slabs: Q8Slabs, host: Option, at: CellAt, x: &[f32]) -> Result<(), CacheError> { + let CellAt { table, pos, shapes: s } = at; let (hd, kvh, ps) = (s.head_dim as usize, s.n_head_kv as u64, s.page_size); if hd % KV_Q8_GROUP != 0 || x.len() != kvh as usize * hd { return Err(CacheError::Geometry); @@ -196,10 +221,10 @@ pub fn append_q8_half( x[h as usize * hd + g * KV_Q8_GROUP..][..KV_Q8_GROUP].try_into().expect("group"); let (q, sbits) = kv_q8::quantize_group(grp); if page >= 0 { - write_q8(codes, scales, physical_row(s, page as u64, h, slot), g, &q, sbits, hd); + slabs.write(physical_row(s, page as u64, h, slot), g, &q, sbits); } - if let Some((hc, hs)) = host.as_mut() { - write_q8(hc, hs, physical_row(s, blk_page as u64, h, slot), g, &q, sbits, hd); + if let Some(hs) = host.as_mut() { + hs.write(physical_row(s, blk_page as u64, h, slot), g, &q, sbits); } } } @@ -207,66 +232,53 @@ pub fn append_q8_half( } /// INT8 K and V of one cell, each with its own codes and scales (and the host mirror's, when streaming). -fn append_int8_pair( - pools: &mut PoolSet, - host: Option<&mut PoolSet>, - table: &[i32], - pos: i64, - (k, v): (&[f32], &[f32]), - s: &QsaShapes, -) -> Result<(), CacheError> { +fn append_int8_pair(target: PoolTarget, at: CellAt, kv: CellKv) -> Result<(), CacheError> { + let PoolTarget { pools, host } = target; + let s = at.shapes; let (hk, hv) = match host { - Some(PoolSet { k_q, v_q, k_scale, v_scale, .. }) => { - (Some((&mut k_q[..], &mut k_scale[..])), Some((&mut v_q[..], &mut v_scale[..]))) - } + Some(PoolSet { k_q, v_q, k_scale, v_scale, .. }) => ( + Some(Q8Slabs::new(&mut k_q[..], &mut k_scale[..], s)), + Some(Q8Slabs::new(&mut v_q[..], &mut v_scale[..], s)), + ), None => (None, None), }; - append_q8_half(&mut pools.k_q, &mut pools.k_scale, hk, table, pos, k, s)?; - append_q8_half(&mut pools.v_q, &mut pools.v_scale, hv, table, pos, v, s) + append_q8_half(Q8Slabs::new(&mut pools.k_q, &mut pools.k_scale, s), hk, at, kv.k)?; + append_q8_half(Q8Slabs::new(&mut pools.v_q, &mut pools.v_scale, s), hv, at, kv.v) } /// Q4_0 K and V of one cell, each into its own pool (and the host mirror's, when streaming). -fn append_q4_pair( - pools: &mut PoolSet, - mut host: Option<&mut PoolSet>, - table: &[i32], - pos: i64, - (k, v): (&[f32], &[f32]), - (s, c): (&QsaShapes, Contraction), -) -> Result<(), CacheError> { - append_q4_half(&mut pools.k_q4, host.as_deref_mut().map(|h| &mut h.k_q4[..]), table, pos, k, s, c)?; - append_q4_half(&mut pools.v_q4, host.as_deref_mut().map(|h| &mut h.v_q4[..]), table, pos, v, s, c) +fn append_q4_pair(target: PoolTarget, at: CellAt, kv: CellKv, c: Contraction) -> Result<(), CacheError> { + let PoolTarget { pools, mut host } = target; + append_q4_half(&mut pools.k_q4, host.as_deref_mut().map(|h| &mut h.k_q4[..]), at, kv.k, c)?; + append_q4_half(&mut pools.v_q4, host.as_deref_mut().map(|h| &mut h.v_q4[..]), at, kv.v, c) } /// The whole cell append of `layer.cpp` for `format`: rotation is the caller's (`fwht256` of K and/or V as -/// [`KvFormat::rotates_k`] / [`KvFormat::rotates_v`] say); this writes the already-rotated `k` and `v`. -/// K8V4 is the composed call (INT8 K, Q4_0 V); a value-only cache ignores `k`. -#[allow(clippy::too_many_arguments)] +/// [`KvFormat::rotates_k`] / [`KvFormat::rotates_v`] say); this writes the already-rotated `kv`. +/// K8V4 is the composed call (INT8 K, Q4_0 V); a value-only cache ignores `kv.k`. pub fn append_cell( format: KvFormat, - pools: &mut PoolSet, - mut host: Option<&mut PoolSet>, - table: &[i32], - pos: i64, - k: &[f32], - v: &[f32], - s: &QsaShapes, + target: PoolTarget, + at: CellAt, + kv: CellKv, c: Contraction, ) -> Result<(), CacheError> { + let s = at.shapes; check_geometry(format, s)?; + let PoolTarget { pools, mut host } = target; match format { - KvFormat::Q4_0 => append_q4_pair(pools, host, table, pos, (k, v), (s, c)), - KvFormat::Int8 | KvFormat::Int8Rotated => append_int8_pair(pools, host, table, pos, (k, v), s), + KvFormat::Q4_0 => append_q4_pair(PoolTarget { pools, host }, at, kv, c), + KvFormat::Int8 | KvFormat::Int8Rotated => append_int8_pair(PoolTarget { pools, host }, at, kv), KvFormat::Int8Keyless => { - let hv = host.as_deref_mut().map(|h| (&mut h.v_q[..], &mut h.v_scale[..])); - append_q8_half(&mut pools.v_q, &mut pools.v_scale, hv, table, pos, v, s) + let hv = host.as_deref_mut().map(|h| Q8Slabs::new(&mut h.v_q[..], &mut h.v_scale[..], s)); + append_q8_half(Q8Slabs::new(&mut pools.v_q, &mut pools.v_scale, s), hv, at, kv.v) } KvFormat::K8V4 => { // layer.cpp: fwht256(vcur); kv_append_q8_step(k_q, k_q, ..., kcur, kcur); kv_append_q4_step(v_q4, v_q4, // ..., vcur, vcur) // mode 0 only: no host mirror ("K8V4 does not support streaming") - append_q8_half(&mut pools.k_q, &mut pools.k_scale, None, table, pos, k, s)?; - append_q4_half(&mut pools.v_q4, None, table, pos, v, s, c) + append_q8_half(Q8Slabs::new(&mut pools.k_q, &mut pools.k_scale, s), None, at, kv.k)?; + append_q4_half(&mut pools.v_q4, None, at, kv.v, c) } KvFormat::Fp16 => Err(CacheError::UnsupportedFormat), } diff --git a/crates/experimental-ref/src/cache/tests.rs b/crates/experimental-ref/src/cache/tests.rs index 071cd210..be8baee2 100644 --- a/crates/experimental-ref/src/cache/tests.rs +++ b/crates/experimental-ref/src/cache/tests.rs @@ -31,7 +31,15 @@ fn q4_round_trip_stays_within_half_a_step_in_the_rotated_domain() { let mut v = cell(2, 4.0); fwht::fwht256_rows_in_place(&mut k); fwht::fwht256_rows_in_place(&mut v); - append_cell(KvFormat::Q4_0, &mut pools, None, &table, 5, &k, &v, &S, Contraction::Separate).unwrap(); + let target = PoolTarget { pools: &mut pools, host: None }; + append_cell( + KvFormat::Q4_0, + target, + CellAt { table: &table, pos: 5, shapes: &S }, + CellKv { k: &k, v: &v }, + Contraction::Separate, + ) + .unwrap(); let back = dequant_q4(&pools.k_q4, &table, &[5], &S).unwrap(); for (i, (a, b)) in back.iter().zip(&k).enumerate() { let blk = i / 32; @@ -55,7 +63,9 @@ fn streaming_write_rule_host_always_vram_only_when_resident() { let k = cell(3, 2.0); let v = cell(4, 2.0); for pos in 0..16 { - append_cell(KvFormat::Int8, &mut pools, Some(&mut host), &table, pos, &k, &v, &S, Contraction::Fused).unwrap(); + let target = PoolTarget { pools: &mut pools, host: Some(&mut host) }; + let at = CellAt { table: &table, pos, shapes: &S }; + append_cell(KvFormat::Int8, target, at, CellKv { k: &k, v: &v }, Contraction::Fused).unwrap(); } assert!(host.k_q.iter().any(|b| *b != 0)); // resident slots (pages 0 and 1 of the VRAM pool) hold blocks 1 and 3, the rest is untouched @@ -75,7 +85,15 @@ fn k8v4_composition_writes_int8_k_and_q4_v_only() { let k = cell(5, 3.0); let mut v = cell(6, 3.0); fwht::fwht256_rows_in_place(&mut v); - append_cell(KvFormat::K8V4, &mut pools, None, &table, 0, &k, &v, &S, Contraction::Fused).unwrap(); + let target = PoolTarget { pools: &mut pools, host: None }; + append_cell( + KvFormat::K8V4, + target, + CellAt { table: &table, pos: 0, shapes: &S }, + CellKv { k: &k, v: &v }, + Contraction::Fused, + ) + .unwrap(); assert!(pools.k_q.iter().any(|b| *b != 0) && pools.v_q4.iter().any(|b| *b != 0)); assert!(pools.v_q.is_empty() && pools.k_q4.is_empty()); let kd = dequant_q8(&pools.k_q, &pools.k_scale, &table, &[0], &S).unwrap(); @@ -90,8 +108,8 @@ fn fp16_is_refused_and_geometry_is_checked() { let mut bad = S; bad.head_dim = 128; let mut p = PoolSet::new(KvFormat::Q4_0, &S, 8).unwrap(); - assert_eq!( - append_cell(KvFormat::Q4_0, &mut p, None, &[0, 1], 0, &[0.0; 256], &[0.0; 256], &bad, Contraction::Fused), - Err(CacheError::Geometry) - ); + let target = PoolTarget { pools: &mut p, host: None }; + let at = CellAt { table: &[0, 1], pos: 0, shapes: &bad }; + let kv = CellKv { k: &[0.0; 256], v: &[0.0; 256] }; + assert_eq!(append_cell(KvFormat::Q4_0, target, at, kv, Contraction::Fused), Err(CacheError::Geometry)); } diff --git a/crates/experimental-ref/src/cvec/load_control_vectors.rs b/crates/experimental-ref/src/cvec/load_control_vectors.rs index d65d4232..4222a2c6 100644 --- a/crates/experimental-ref/src/cvec/load_control_vectors.rs +++ b/crates/experimental-ref/src/cvec/load_control_vectors.rs @@ -260,19 +260,25 @@ fn block_dot(dots: &[f32; THREADS]) -> f32 { warp_xor_sum(lanes) } +/// The residual rows of one `cvec_apply` batch: `t_count` rows of `r_ld` floats. +pub struct CvecRows<'a> { + pub r: &'a mut [f32], + pub t_count: usize, + pub r_ld: usize, +} + /// One `cvec_apply` over a batch: `R` is `T` rows of `r_ld` floats, each holding `hc` streams of `n`. With /// `write`, the pending FFN write `R += bo * 2 sigmoid(inj / hc)` is applied first (`bo` rows of `bo_ld`, /// `inj` rows of `inj_ld`). Literal twin of `cvec_kernel`'s per-thread dataflow, including the reduction tree. -#[allow(clippy::too_many_arguments, clippy::needless_range_loop)] // thread/k indices mirror the CUDA text +#[allow(clippy::needless_range_loop)] // thread/k indices mirror the CUDA text pub fn apply( - r: &mut [f32], + rows: CvecRows, tables: &CvecTables, on: bool, layer: usize, - t_count: usize, - r_ld: usize, pending: Option<(&[f32], usize, &[f32], usize)>, ) { + let CvecRows { r, t_count, r_ld } = rows; let (n, hc) = (tables.n_embd as usize, tables.hc as usize); let write = pending.is_some(); let s = tables.s[layer]; diff --git a/crates/experimental-ref/src/cvec/tests.rs b/crates/experimental-ref/src/cvec/tests.rs index f4893645..9a121a3c 100644 --- a/crates/experimental-ref/src/cvec/tests.rs +++ b/crates/experimental-ref/src/cvec/tests.rs @@ -136,7 +136,16 @@ fn rejections() { assert_eq!(check_tables(&[0.0; 4097 * 2], &[0.0; 2], 4097), Err(CvecError::UnsupportedEmbd)); } -fn tables(mode: CvecMode, n: usize, hc: usize, layer: usize, l: usize, scale: f32) -> CvecTables { +/// The size of a test table: `l` layers of `n` values, `hc` streams, the steered layer `layer`. +#[derive(Clone, Copy)] +struct TableShape { + n: usize, + hc: usize, + layer: usize, + l: usize, +} + +fn tables(mode: CvecMode, TableShape { n, hc, layer, l }: TableShape, scale: f32) -> CvecTables { let mut dir = vec![0.0f32; l * n]; let mut s = vec![0.0f32; l]; let v = vec_of(n, 3.0); @@ -172,24 +181,24 @@ fn project_removes_the_component_and_add_adds() { let (n, hc, t_count) = (600usize, 3usize, 2usize); let r_ld = hc * n; let r0: Vec = (0..t_count * r_ld).map(|i| ((i * 7 % 13) as f32 - 6.0) * 0.3).collect(); - let tp = tables(CvecMode::Project, n, hc, 2, 4, 1.0); + let tp = tables(CvecMode::Project, TableShape { n, hc, layer: 2, l: 4 }, 1.0); assert_projection_removes_the_component(&tp, &r0, (n, hc, t_count)); // off: unchanged let mut r = r0.clone(); - apply(&mut r, &tp, false, 2, t_count, r_ld, None); + apply(CvecRows { r: &mut r, t_count, r_ld }, &tp, false, 2, None); assert_eq!(r, r0); // a layer without a direction is untouched - apply(&mut r, &tp, true, 1, t_count, r_ld, None); + apply(CvecRows { r: &mut r, t_count, r_ld }, &tp, true, 1, None); assert_eq!(r, r0); // add - let ta = tables(CvecMode::Add, n, hc, 2, 4, 1.0); + let ta = tables(CvecMode::Add, TableShape { n, hc, layer: 2, l: 4 }, 1.0); assert_add_adds_the_direction(&ta, &r0, (n, hc, t_count)); } fn assert_projection_removes_the_component(tp: &CvecTables, r0: &[f32], (n, hc, t_count): (usize, usize, usize)) { let r_ld = hc * n; let mut r = r0.to_vec(); - apply(&mut r, tp, true, 2, t_count, r_ld, None); + apply(CvecRows { r: &mut r, t_count, r_ld }, tp, true, 2, None); for t in 0..t_count { for c in 0..hc { let after: f64 = (0..n) @@ -203,7 +212,7 @@ fn assert_projection_removes_the_component(tp: &CvecTables, r0: &[f32], (n, hc, fn assert_add_adds_the_direction(ta: &CvecTables, r0: &[f32], (n, hc, t_count): (usize, usize, usize)) { let r_ld = hc * n; let mut r = r0.to_vec(); - apply(&mut r, ta, true, 2, t_count, r_ld, None); + apply(CvecRows { r: &mut r, t_count, r_ld }, ta, true, 2, None); for t in 0..t_count { for c in 0..hc { for j in 0..n { @@ -219,9 +228,9 @@ fn pending_write_is_applied_even_when_the_vector_is_off() { let r0: Vec = (0..hc * n).map(|i| (i % 11) as f32 * 0.1).collect(); let bo: Vec = (0..n).map(|i| (i % 5) as f32 - 2.0).collect(); let inj = vec![0.5f32, -1.0]; - let tp = tables(CvecMode::Project, n, hc, 2, 4, 1.0); + let tp = tables(CvecMode::Project, TableShape { n, hc, layer: 2, l: 4 }, 1.0); let mut r = r0.clone(); - apply(&mut r, &tp, false, 2, 1, hc * n, Some((&bo, n, &inj, hc))); + apply(CvecRows { r: &mut r, t_count: 1, r_ld: hc * n }, &tp, false, 2, Some((&bo, n, &inj, hc))); for c in 0..hc { let w = 2.0 * sigmoid(inj[c] / hc as f32); for j in 0..n { diff --git a/crates/experimental-ref/src/kv_stream.rs b/crates/experimental-ref/src/kv_stream.rs index 2d058939..040b6fb1 100644 --- a/crates/experimental-ref/src/kv_stream.rs +++ b/crates/experimental-ref/src/kv_stream.rs @@ -84,6 +84,25 @@ pub enum MissOrder { Observed(Vec), } +/// The selections of one resolve call: `ids` is `[n_q][cap]` ascending cell ids, the width of query `q` is +/// `steps[q * 4 + 3]`, and `page_size` cells make one block. +#[derive(Clone, Copy, Debug)] +pub struct ResolveBatch<'a> { + pub ids: &'a [i32], + pub steps: &'a [i32], + pub n_q: usize, + pub cap: usize, + pub page_size: i32, +} + +/// The blocks `[b0, b1)` a ring restore copies, and the ring's slot count. +#[derive(Clone, Copy, Debug)] +pub struct RingSpan { + pub b0: usize, + pub b1: usize, + pub n_slots: usize, +} + #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct ResolveReport { pub epoch: i32, diff --git a/crates/experimental-ref/src/kv_stream/impl_streammap.rs b/crates/experimental-ref/src/kv_stream/impl_streammap.rs index b7c62856..332f51ef 100644 --- a/crates/experimental-ref/src/kv_stream/impl_streammap.rs +++ b/crates/experimental-ref/src/kv_stream/impl_streammap.rs @@ -38,23 +38,14 @@ impl StreamMap { self.ctl[i + 1] = (n >> 32) as u32 as i32; } - /// One `resolve_kernel` call. `ids` is `[n_q][cap]` ascending cell ids, the width of query `q` is - /// `steps[q * 4 + 3]`. - pub fn resolve( - &mut self, - ids: &[i32], - steps: &[i32], - n_q: usize, - cap: usize, - page_size: i32, - order: &MissOrder, - ) -> Result { + /// One `resolve_kernel` call over the selections of `batch`. + pub fn resolve(&mut self, batch: ResolveBatch, order: &MissOrder) -> Result { let n = self.n_slots(); if n < RT { return Err(StreamError::TooFewSlots); } let epoch = self.ctl[0] + 1; - let (lookups, misses) = self.claim_misses(ids, steps, (n_q, cap), page_size, epoch)?; + let (lookups, misses) = self.claim_misses(&batch, epoch)?; if misses.len() > n { return Err(StreamError::CallTooLarge); } @@ -86,14 +77,8 @@ impl StreamMap { /// Step 1: hits take this epoch and their reference bit; a missing block is claimed exactly once (-1 -> -2). /// Returns the number of lookups and the claimed blocks in lookup order. - fn claim_misses( - &mut self, - ids: &[i32], - steps: &[i32], - (n_q, cap): (usize, usize), - page_size: i32, - epoch: i32, - ) -> Result<(usize, Vec), StreamError> { + fn claim_misses(&mut self, batch: &ResolveBatch, epoch: i32) -> Result<(usize, Vec), StreamError> { + let ResolveBatch { ids, steps, n_q, cap, page_size } = *batch; let mut lookups = 0usize; let mut misses: Vec = Vec::new(); for q in 0..n_q { @@ -231,15 +216,8 @@ pub fn ring_table(n_blocks: usize, n_slots: usize) -> Vec { /// `kv_ring_restore`: blocks `[b0, b1)` of the host copy into the ring slots `b % n_slots`, in runs up to the /// ring's end (the Original issues one copy per run per array). -pub fn ring_restore( - slots: &mut PoolSet, - host: &PoolSet, - s: &QsaShapes, - fmt: StreamFormat, - b0: usize, - b1: usize, - n_slots: usize, -) { +pub fn ring_restore(slots: &mut PoolSet, host: &PoolSet, s: &QsaShapes, fmt: StreamFormat, span: RingSpan) { + let RingSpan { b0, b1, n_slots } = span; for (name, len) in stream_runs(s, fmt) { let len = len as usize; let src = host.array(name).expect("host array"); diff --git a/crates/experimental-ref/src/kv_stream/map_bytes.rs b/crates/experimental-ref/src/kv_stream/map_bytes.rs index efa887d3..bd093c42 100644 --- a/crates/experimental-ref/src/kv_stream/map_bytes.rs +++ b/crates/experimental-ref/src/kv_stream/map_bytes.rs @@ -42,17 +42,19 @@ pub(super) fn align16(n: u64) -> u64 { (n + 15) & !15 } +/// The cell counts a QSA state is sized from: `max_cells`, the drafter's `ring_cells` (`<= 0`: not a ring) and +/// `kv_resident` (`<= 0`: fully resident). +#[derive(Clone, Copy, Debug)] +pub struct StateCells { + pub max_cells: i64, + pub ring_cells: i64, + pub kv_resident: i64, +} + /// `qsa_state_bytes(g, max_cells, with_rope, ring_cells)` of one QSA layer for `format`. `ring` selects the /// drafter's state (`ring_cells > 0`): K8V4 does not apply to it (the drafter is plain INT8), the other globals do. -pub fn qsa_state_bytes( - s: &QsaShapes, - format: KvFormat, - max_cells: i64, - with_rope: bool, - ring_cells: i64, - kv_resident: i64, - sw: PlanSwitches, -) -> u64 { +pub fn qsa_state_bytes(s: &QsaShapes, format: KvFormat, cells: StateCells, with_rope: bool, sw: PlanSwitches) -> u64 { + let StateCells { max_cells, ring_cells, kv_resident } = cells; let p = kv_plan(s, max_cells, ring_cells, kv_resident, sw); // g_kv_hybrid && ring_cells <= 0 selects the hybrid pool; a ring state under k8v4 is INT8 (mtp.cpp) let pool_format = if format == KvFormat::K8V4 && ring_cells > 0 { KvFormat::Int8 } else { format }; diff --git a/crates/experimental-ref/src/kv_stream/tests.rs b/crates/experimental-ref/src/kv_stream/tests.rs index ec587a35..67063651 100644 --- a/crates/experimental-ref/src/kv_stream/tests.rs +++ b/crates/experimental-ref/src/kv_stream/tests.rs @@ -4,6 +4,10 @@ use super::*; const S: QsaShapes = QsaShapes::real(); +fn batch<'a>(ids: &'a [i32], steps: &'a [i32], n_q: usize, cap: usize) -> ResolveBatch<'a> { + ResolveBatch { ids, steps, n_q, cap, page_size: 4 } +} + #[test] fn plan_matches_the_documented_modes() { let sw = PlanSwitches::default(); @@ -67,7 +71,7 @@ fn run_calls(map: &mut StreamMap, calls: usize, nb: usize, n_q: usize) { steps.extend_from_slice(&[0, 0, 0, sel.len() as i32]); ids.extend_from_slice(&sel); } - let report = map.resolve(&ids, &steps, n_q, cap, 4, &MissOrder::Canonical).unwrap(); + let report = map.resolve(batch(&ids, &steps, n_q, cap), &MissOrder::Canonical).unwrap(); assert_eq!(report.placed, report.misses); assert!(map.is_consistent()); // every selected block is resident after the call @@ -92,9 +96,9 @@ fn eviction_keeps_the_map_consistent_and_counters_add_up() { // a repeated call is all hits let ids: Vec = (0..40).collect(); let steps = [0, 0, 0, 40]; - map.resolve(&ids, &steps, 1, 40, 4, &MissOrder::Canonical).unwrap(); + map.resolve(batch(&ids, &steps, 1, 40), &MissOrder::Canonical).unwrap(); let before = map.counters().misses; - let r = map.resolve(&ids, &steps, 1, 40, 4, &MissOrder::Canonical).unwrap(); + let r = map.resolve(batch(&ids, &steps, 1, 40), &MissOrder::Canonical).unwrap(); assert_eq!(r.misses, 0); assert_eq!(map.counters().misses, before); } @@ -107,14 +111,14 @@ fn a_slot_used_by_the_call_is_never_a_victim() { let first = chunk * 40; let ids: Vec = (first * 4..(first + 40) * 4).collect(); let steps = [0, 0, 0, ids.len() as i32]; - map.resolve(&ids, &steps, 1, ids.len(), 4, &MissOrder::Canonical).unwrap(); + map.resolve(batch(&ids, &steps, 1, ids.len()), &MissOrder::Canonical).unwrap(); } assert_eq!(map.resident_blocks(), 1030); // one call that hits 40 resident blocks and misses 40 new ones: no hit block may be evicted let mut ids: Vec = (100..140).flat_map(|b| (0..4).map(move |i| b * 4 + i)).collect(); ids.extend((2000..2040).flat_map(|b| (0..4).map(move |i| b * 4 + i))); let steps = [0, 0, 0, ids.len() as i32]; - map.resolve(&ids, &steps, 1, ids.len(), 4, &MissOrder::Canonical).unwrap(); + map.resolve(batch(&ids, &steps, 1, ids.len()), &MissOrder::Canonical).unwrap(); for b in 100..140 { assert!(map.page_table[b] >= 0, "hit block {b} was evicted"); } @@ -132,8 +136,8 @@ fn observed_miss_order_changes_only_the_pairing_not_the_victim_set() { let steps = [0, 0, 0, sorted.len() as i32]; let mut a = StreamMap::new(600, 1030); let mut b = a.clone(); - a.resolve(&sorted, &steps, 1, sorted.len(), 4, &MissOrder::Canonical).unwrap(); - b.resolve(&sorted, &steps, 1, sorted.len(), 4, &MissOrder::Observed(vec![500, 9, 3, 7])).unwrap(); + a.resolve(batch(&sorted, &steps, 1, sorted.len()), &MissOrder::Canonical).unwrap(); + b.resolve(batch(&sorted, &steps, 1, sorted.len()), &MissOrder::Observed(vec![500, 9, 3, 7])).unwrap(); let mut sa = a.miss_slot[..4].to_vec(); let mut sb = b.miss_slot[..4].to_vec(); sa.sort_unstable(); @@ -142,7 +146,7 @@ fn observed_miss_order_changes_only_the_pairing_not_the_victim_set() { assert_ne!(a.page_table, b.page_table); assert!(a.is_consistent() && b.is_consistent()); assert_eq!( - a.resolve(&sorted, &steps, 1, sorted.len(), 4, &MissOrder::Observed(vec![1, 2, 3, 4])), + a.resolve(batch(&sorted, &steps, 1, sorted.len()), &MissOrder::Observed(vec![1, 2, 3, 4])), Err(StreamError::BadMissOrder) ); } @@ -152,10 +156,7 @@ fn too_many_distinct_blocks_for_the_slots_is_refused() { let mut map = StreamMap::new(5000, 1024); let ids: Vec = (0..1025 * 4).collect(); let steps = [0, 0, 0, ids.len() as i32]; - assert_eq!( - map.resolve(&ids, &steps, 1, ids.len(), 4, &MissOrder::Canonical), - Err(StreamError::CallTooLarge) - ); + assert_eq!(map.resolve(batch(&ids, &steps, 1, ids.len()), &MissOrder::Canonical), Err(StreamError::CallTooLarge)); } #[test] @@ -171,7 +172,7 @@ fn ring_table_and_restore() { *b = (i % 13) as u8; } let mut ring = PoolSet::new(KvFormat::Int8, &S, 4 * S.rows_per_page()).unwrap(); - ring_restore(&mut ring, &host, &S, StreamFormat::Int8, 6, 10, 4); + ring_restore(&mut ring, &host, &S, StreamFormat::Int8, RingSpan { b0: 6, b1: 10, n_slots: 4 }); let len = 2048; // k_q bytes of a block for b in 6..10 { let sl = b % 4; @@ -182,8 +183,15 @@ fn ring_table_and_restore() { #[test] fn state_bytes_grow_with_resident_slots_only() { let sw = PlanSwitches::default(); - let full = qsa_state_bytes(&S, KvFormat::Int8, 262_144, true, 0, 0, sw); - let streamed = qsa_state_bytes(&S, KvFormat::Int8, 262_144, true, 0, 20_480, sw); + let full = + qsa_state_bytes(&S, KvFormat::Int8, StateCells { max_cells: 262_144, ring_cells: 0, kv_resident: 0 }, true, sw); + let streamed = qsa_state_bytes( + &S, + KvFormat::Int8, + StateCells { max_cells: 262_144, ring_cells: 0, kv_resident: 20_480 }, + true, + sw, + ); assert!(streamed < full); // the streamed state is the resident one minus the evicted pages' KV, plus the map let removed = kv_pool_bytes(KvFormat::Int8, &S, 65_536) - kv_pool_bytes(KvFormat::Int8, &S, 5120); diff --git a/crates/experimental-ref/src/remote_experts.rs b/crates/experimental-ref/src/remote_experts.rs index 5084ceb6..1ce5f439 100644 --- a/crates/experimental-ref/src/remote_experts.rs +++ b/crates/experimental-ref/src/remote_experts.rs @@ -127,22 +127,41 @@ impl RemotePlan { } } +/// The helper device of `plan_open`: its index, the visible device count and its free memory. +#[derive(Clone, Copy, Debug)] +pub struct HelperDevice { + pub device: i32, + pub device_count: i32, + pub free_bytes: u64, +} + +/// The size of the tier `plan_open` plans: the slot count and the `layers x experts` table. +#[derive(Clone, Copy, Debug)] +pub struct OpenShape { + pub slots: i32, + pub layers: i64, + pub experts: i64, +} + +/// What `plan_open` chooses from: the ranked experts, the primary's residency test (`primary_has(layer, expert)` +/// is `primary.slot_of(..) >= 0`) and the claim table of the other tiers. +pub struct Candidates<'a> { + pub ranked: &'a [(i32, i32)], + pub primary_has: &'a dyn Fn(i32, i32) -> bool, + pub claimed: &'a mut [u8], +} + /// Everything `RemoteExperts::open` decides before it touches the helper device (`preflight` and the checks of -/// `open`). `primary_has(layer, expert)` is `primary.slot_of(..) >= 0`. On success `claimed` marks the helper's -/// experts (only then: a failed open leaves it untouched). -#[allow(clippy::too_many_arguments)] +/// `open`). On success `claimed` marks the helper's experts (only then: a failed open leaves it untouched). pub fn plan_open( - device: i32, - device_count: i32, - free_bytes: u64, - slots: i32, - layers: i64, - experts: i64, - ranked: &[(i32, i32)], - primary_has: &dyn Fn(i32, i32) -> bool, - claimed: &mut [u8], + helper: HelperDevice, + shape: OpenShape, + candidates: Candidates, sizes: &ExpertSizes, ) -> Result { + let HelperDevice { device, device_count, free_bytes } = helper; + let OpenShape { slots, layers, experts } = shape; + let Candidates { ranked, primary_has, claimed } = candidates; if !valid_open_arguments((device, device_count), (slots, layers, experts), ranked.len(), claimed.len()) { return Err(RemoteError::BadArguments); } @@ -291,18 +310,31 @@ impl Dispatch { } } -/// `RemoteExperts::begin` minus staging and launches. `ids` is `[n_tok][k]`, `kind` the primary verifier's -/// classification (-1 = CPU candidate, null on the one-token path), `primary_res` the primary's -/// `layer x expert -> slot` table. +/// The routing width of a dispatch: `n_tok` tokens of `k` routed experts each. +#[derive(Clone, Copy, Debug)] +pub struct RouteShape { + pub n_tok: i64, + pub k: i64, +} + +/// What the primary verifier knows: `kind` is its classification (-1 = CPU candidate, null on the one-token +/// path), `res` its `layer x expert -> slot` table. +#[derive(Clone, Copy, Debug)] +pub struct PrimaryView<'a> { + pub kind: Option<&'a [i32]>, + pub res: Option<&'a [i32]>, +} + +/// `RemoteExperts::begin` minus staging and launches. `ids` is `[n_tok][k]`. pub fn dispatch( plan: &RemotePlan, layer: i64, ids: &[i32], - n_tok: i64, - k: i64, - kind: Option<&[i32]>, - primary_res: Option<&[i32]>, + route: RouteShape, + primary: PrimaryView, ) -> Result { + let RouteShape { n_tok, k } = route; + let (kind, primary_res) = (primary.kind, primary.res); let n = dispatch_entries(plan, layer, (n_tok, k))?; let mut d = Dispatch::empty(n); if plan.layers_present[layer as usize] == 0 { diff --git a/crates/experimental-ref/src/remote_experts/tests.rs b/crates/experimental-ref/src/remote_experts/tests.rs index 9e9f6650..960e7900 100644 --- a/crates/experimental-ref/src/remote_experts/tests.rs +++ b/crates/experimental-ref/src/remote_experts/tests.rs @@ -2,6 +2,28 @@ use super::*; +fn dev(device: i32, device_count: i32, free_bytes: u64) -> HelperDevice { + HelperDevice { device, device_count, free_bytes } +} + +fn shape(slots: i32, layers: i64, experts: i64) -> OpenShape { + OpenShape { slots, layers, experts } +} + +fn cand<'a>( + ranked: &'a [(i32, i32)], + primary_has: &'a dyn Fn(i32, i32) -> bool, + claimed: &'a mut [u8], +) -> Candidates<'a> { + Candidates { ranked, primary_has, claimed } +} + +fn route(n_tok: i64, k: i64) -> RouteShape { + RouteShape { n_tok, k } +} + +const NO_PRIMARY: PrimaryView<'static> = PrimaryView { kind: None, res: None }; + fn canonical() -> ExpertSizes { ExpertSizes { native: false, max_blob: 1_382_400, blob_bytes: Vec::new() } } @@ -23,7 +45,7 @@ fn selection_skips_primary_claimed_duplicates_and_out_of_range() { claimed[2 * 8 + 3] = 1; // (2,3) taken by another tier let primary = |l: i32, e: i32| (l, e) == (1, 2); let sizes = canonical(); - let plan = plan_open(1, 2, 24 << 30, 3, 4, 8, &ranked, &primary, &mut claimed, &sizes).unwrap(); + let plan = plan_open(dev(1, 2, 24 << 30), shape(3, 4, 8), cand(&ranked, &primary, &mut claimed), &sizes).unwrap(); assert_eq!(plan.selected, [(0, 1), (1, 5), (3, 3)]); assert_eq!(plan.slot_of(1, 5), 1); assert_eq!(plan.slot_of(1, 2), -1); @@ -51,28 +73,29 @@ fn open_failures_leave_claimed_untouched() { // the boundary is inclusive let none = |_: i32, _: i32| false; let need = 2 * 1_382_400 + RESERVE_BYTES; - assert!(plan_open(1, 2, need, 2, 4, 8, &[(0, 0), (0, 1)], &none, &mut claimed, &sizes).is_ok()); + assert!(plan_open(dev(1, 2, need), shape(2, 4, 8), cand(&[(0, 0), (0, 1)], &none, &mut claimed), &sizes).is_ok()); } fn assert_bad_arguments_refused(claimed: &mut [u8], sizes: &ExpertSizes) { let none = |_: i32, _: i32| false; let bad = Err(RemoteError::BadArguments); - assert_eq!(plan_open(0, 2, 1 << 40, 2, 4, 8, &[(0, 0)], &none, claimed, sizes), bad); - assert_eq!(plan_open(2, 2, 1 << 40, 2, 4, 8, &[(0, 0)], &none, claimed, sizes), bad); - assert_eq!(plan_open(1, 2, 1 << 40, 0, 4, 8, &[(0, 0)], &none, claimed, sizes), bad); - assert_eq!(plan_open(1, 2, 1 << 40, 2, 4, 8, &[], &none, claimed, sizes), bad); - assert_eq!(plan_open(1, 2, 1 << 40, 2, 4, 7, &[(0, 0)], &none, claimed, sizes), bad); + assert_eq!(plan_open(dev(0, 2, 1 << 40), shape(2, 4, 8), cand(&[(0, 0)], &none, claimed), sizes), bad); + assert_eq!(plan_open(dev(2, 2, 1 << 40), shape(2, 4, 8), cand(&[(0, 0)], &none, claimed), sizes), bad); + assert_eq!(plan_open(dev(1, 2, 1 << 40), shape(0, 4, 8), cand(&[(0, 0)], &none, claimed), sizes), bad); + assert_eq!(plan_open(dev(1, 2, 1 << 40), shape(2, 4, 8), cand(&[], &none, claimed), sizes), bad); + assert_eq!(plan_open(dev(1, 2, 1 << 40), shape(2, 4, 7), cand(&[(0, 0)], &none, claimed), sizes), bad); } fn assert_resource_failures(claimed: &mut [u8], sizes: &ExpertSizes) { let none = |_: i32, _: i32| false; let all = |_: i32, _: i32| true; assert_eq!( - plan_open(1, 2, 1 << 40, 2, 4, 8, &[(0, 0)], &all, claimed, sizes), + plan_open(dev(1, 2, 1 << 40), shape(2, 4, 8), cand(&[(0, 0)], &all, claimed), sizes), Err(RemoteError::NoUnclaimedExperts) ); // 2 slots of 1.38 MB plus 512 MiB do not fit in 512 MiB - let e = plan_open(1, 2, 512 << 20, 2, 4, 8, &[(0, 0), (0, 1)], &none, claimed, sizes).unwrap_err(); + let e = + plan_open(dev(1, 2, 512 << 20), shape(2, 4, 8), cand(&[(0, 0), (0, 1)], &none, claimed), sizes).unwrap_err(); assert!(matches!(e, RemoteError::SlotsLeaveLessThanReserve { .. })); assert_eq!( e.message(1), @@ -87,7 +110,9 @@ fn native_packs_round_slots_up_to_256_and_keep_each_layers_size() { assert_eq!(sizes.slot_cost(1), 1280); let mut claimed = vec![0u8; 4 * 2]; let none = |_: i32, _: i32| false; - let plan = plan_open(1, 2, 1 << 30, 3, 4, 2, &[(1, 0), (3, 1), (0, 0)], &none, &mut claimed, &sizes).unwrap(); + let plan = + plan_open(dev(1, 2, 1 << 30), shape(3, 4, 2), cand(&[(1, 0), (3, 1), (0, 0)], &none, &mut claimed), &sizes) + .unwrap(); assert_eq!(plan.slot_sizes, [1025, 513, 1000]); assert_eq!(plan.needed_bytes, 1280 + 768 + 1024); } @@ -96,7 +121,13 @@ fn plan_for_dispatch() -> RemotePlan { let mut claimed = vec![0u8; 3 * 16]; let none = |_: i32, _: i32| false; // layer 1 holds experts 4, 9, 2 (slots 0, 1, 2); layer 0 holds expert 7 (slot 3) - plan_open(1, 2, 1 << 40, 4, 3, 16, &[(1, 4), (1, 9), (1, 2), (0, 7)], &none, &mut claimed, &canonical()).unwrap() + plan_open( + dev(1, 2, 1 << 40), + shape(4, 3, 16), + cand(&[(1, 4), (1, 9), (1, 2), (0, 7)], &none, &mut claimed), + &canonical(), + ) + .unwrap() } #[test] @@ -106,7 +137,7 @@ fn dispatch_groups_by_expert_in_first_appearance_order() { let mut ids = vec![0i32; 20]; ids[..10].copy_from_slice(&[4, 3, 9, 5, 6, 8, 10, 11, 12, 13]); ids[10..].copy_from_slice(&[9, 4, 1, 2, 0, 3, 5, 6, 7, 8]); - let d = dispatch(&plan, 1, &ids, 2, 10, None, None).unwrap(); + let d = dispatch(&plan, 1, &ids, route(2, 10), NO_PRIMARY).unwrap(); assert_eq!(d.groups, [Group { expert: 4, slot: 0 }, Group { expert: 9, slot: 1 }, Group { expert: 2, slot: 2 }]); assert_eq!(d.start, [0, 2, 4, 5]); assert_eq!(d.original_row, [0, 11, 2, 10, 13]); @@ -124,19 +155,19 @@ fn dispatch_respects_kind_primary_residency_and_missing_layers() { let ids: Vec = vec![4, 9, 2, 0, 1, 3, 5, 6, 8, 10]; let mut kind = vec![-1i32; 10]; kind[1] = 2; // expert 9 was already served on the primary - let d = dispatch(&plan, 1, &ids, 1, 10, Some(&kind), None).unwrap(); + let d = dispatch(&plan, 1, &ids, route(1, 10), PrimaryView { kind: Some(&kind), res: None }).unwrap(); assert_eq!(d.original_row, [0, 2]); // the primary holds expert 4 of layer 1 let mut res = vec![-1i32; 3 * 16]; res[16 + 4] = 5; - let d = dispatch(&plan, 1, &ids, 1, 10, None, Some(&res)).unwrap(); + let d = dispatch(&plan, 1, &ids, route(1, 10), PrimaryView { kind: None, res: Some(&res) }).unwrap(); assert_eq!(d.original_row, [1, 2]); // a layer the helper holds nothing of - let d = dispatch(&plan, 2, &ids, 1, 10, None, None).unwrap(); + let d = dispatch(&plan, 2, &ids, route(1, 10), NO_PRIMARY).unwrap(); assert!(d.is_empty() && d.owned.iter().all(|o| *o == 0)); assert!(d.start.is_empty()); // out-of-range experts are ignored - let d = dispatch(&plan, 1, &[-3, 99, 4, 4, 4, 4, 4, 4, 4, 4], 1, 10, None, None).unwrap(); + let d = dispatch(&plan, 1, &[-3, 99, 4, 4, 4, 4, 4, 4, 4, 4], route(1, 10), NO_PRIMARY).unwrap(); assert_eq!(d.groups.len(), 1); assert_eq!(d.original_row.len(), 8); } @@ -147,19 +178,19 @@ fn dispatch_validation() { let ids = vec![0i32; 100]; for (layer, n_tok, k) in [(1, 0, 10), (1, 9, 10), (1, 1, 9), (-1, 1, 10), (3, 1, 10)] { assert_eq!( - dispatch(&plan, layer, &ids, n_tok, k, None, None), + dispatch(&plan, layer, &ids, route(n_tok, k), NO_PRIMARY), Err(RemoteError::InvalidDispatch), "{layer} {n_tok} {k}" ); } - assert!(dispatch(&plan, 1, &ids, 8, 10, None, None).is_ok()); + assert!(dispatch(&plan, 1, &ids, route(8, 10), NO_PRIMARY).is_ok()); } #[test] fn meta_image_and_scatter() { let plan = plan_for_dispatch(); let ids: Vec = vec![4, 9, 4, 0, 1, 3, 5, 6, 8, 10]; - let d = dispatch(&plan, 1, &ids, 1, 10, None, None).unwrap(); + let d = dispatch(&plan, 1, &ids, route(1, 10), NO_PRIMARY).unwrap(); let img = RemoteMeta::to_bytes(&d, &|slot| 0x1000_0000 + slot as u64 * 0x10_0000); assert_eq!(u64::from_le_bytes(img[0..8].try_into().unwrap()), 0x1000_0000); assert_eq!(u64::from_le_bytes(img[8..16].try_into().unwrap()), 0x1010_0000); @@ -184,7 +215,7 @@ fn device_buffers_fit_a_small_budget() { assert_eq!(moe_hit_grouped_scratch_bytes(0, 2560, 640), 0); assert_eq!(native_expert_scratch_bytes(80, 640), 3 * 204_800 + ((80 * 20 * 36 + 255) & !255)); let mut t = Totals::default(); - let d = dispatch(&plan_for_dispatch(), 1, &[4; 10], 1, 10, None, None).unwrap(); + let d = dispatch(&plan_for_dispatch(), 1, &[4; 10], route(1, 10), NO_PRIMARY).unwrap(); t.record(&d); assert_eq!((t.computed, t.launched_layers), (10, 1)); } diff --git a/crates/experimental-ref/tests/emulated_kernels.rs b/crates/experimental-ref/tests/emulated_kernels.rs index 30747bb5..7c9a0e6a 100644 --- a/crates/experimental-ref/tests/emulated_kernels.rs +++ b/crates/experimental-ref/tests/emulated_kernels.rs @@ -6,7 +6,7 @@ mod common; use common::*; use leleka_experimental_ref::{ - cache::{self, PoolSet}, + cache::{self, CellAt, CellKv, PoolSet, PoolTarget}, fwht, layout::{KvFormat, QsaShapes}, q4_0::Contraction, @@ -89,18 +89,18 @@ fn gqa_tensors(ids: &[i32], deq: &dyn Fn(&[i32]) -> Vec) -> Vec { deq(ids) } -fn check_attention( - name: &str, - got: &[f32], - q: &[Vec], - selections: &[Vec], - k: &dyn Fn(&[i32]) -> Vec, - v: &dyn Fn(&[i32]) -> Vec, -) { +/// The dequantizers of one attention case: the K and V values at the selected cells. +struct Dequant<'a> { + k: &'a dyn Fn(&[i32]) -> Vec, + v: &'a dyn Fn(&[i32]) -> Vec, +} + +fn check_attention(name: &str, got: &[f32], q: &[Vec], selections: &[Vec], deq: Dequant) { assert_eq!(got.len(), NQ * NH * 256); for b in 0..NQ { let ids = &selections[b]; - let want = attn::reference(&q[b], &gqa_tensors(ids, k), &gqa_tensors(ids, v), NH, 2, ids.len()); + let shape = attn::AttnShape { n_head: NH, n_head_kv: 2, n_ids: ids.len() }; + let want = attn::reference(&q[b], &gqa_tensors(ids, deq.k), &gqa_tensors(ids, deq.v), shape); let (l2, max) = attn::errors(&got[b * NH * 256..(b + 1) * NH * 256], &want); eprintln!("{name} query {b}: relative L2 {l2:e}, max abs {max:e}"); assert!( diff --git a/crates/experimental-ref/tests/emulated_kernels/cvec_reduction.rs b/crates/experimental-ref/tests/emulated_kernels/cvec_reduction.rs index 69d11d80..d59b171a 100644 --- a/crates/experimental-ref/tests/emulated_kernels/cvec_reduction.rs +++ b/crates/experimental-ref/tests/emulated_kernels/cvec_reduction.rs @@ -68,11 +68,12 @@ impl CvecCase { /// The residual after one `apply` of the case's table `spec` on layer `layer_used`. fn run(&self, spec: &CaseSpec, layer_used: usize) -> Vec { - let dirv = if spec.unit { &self.unit } else { &self.add_dir }; - let t = self.table(spec.mode, dirv, spec.scale); + let dirv = if spec.table.unit { &self.unit } else { &self.add_dir }; + let t = self.table(spec.table.mode, dirv, spec.table.scale); let mut r = self.r0.clone(); let pending = if spec.write { Some((&self.bo[..], self.n, &self.inj[..], self.hc)) } else { None }; - cvec::apply(&mut r, &t, spec.on, layer_used, self.t_count, self.hc * self.n, pending); + let rows = cvec::CvecRows { r: &mut r, t_count: self.t_count, r_ld: self.hc * self.n }; + cvec::apply(rows, &t, spec.on, layer_used, pending); r } } @@ -80,28 +81,37 @@ impl CvecCase { /// One case: the table (mode, which direction, scale), whether steering is on, and whether a write is pending. struct CaseSpec { name: &'static str, - mode: CvecMode, - unit: bool, - scale: f32, + table: TableSpec, on: bool, write: bool, } -const fn spec(name: &'static str, mode: CvecMode, unit: bool, scale: f32, on: bool, write: bool) -> CaseSpec { - CaseSpec { name, mode, unit, scale, on, write } +/// The table of a case: its mode, whether it steers with the unit direction, and the scale. +struct TableSpec { + mode: CvecMode, + unit: bool, + scale: f32, +} + +const fn tab(mode: CvecMode, unit: bool, scale: f32) -> TableSpec { + TableSpec { mode, unit, scale } +} + +const fn spec(name: &'static str, table: TableSpec, on: bool, write: bool) -> CaseSpec { + CaseSpec { name, table, on, write } } /// The eight cases of the fixture; the last one runs on layer 1, which has no direction. fn case_specs() -> [CaseSpec; 8] { [ - spec("project_s1", CvecMode::Project, true, 1.0, true, false), - spec("project_s2", CvecMode::Project, true, 2.0, true, false), - spec("add", CvecMode::Add, false, 1.0, true, false), - spec("off", CvecMode::Project, true, 1.0, false, false), - spec("off_write", CvecMode::Project, true, 1.0, false, true), - spec("project_write", CvecMode::Project, true, 1.0, true, true), - spec("add_write", CvecMode::Add, false, 1.0, true, true), - spec("no_direction_layer", CvecMode::Project, true, 1.0, true, false), + spec("project_s1", tab(CvecMode::Project, true, 1.0), true, false), + spec("project_s2", tab(CvecMode::Project, true, 2.0), true, false), + spec("add", tab(CvecMode::Add, false, 1.0), true, false), + spec("off", tab(CvecMode::Project, true, 1.0), false, false), + spec("off_write", tab(CvecMode::Project, true, 1.0), false, true), + spec("project_write", tab(CvecMode::Project, true, 1.0), true, true), + spec("add_write", tab(CvecMode::Add, false, 1.0), true, true), + spec("no_direction_layer", tab(CvecMode::Project, true, 1.0), true, false), ] } diff --git a/crates/experimental-ref/tests/emulated_kernels/fwht_and_q4_append.rs b/crates/experimental-ref/tests/emulated_kernels/fwht_and_q4_append.rs index 7532db82..c64ecac2 100644 --- a/crates/experimental-ref/tests/emulated_kernels/fwht_and_q4_append.rs +++ b/crates/experimental-ref/tests/emulated_kernels/fwht_and_q4_append.rs @@ -33,8 +33,9 @@ fn append_cells_one_by_one(f: &serde_json::Value, ks: &[Vec], vs: &[Vec Result (RemotePlan, Vec) { @@ -89,15 +92,11 @@ fn dispatch_case(plan: &RemotePlan, primary: &[u8], c: &Value) -> Result = ints(&c["ids"]).iter().map(|&x| x as i32).collect(); let kind: Vec = ints(&c["kind"]).iter().map(|&x| x as i32).collect(); let (n_tok, k) = (c["n_tok"].as_i64().unwrap(), c["k"].as_i64().unwrap()); - dispatch( - plan, - c["layer"].as_i64().unwrap(), - &ids, - n_tok, - k, - (c["use_kind"].as_i64() == Some(1)).then_some(&kind[..]), - (c["use_primary"].as_i64() == Some(1)).then_some(&pres[..]), - ) + let primary = PrimaryView { + kind: (c["use_kind"].as_i64() == Some(1)).then_some(&kind[..]), + res: (c["use_primary"].as_i64() == Some(1)).then_some(&pres[..]), + }; + dispatch(plan, c["layer"].as_i64().unwrap(), &ids, RouteShape { n_tok, k }, primary) } /// The grouping arrays of a launched dispatch equal the original's. diff --git a/crates/experimental-ref/tests/stream_plan.rs b/crates/experimental-ref/tests/stream_plan.rs index 233b857d..ad1f85f6 100644 --- a/crates/experimental-ref/tests/stream_plan.rs +++ b/crates/experimental-ref/tests/stream_plan.rs @@ -36,7 +36,8 @@ fn check_case(s: &QsaShapes, c: &serde_json::Value) -> usize { assert_eq!(plan.slots, c["slots"].as_i64().unwrap(), "{ctx}"); assert_eq!(plan.pooled_rows, c["pooled_rows"].as_i64().unwrap(), "{ctx}"); let rope = c["rope"].as_i64() == Some(1); - let bytes = kv_stream::qsa_state_bytes(s, format, max_cells, rope, ring, resident, sw); + let cells = kv_stream::StateCells { max_cells, ring_cells: ring, kv_resident: resident }; + let bytes = kv_stream::qsa_state_bytes(s, format, cells, rope, sw); assert_eq!(bytes, c["state_bytes"].as_u64().unwrap(), "{ctx}"); plan.mode as usize } From 48417b6b417e957dee086a206d2134b5098821fa Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 01:05:51 +0100 Subject: [PATCH 2/2] STRA-338 params p04: gptoss family (gptoss, igpu, gptoss-igpu, gptoss-npu, gpu-npu-worker, npu-service) down to 5 parameters; domain names for the experimental-ref structs --- crates/cpu-worker/src/engine.rs | 12 +- .../cuda-driver/src/experimental_gpu_smoke.rs | 6 +- crates/experimental-ref/src/attn.rs | 55 ++++--- crates/experimental-ref/src/cache.rs | 15 +- crates/experimental-ref/src/cache/tests.rs | 8 +- .../src/cvec/load_control_vectors.rs | 8 +- crates/experimental-ref/src/cvec/tests.rs | 42 +++--- crates/experimental-ref/src/kv_stream.rs | 14 +- .../{impl_streammap.rs => residency_map.rs} | 4 +- .../experimental-ref/src/kv_stream/tests.rs | 26 ++-- crates/experimental-ref/src/remote_experts.rs | 14 +- .../src/remote_experts/tests.rs | 78 ++++++---- .../tests/emulated_kernels.rs | 6 +- .../tests/emulated_kernels/cvec_reduction.rs | 22 +-- .../emulated_kernels/fwht_and_q4_append.rs | 4 +- .../emulated_kernels/int8_and_k8v4_append.rs | 2 +- .../kv_stream_and_keyless_routing.rs | 2 +- .../emulated_kernels/quantized_attention.rs | 8 +- .../experimental-ref/tests/remote_golden.rs | 6 +- crates/gptoss-igpu/examples/ab_prefill.rs | 12 +- .../gptoss-igpu/examples/admission_check.rs | 6 +- crates/gptoss-igpu/examples/gpu_prefill.rs | 6 +- crates/gptoss-igpu/examples/layer0_probe.rs | 9 +- crates/gptoss-igpu/src/lib.rs | 14 +- crates/gptoss-igpu/src/prefill_pass.rs | 18 +-- crates/gptoss-igpu/src/prefill_run.rs | 135 ++++++++++++------ crates/gptoss-npu/examples/ab_prefill_npu.rs | 12 +- crates/gptoss-npu/examples/npu_prefill.rs | 6 +- crates/gptoss-npu/examples/numerics_probe.rs | 5 +- crates/gptoss-npu/src/accelerator.rs | 6 +- crates/gptoss-npu/src/client.rs | 22 ++- .../src/construction_and_estimates.rs | 10 +- crates/gptoss-npu/src/expert_pass.rs | 16 +-- crates/gptoss-npu/src/lib.rs | 6 +- crates/gptoss-npu/src/prefill_batch.rs | 44 +++--- crates/gptoss-npu/src/prefill_part_pass.rs | 16 +-- crates/gptoss-npu/src/service_transfers.rs | 15 +- crates/gptoss/src/forward_attention.rs | 2 +- crates/gptoss/src/lib.rs | 4 +- crates/gptoss/src/model.rs | 18 +-- crates/gptoss/src/ops.rs | 13 +- crates/gptoss/src/ops/tests.rs | 35 ++--- crates/gptoss/src/prefill.rs | 7 +- crates/gptoss/src/state_and_cache.rs | 35 ++++- crates/gptoss/src/tensor_loading.rs | 30 ++-- .../gpu-npu-worker/examples/split_prefill.rs | 6 +- crates/gpu-npu-worker/src/lib.rs | 36 +++-- crates/gpu-npu-worker/src/split_run.rs | 50 ++++--- crates/igpu/examples/attn_bench.rs | 6 +- crates/igpu/src/lib.rs | 2 + crates/igpu/src/matrices_and_moe_plan.rs | 4 +- crates/igpu/src/params.rs | 84 +++++++++++ .../igpu/src/recorder_attention_and_submit.rs | 17 +-- crates/igpu/src/recorder_core.rs | 19 +-- crates/igpu/src/recorder_moe.rs | 18 +-- crates/igpu/src/recorder_norm_and_routing.rs | 32 +---- crates/igpu/tests/attention.rs | 19 +-- crates/igpu/tests/gemm.rs | 36 +++-- crates/igpu/tests/moe.rs | 16 ++- crates/igpu/tests/norm.rs | 11 +- crates/igpu/tests/real_weights.rs | 16 ++- crates/npu-service/tests/service.rs | 23 ++- 62 files changed, 734 insertions(+), 495 deletions(-) rename crates/experimental-ref/src/kv_stream/{impl_streammap.rs => residency_map.rs} (98%) diff --git a/crates/cpu-worker/src/engine.rs b/crates/cpu-worker/src/engine.rs index 87f88f4e..3199bb6d 100644 --- a/crates/cpu-worker/src/engine.rs +++ b/crates/cpu-worker/src/engine.rs @@ -247,13 +247,11 @@ impl Decoder for GptOssEngine { self.select_slot(prompt); let state = &mut self.slots[self.active].state; if let Some(accelerator) = self.accelerator.as_mut() { - match self.model.prefill_reuse_accelerated( - state, - prompt, - accelerator.as_mut(), - self.accelerate_from, - progress, - ) { + let accelerate = leleka_gptoss::PrefillOffload { + accelerator: accelerator.as_mut(), + min_tokens: self.accelerate_from, + }; + match self.model.prefill_reuse_accelerated(state, prompt, accelerate, progress) { Ok(done) => return Ok(done.map(|r| r.reused)), Err(e) => { eprintln!( diff --git a/crates/cuda-driver/src/experimental_gpu_smoke.rs b/crates/cuda-driver/src/experimental_gpu_smoke.rs index d1e90f01..229b74f6 100644 --- a/crates/cuda-driver/src/experimental_gpu_smoke.rs +++ b/crates/cuda-driver/src/experimental_gpu_smoke.rs @@ -124,7 +124,7 @@ fn matching_model( let mut m = PoolSet::new(KvFormat::Q4_0, q, p.shape.rows(p.pages)).unwrap(); for (pos, kc, vc) in cells { let target = PoolTarget { pools: &mut m, host: None }; - let at = CellAt { table, pos: i64::from(*pos), shapes: q }; + let at = CellAt { page_table: table, position: i64::from(*pos), shapes: q }; append_cell(KvFormat::Q4_0, target, at, CellKv { k: kc, v: vc }, c).unwrap(); } if m.k_q4 == got.0 && m.v_q4 == got.1 { @@ -313,8 +313,8 @@ fn assert_resolved_like_cpu( leleka_experimental_ref::kv_stream::ResolveBatch { ids: inputs.0, steps: inputs.1, - n_q: STREAM_QUERIES as usize, - cap: STREAM_CAP as usize, + query_count: STREAM_QUERIES as usize, + capacity: STREAM_CAP as usize, page_size: 4, }, &leleka_experimental_ref::kv_stream::MissOrder::Canonical, diff --git a/crates/experimental-ref/src/attn.rs b/crates/experimental-ref/src/attn.rs index f4b3893d..6d52be16 100644 --- a/crates/experimental-ref/src/attn.rs +++ b/crates/experimental-ref/src/attn.rs @@ -31,37 +31,44 @@ pub const SCALE: f32 = 0.0625; /// The head counts and the number of attended cells of one reference attention. #[derive(Clone, Copy, Debug)] -pub struct AttnShape { - pub n_head: usize, - pub n_head_kv: usize, - pub n_ids: usize, +pub struct ReferenceAttentionShape { + pub head_count: usize, + pub kv_head_count: usize, + pub attended_count: usize, } -/// Softmax GQA attention in f64. `q` is `[n_head][256]`; `k` and `v` are `[n_ids][n_head_kv][256]` -/// (dequantized, already in the domain the kernel sees); `n_ids` cells are attended. Returns `[n_head][256]`. -pub fn reference(q: &[f32], k: &[f32], v: &[f32], AttnShape { n_head, n_head_kv, n_ids }: AttnShape) -> Vec { - assert_eq!(n_head % n_head_kv, 0); - assert_eq!(q.len(), n_head * HD); - assert_eq!(k.len(), n_ids * n_head_kv * HD); +/// The scaled dot products of one query head with the keys of `kv_head` over every attended cell, in f64. +fn head_scores(query_head: &[f32], keys: &[f32], kv_head_count: usize, kv_head: usize) -> Vec { + keys.chunks_exact(kv_head_count * HD) + .map(|cell| { + let key = &cell[kv_head * HD..][..HD]; + query_head.iter().zip(key).map(|(a, b)| f64::from(*a) * f64::from(*b)).sum::() * f64::from(SCALE) + }) + .collect() +} + +/// Softmax GQA attention in f64. `q` is `[head_count][256]`; `k` and `v` are +/// `[attended_count][kv_head_count][256]` (dequantized, already in the domain the kernel sees). Returns +/// `[head_count][256]`. +pub fn reference(q: &[f32], k: &[f32], v: &[f32], shape: ReferenceAttentionShape) -> Vec { + let ReferenceAttentionShape { head_count, kv_head_count, attended_count } = shape; + assert_eq!(head_count % kv_head_count, 0); + assert_eq!(q.len(), head_count * HD); + assert_eq!(k.len(), attended_count * kv_head_count * HD); assert_eq!(v.len(), k.len()); - let group = n_head / n_head_kv; - let mut out = vec![0f64; n_head * HD]; - if n_ids == 0 { + let group = head_count / kv_head_count; + let mut out = vec![0f64; head_count * HD]; + if attended_count == 0 { return out; } - for h in 0..n_head { + for h in 0..head_count { let kvh = h / group; - let mut scores = vec![0f64; n_ids]; - for (j, sc) in scores.iter_mut().enumerate() { - let kr = &k[(j * n_head_kv + kvh) * HD..][..HD]; - let qr = &q[h * HD..][..HD]; - *sc = qr.iter().zip(kr).map(|(a, b)| f64::from(*a) * f64::from(*b)).sum::() * f64::from(SCALE); - } + let scores = head_scores(&q[h * HD..][..HD], k, kv_head_count, kvh); let max = scores.iter().cloned().fold(f64::NEG_INFINITY, f64::max); let weights: Vec = scores.iter().map(|s| (s - max).exp()).collect(); let total: f64 = weights.iter().sum(); for (j, w) in weights.iter().enumerate() { - let vr = &v[(j * n_head_kv + kvh) * HD..][..HD]; + let vr = &v[(j * kv_head_count + kvh) * HD..][..HD]; for d in 0..HD { out[h * HD + d] += w / total * f64::from(vr[d]); } @@ -104,7 +111,8 @@ mod tests { for j in 0..n { v[j * HD] = (j + 1) as f32; // 1, 2, 3 } - let out = reference(&q, &k, &v, AttnShape { n_head: nh, n_head_kv: nkv, n_ids: n }); + let shape = ReferenceAttentionShape { head_count: nh, kv_head_count: nkv, attended_count: n }; + let out = reference(&q, &k, &v, shape); assert!((out[0] - 2.0).abs() < 1e-12 && (out[HD] - 2.0).abs() < 1e-12); } @@ -118,7 +126,8 @@ mod tests { let mut v = vec![0.0f32; n * HD]; v[0] = 5.0; v[HD] = -7.0; - let out = reference(&q, &k, &v, AttnShape { n_head: nh, n_head_kv: nkv, n_ids: n }); + let shape = ReferenceAttentionShape { head_count: nh, kv_head_count: nkv, attended_count: n }; + let out = reference(&q, &k, &v, shape); assert!((out[0] - 5.0).abs() < 1e-3); } } diff --git a/crates/experimental-ref/src/cache.rs b/crates/experimental-ref/src/cache.rs index ddfb064b..b075af6d 100644 --- a/crates/experimental-ref/src/cache.rs +++ b/crates/experimental-ref/src/cache.rs @@ -118,16 +118,17 @@ fn write_q4(pool: &mut [u8], row: u64, b: usize, blk: &q4_0::BlockQ4_0, blocks_p pub struct Q8Slabs<'a> { codes: &'a mut [u8], scales: &'a mut [u8], - hd: usize, + head_dim: usize, } impl<'a> Q8Slabs<'a> { + /// The code and scale arrays of one half, strided by the head dimension of `s`. pub fn new(codes: &'a mut [u8], scales: &'a mut [u8], s: &QsaShapes) -> Self { - Self { codes, scales, hd: s.head_dim as usize } + Self { codes, scales, head_dim: s.head_dim as usize } } fn write(&mut self, row: u64, g: usize, group: &[i8; KV_Q8_GROUP], sbits: u16) { - let hd = self.hd; + let hd = self.head_dim; let at = row as usize * hd + g * KV_Q8_GROUP; for (i, c) in group.iter().enumerate() { self.codes[at + i] = *c as u8; @@ -140,8 +141,8 @@ impl<'a> Q8Slabs<'a> { /// Where one cell append lands: the page table, the cell position and the pool geometry. #[derive(Clone, Copy)] pub struct CellAt<'a> { - pub table: &'a [i32], - pub pos: i64, + pub page_table: &'a [i32], + pub position: i64, pub shapes: &'a QsaShapes, } @@ -182,7 +183,7 @@ pub fn append_q4_half( x: &[f32], c: Contraction, ) -> Result<(), CacheError> { - let CellAt { table, pos, shapes: s } = at; + let CellAt { page_table: table, position: pos, shapes: s } = at; let (hd, kvh, ps) = (s.head_dim as usize, s.n_head_kv as u64, s.page_size); if hd != 256 || x.len() != kvh as usize * hd { return Err(CacheError::Geometry); @@ -208,7 +209,7 @@ pub fn append_q4_half( /// `kv_append_q8_kernel` for one cell and one half. `k_q`/`k_scale` of a value-only cache are simply never /// passed (the Original passes null pointers and launches z = 1 only). pub fn append_q8_half(mut slabs: Q8Slabs, host: Option, at: CellAt, x: &[f32]) -> Result<(), CacheError> { - let CellAt { table, pos, shapes: s } = at; + let CellAt { page_table: table, position: pos, shapes: s } = at; let (hd, kvh, ps) = (s.head_dim as usize, s.n_head_kv as u64, s.page_size); if hd % KV_Q8_GROUP != 0 || x.len() != kvh as usize * hd { return Err(CacheError::Geometry); diff --git a/crates/experimental-ref/src/cache/tests.rs b/crates/experimental-ref/src/cache/tests.rs index be8baee2..90c98f6e 100644 --- a/crates/experimental-ref/src/cache/tests.rs +++ b/crates/experimental-ref/src/cache/tests.rs @@ -35,7 +35,7 @@ fn q4_round_trip_stays_within_half_a_step_in_the_rotated_domain() { append_cell( KvFormat::Q4_0, target, - CellAt { table: &table, pos: 5, shapes: &S }, + CellAt { page_table: &table, position: 5, shapes: &S }, CellKv { k: &k, v: &v }, Contraction::Separate, ) @@ -64,7 +64,7 @@ fn streaming_write_rule_host_always_vram_only_when_resident() { let v = cell(4, 2.0); for pos in 0..16 { let target = PoolTarget { pools: &mut pools, host: Some(&mut host) }; - let at = CellAt { table: &table, pos, shapes: &S }; + let at = CellAt { page_table: &table, position: pos, shapes: &S }; append_cell(KvFormat::Int8, target, at, CellKv { k: &k, v: &v }, Contraction::Fused).unwrap(); } assert!(host.k_q.iter().any(|b| *b != 0)); @@ -89,7 +89,7 @@ fn k8v4_composition_writes_int8_k_and_q4_v_only() { append_cell( KvFormat::K8V4, target, - CellAt { table: &table, pos: 0, shapes: &S }, + CellAt { page_table: &table, position: 0, shapes: &S }, CellKv { k: &k, v: &v }, Contraction::Fused, ) @@ -109,7 +109,7 @@ fn fp16_is_refused_and_geometry_is_checked() { bad.head_dim = 128; let mut p = PoolSet::new(KvFormat::Q4_0, &S, 8).unwrap(); let target = PoolTarget { pools: &mut p, host: None }; - let at = CellAt { table: &[0, 1], pos: 0, shapes: &bad }; + let at = CellAt { page_table: &[0, 1], position: 0, shapes: &bad }; let kv = CellKv { k: &[0.0; 256], v: &[0.0; 256] }; assert_eq!(append_cell(KvFormat::Q4_0, target, at, kv, Contraction::Fused), Err(CacheError::Geometry)); } diff --git a/crates/experimental-ref/src/cvec/load_control_vectors.rs b/crates/experimental-ref/src/cvec/load_control_vectors.rs index 4222a2c6..721d0983 100644 --- a/crates/experimental-ref/src/cvec/load_control_vectors.rs +++ b/crates/experimental-ref/src/cvec/load_control_vectors.rs @@ -262,9 +262,9 @@ fn block_dot(dots: &[f32; THREADS]) -> f32 { /// The residual rows of one `cvec_apply` batch: `t_count` rows of `r_ld` floats. pub struct CvecRows<'a> { - pub r: &'a mut [f32], - pub t_count: usize, - pub r_ld: usize, + pub residual: &'a mut [f32], + pub row_count: usize, + pub row_stride: usize, } /// One `cvec_apply` over a batch: `R` is `T` rows of `r_ld` floats, each holding `hc` streams of `n`. With @@ -278,7 +278,7 @@ pub fn apply( layer: usize, pending: Option<(&[f32], usize, &[f32], usize)>, ) { - let CvecRows { r, t_count, r_ld } = rows; + let CvecRows { residual: r, row_count: t_count, row_stride: r_ld } = rows; let (n, hc) = (tables.n_embd as usize, tables.hc as usize); let write = pending.is_some(); let s = tables.s[layer]; diff --git a/crates/experimental-ref/src/cvec/tests.rs b/crates/experimental-ref/src/cvec/tests.rs index 9a121a3c..cbf5f96b 100644 --- a/crates/experimental-ref/src/cvec/tests.rs +++ b/crates/experimental-ref/src/cvec/tests.rs @@ -139,13 +139,14 @@ fn rejections() { /// The size of a test table: `l` layers of `n` values, `hc` streams, the steered layer `layer`. #[derive(Clone, Copy)] struct TableShape { - n: usize, - hc: usize, - layer: usize, - l: usize, + embedding_width: usize, + stream_count: usize, + steered_layer: usize, + layer_count: usize, } -fn tables(mode: CvecMode, TableShape { n, hc, layer, l }: TableShape, scale: f32) -> CvecTables { +fn tables(mode: CvecMode, shape: TableShape, scale: f32) -> CvecTables { + let TableShape { embedding_width: n, stream_count: hc, steered_layer: layer, layer_count: l } = shape; let mut dir = vec![0.0f32; l * n]; let mut s = vec![0.0f32; l]; let v = vec_of(n, 3.0); @@ -163,17 +164,8 @@ fn tables(mode: CvecMode, TableShape { n, hc, layer, l }: TableShape, scale: f32 } } let steered = s.iter().map(|x| *x != 0.0).collect(); - CvecTables { - dir, - s, - mode, - first: 1, - last: l as i64 - 1, - n_embd: n as i64, - hc: hc as i64, - steered, - summary: String::new(), - } + let (last, n_embd, hc) = (l as i64 - 1, n as i64, hc as i64); + CvecTables { dir, s, mode, first: 1, last, n_embd, hc, steered, summary: String::new() } } #[test] @@ -181,24 +173,25 @@ fn project_removes_the_component_and_add_adds() { let (n, hc, t_count) = (600usize, 3usize, 2usize); let r_ld = hc * n; let r0: Vec = (0..t_count * r_ld).map(|i| ((i * 7 % 13) as f32 - 6.0) * 0.3).collect(); - let tp = tables(CvecMode::Project, TableShape { n, hc, layer: 2, l: 4 }, 1.0); + let shape = TableShape { embedding_width: n, stream_count: hc, steered_layer: 2, layer_count: 4 }; + let tp = tables(CvecMode::Project, shape, 1.0); assert_projection_removes_the_component(&tp, &r0, (n, hc, t_count)); // off: unchanged let mut r = r0.clone(); - apply(CvecRows { r: &mut r, t_count, r_ld }, &tp, false, 2, None); + apply(CvecRows { residual: &mut r, row_count: t_count, row_stride: r_ld }, &tp, false, 2, None); assert_eq!(r, r0); // a layer without a direction is untouched - apply(CvecRows { r: &mut r, t_count, r_ld }, &tp, true, 1, None); + apply(CvecRows { residual: &mut r, row_count: t_count, row_stride: r_ld }, &tp, true, 1, None); assert_eq!(r, r0); // add - let ta = tables(CvecMode::Add, TableShape { n, hc, layer: 2, l: 4 }, 1.0); + let ta = tables(CvecMode::Add, shape, 1.0); assert_add_adds_the_direction(&ta, &r0, (n, hc, t_count)); } fn assert_projection_removes_the_component(tp: &CvecTables, r0: &[f32], (n, hc, t_count): (usize, usize, usize)) { let r_ld = hc * n; let mut r = r0.to_vec(); - apply(CvecRows { r: &mut r, t_count, r_ld }, tp, true, 2, None); + apply(CvecRows { residual: &mut r, row_count: t_count, row_stride: r_ld }, tp, true, 2, None); for t in 0..t_count { for c in 0..hc { let after: f64 = (0..n) @@ -212,7 +205,7 @@ fn assert_projection_removes_the_component(tp: &CvecTables, r0: &[f32], (n, hc, fn assert_add_adds_the_direction(ta: &CvecTables, r0: &[f32], (n, hc, t_count): (usize, usize, usize)) { let r_ld = hc * n; let mut r = r0.to_vec(); - apply(CvecRows { r: &mut r, t_count, r_ld }, ta, true, 2, None); + apply(CvecRows { residual: &mut r, row_count: t_count, row_stride: r_ld }, ta, true, 2, None); for t in 0..t_count { for c in 0..hc { for j in 0..n { @@ -228,9 +221,10 @@ fn pending_write_is_applied_even_when_the_vector_is_off() { let r0: Vec = (0..hc * n).map(|i| (i % 11) as f32 * 0.1).collect(); let bo: Vec = (0..n).map(|i| (i % 5) as f32 - 2.0).collect(); let inj = vec![0.5f32, -1.0]; - let tp = tables(CvecMode::Project, TableShape { n, hc, layer: 2, l: 4 }, 1.0); + let shape = TableShape { embedding_width: n, stream_count: hc, steered_layer: 2, layer_count: 4 }; + let tp = tables(CvecMode::Project, shape, 1.0); let mut r = r0.clone(); - apply(CvecRows { r: &mut r, t_count: 1, r_ld: hc * n }, &tp, false, 2, Some((&bo, n, &inj, hc))); + apply(CvecRows { residual: &mut r, row_count: 1, row_stride: hc * n }, &tp, false, 2, Some((&bo, n, &inj, hc))); for c in 0..hc { let w = 2.0 * sigmoid(inj[c] / hc as f32); for j in 0..n { diff --git a/crates/experimental-ref/src/kv_stream.rs b/crates/experimental-ref/src/kv_stream.rs index 040b6fb1..39ce41d5 100644 --- a/crates/experimental-ref/src/kv_stream.rs +++ b/crates/experimental-ref/src/kv_stream.rs @@ -90,17 +90,17 @@ pub enum MissOrder { pub struct ResolveBatch<'a> { pub ids: &'a [i32], pub steps: &'a [i32], - pub n_q: usize, - pub cap: usize, + pub query_count: usize, + pub capacity: usize, pub page_size: i32, } /// The blocks `[b0, b1)` a ring restore copies, and the ring's slot count. #[derive(Clone, Copy, Debug)] pub struct RingSpan { - pub b0: usize, - pub b1: usize, - pub n_slots: usize, + pub first_block: usize, + pub end_block: usize, + pub slot_count: usize, } #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -141,6 +141,6 @@ mod tests; mod map_bytes; #[allow(unused_imports)] pub use map_bytes::*; -mod impl_streammap; +mod residency_map; #[allow(unused_imports)] -pub use impl_streammap::*; +pub use residency_map::*; diff --git a/crates/experimental-ref/src/kv_stream/impl_streammap.rs b/crates/experimental-ref/src/kv_stream/residency_map.rs similarity index 98% rename from crates/experimental-ref/src/kv_stream/impl_streammap.rs rename to crates/experimental-ref/src/kv_stream/residency_map.rs index 332f51ef..21d3f636 100644 --- a/crates/experimental-ref/src/kv_stream/impl_streammap.rs +++ b/crates/experimental-ref/src/kv_stream/residency_map.rs @@ -78,7 +78,7 @@ impl StreamMap { /// Step 1: hits take this epoch and their reference bit; a missing block is claimed exactly once (-1 -> -2). /// Returns the number of lookups and the claimed blocks in lookup order. fn claim_misses(&mut self, batch: &ResolveBatch, epoch: i32) -> Result<(usize, Vec), StreamError> { - let ResolveBatch { ids, steps, n_q, cap, page_size } = *batch; + let ResolveBatch { ids, steps, query_count: n_q, capacity: cap, page_size } = *batch; let mut lookups = 0usize; let mut misses: Vec = Vec::new(); for q in 0..n_q { @@ -217,7 +217,7 @@ pub fn ring_table(n_blocks: usize, n_slots: usize) -> Vec { /// `kv_ring_restore`: blocks `[b0, b1)` of the host copy into the ring slots `b % n_slots`, in runs up to the /// ring's end (the Original issues one copy per run per array). pub fn ring_restore(slots: &mut PoolSet, host: &PoolSet, s: &QsaShapes, fmt: StreamFormat, span: RingSpan) { - let RingSpan { b0, b1, n_slots } = span; + let RingSpan { first_block: b0, end_block: b1, slot_count: n_slots } = span; for (name, len) in stream_runs(s, fmt) { let len = len as usize; let src = host.array(name).expect("host array"); diff --git a/crates/experimental-ref/src/kv_stream/tests.rs b/crates/experimental-ref/src/kv_stream/tests.rs index 67063651..3f91a56d 100644 --- a/crates/experimental-ref/src/kv_stream/tests.rs +++ b/crates/experimental-ref/src/kv_stream/tests.rs @@ -4,8 +4,9 @@ use super::*; const S: QsaShapes = QsaShapes::real(); -fn batch<'a>(ids: &'a [i32], steps: &'a [i32], n_q: usize, cap: usize) -> ResolveBatch<'a> { - ResolveBatch { ids, steps, n_q, cap, page_size: 4 } +/// A resolve call of `query_count` queries of width `capacity` over four-cell blocks. +fn resolve_batch<'a>(ids: &'a [i32], steps: &'a [i32], query_count: usize, capacity: usize) -> ResolveBatch<'a> { + ResolveBatch { ids, steps, query_count, capacity, page_size: 4 } } #[test] @@ -71,7 +72,7 @@ fn run_calls(map: &mut StreamMap, calls: usize, nb: usize, n_q: usize) { steps.extend_from_slice(&[0, 0, 0, sel.len() as i32]); ids.extend_from_slice(&sel); } - let report = map.resolve(batch(&ids, &steps, n_q, cap), &MissOrder::Canonical).unwrap(); + let report = map.resolve(resolve_batch(&ids, &steps, n_q, cap), &MissOrder::Canonical).unwrap(); assert_eq!(report.placed, report.misses); assert!(map.is_consistent()); // every selected block is resident after the call @@ -96,9 +97,9 @@ fn eviction_keeps_the_map_consistent_and_counters_add_up() { // a repeated call is all hits let ids: Vec = (0..40).collect(); let steps = [0, 0, 0, 40]; - map.resolve(batch(&ids, &steps, 1, 40), &MissOrder::Canonical).unwrap(); + map.resolve(resolve_batch(&ids, &steps, 1, 40), &MissOrder::Canonical).unwrap(); let before = map.counters().misses; - let r = map.resolve(batch(&ids, &steps, 1, 40), &MissOrder::Canonical).unwrap(); + let r = map.resolve(resolve_batch(&ids, &steps, 1, 40), &MissOrder::Canonical).unwrap(); assert_eq!(r.misses, 0); assert_eq!(map.counters().misses, before); } @@ -111,14 +112,14 @@ fn a_slot_used_by_the_call_is_never_a_victim() { let first = chunk * 40; let ids: Vec = (first * 4..(first + 40) * 4).collect(); let steps = [0, 0, 0, ids.len() as i32]; - map.resolve(batch(&ids, &steps, 1, ids.len()), &MissOrder::Canonical).unwrap(); + map.resolve(resolve_batch(&ids, &steps, 1, ids.len()), &MissOrder::Canonical).unwrap(); } assert_eq!(map.resident_blocks(), 1030); // one call that hits 40 resident blocks and misses 40 new ones: no hit block may be evicted let mut ids: Vec = (100..140).flat_map(|b| (0..4).map(move |i| b * 4 + i)).collect(); ids.extend((2000..2040).flat_map(|b| (0..4).map(move |i| b * 4 + i))); let steps = [0, 0, 0, ids.len() as i32]; - map.resolve(batch(&ids, &steps, 1, ids.len()), &MissOrder::Canonical).unwrap(); + map.resolve(resolve_batch(&ids, &steps, 1, ids.len()), &MissOrder::Canonical).unwrap(); for b in 100..140 { assert!(map.page_table[b] >= 0, "hit block {b} was evicted"); } @@ -136,8 +137,8 @@ fn observed_miss_order_changes_only_the_pairing_not_the_victim_set() { let steps = [0, 0, 0, sorted.len() as i32]; let mut a = StreamMap::new(600, 1030); let mut b = a.clone(); - a.resolve(batch(&sorted, &steps, 1, sorted.len()), &MissOrder::Canonical).unwrap(); - b.resolve(batch(&sorted, &steps, 1, sorted.len()), &MissOrder::Observed(vec![500, 9, 3, 7])).unwrap(); + a.resolve(resolve_batch(&sorted, &steps, 1, sorted.len()), &MissOrder::Canonical).unwrap(); + b.resolve(resolve_batch(&sorted, &steps, 1, sorted.len()), &MissOrder::Observed(vec![500, 9, 3, 7])).unwrap(); let mut sa = a.miss_slot[..4].to_vec(); let mut sb = b.miss_slot[..4].to_vec(); sa.sort_unstable(); @@ -146,7 +147,7 @@ fn observed_miss_order_changes_only_the_pairing_not_the_victim_set() { assert_ne!(a.page_table, b.page_table); assert!(a.is_consistent() && b.is_consistent()); assert_eq!( - a.resolve(batch(&sorted, &steps, 1, sorted.len()), &MissOrder::Observed(vec![1, 2, 3, 4])), + a.resolve(resolve_batch(&sorted, &steps, 1, sorted.len()), &MissOrder::Observed(vec![1, 2, 3, 4])), Err(StreamError::BadMissOrder) ); } @@ -156,7 +157,8 @@ fn too_many_distinct_blocks_for_the_slots_is_refused() { let mut map = StreamMap::new(5000, 1024); let ids: Vec = (0..1025 * 4).collect(); let steps = [0, 0, 0, ids.len() as i32]; - assert_eq!(map.resolve(batch(&ids, &steps, 1, ids.len()), &MissOrder::Canonical), Err(StreamError::CallTooLarge)); + let refused = map.resolve(resolve_batch(&ids, &steps, 1, ids.len()), &MissOrder::Canonical); + assert_eq!(refused, Err(StreamError::CallTooLarge)); } #[test] @@ -172,7 +174,7 @@ fn ring_table_and_restore() { *b = (i % 13) as u8; } let mut ring = PoolSet::new(KvFormat::Int8, &S, 4 * S.rows_per_page()).unwrap(); - ring_restore(&mut ring, &host, &S, StreamFormat::Int8, RingSpan { b0: 6, b1: 10, n_slots: 4 }); + ring_restore(&mut ring, &host, &S, StreamFormat::Int8, RingSpan { first_block: 6, end_block: 10, slot_count: 4 }); let len = 2048; // k_q bytes of a block for b in 6..10 { let sl = b % 4; diff --git a/crates/experimental-ref/src/remote_experts.rs b/crates/experimental-ref/src/remote_experts.rs index 1ce5f439..2455af3c 100644 --- a/crates/experimental-ref/src/remote_experts.rs +++ b/crates/experimental-ref/src/remote_experts.rs @@ -127,9 +127,9 @@ impl RemotePlan { } } -/// The helper device of `plan_open`: its index, the visible device count and its free memory. +/// The remote device of `plan_open`: its index, the visible device count and its free memory. #[derive(Clone, Copy, Debug)] -pub struct HelperDevice { +pub struct RemoteDevice { pub device: i32, pub device_count: i32, pub free_bytes: u64, @@ -154,12 +154,12 @@ pub struct Candidates<'a> { /// Everything `RemoteExperts::open` decides before it touches the helper device (`preflight` and the checks of /// `open`). On success `claimed` marks the helper's experts (only then: a failed open leaves it untouched). pub fn plan_open( - helper: HelperDevice, + helper: RemoteDevice, shape: OpenShape, candidates: Candidates, sizes: &ExpertSizes, ) -> Result { - let HelperDevice { device, device_count, free_bytes } = helper; + let RemoteDevice { device, device_count, free_bytes } = helper; let OpenShape { slots, layers, experts } = shape; let Candidates { ranked, primary_has, claimed } = candidates; if !valid_open_arguments((device, device_count), (slots, layers, experts), ranked.len(), claimed.len()) { @@ -313,8 +313,8 @@ impl Dispatch { /// The routing width of a dispatch: `n_tok` tokens of `k` routed experts each. #[derive(Clone, Copy, Debug)] pub struct RouteShape { - pub n_tok: i64, - pub k: i64, + pub token_count: i64, + pub experts_per_token: i64, } /// What the primary verifier knows: `kind` is its classification (-1 = CPU candidate, null on the one-token @@ -333,7 +333,7 @@ pub fn dispatch( route: RouteShape, primary: PrimaryView, ) -> Result { - let RouteShape { n_tok, k } = route; + let RouteShape { token_count: n_tok, experts_per_token: k } = route; let (kind, primary_res) = (primary.kind, primary.res); let n = dispatch_entries(plan, layer, (n_tok, k))?; let mut d = Dispatch::empty(n); diff --git a/crates/experimental-ref/src/remote_experts/tests.rs b/crates/experimental-ref/src/remote_experts/tests.rs index 960e7900..44a881ff 100644 --- a/crates/experimental-ref/src/remote_experts/tests.rs +++ b/crates/experimental-ref/src/remote_experts/tests.rs @@ -2,15 +2,18 @@ use super::*; -fn dev(device: i32, device_count: i32, free_bytes: u64) -> HelperDevice { - HelperDevice { device, device_count, free_bytes } +/// The remote device of a test: its index, the visible device count and its free memory. +fn remote_device(device: i32, device_count: i32, free_bytes: u64) -> RemoteDevice { + RemoteDevice { device, device_count, free_bytes } } -fn shape(slots: i32, layers: i64, experts: i64) -> OpenShape { +/// The slot count and table size of a test tier. +fn open_shape(slots: i32, layers: i64, experts: i64) -> OpenShape { OpenShape { slots, layers, experts } } -fn cand<'a>( +/// The ranked experts, the primary's residency test and the claim table of a test tier. +fn candidates<'a>( ranked: &'a [(i32, i32)], primary_has: &'a dyn Fn(i32, i32) -> bool, claimed: &'a mut [u8], @@ -18,10 +21,12 @@ fn cand<'a>( Candidates { ranked, primary_has, claimed } } -fn route(n_tok: i64, k: i64) -> RouteShape { - RouteShape { n_tok, k } +/// The routing width of a test dispatch. +fn route_shape(token_count: i64, experts_per_token: i64) -> RouteShape { + RouteShape { token_count, experts_per_token } } +/// A primary verifier that knows nothing: every routed expert is a candidate for the helper. const NO_PRIMARY: PrimaryView<'static> = PrimaryView { kind: None, res: None }; fn canonical() -> ExpertSizes { @@ -45,7 +50,12 @@ fn selection_skips_primary_claimed_duplicates_and_out_of_range() { claimed[2 * 8 + 3] = 1; // (2,3) taken by another tier let primary = |l: i32, e: i32| (l, e) == (1, 2); let sizes = canonical(); - let plan = plan_open(dev(1, 2, 24 << 30), shape(3, 4, 8), cand(&ranked, &primary, &mut claimed), &sizes).unwrap(); + let plan = plan_open( + remote_device(1, 2, 24 << 30), + open_shape(3, 4, 8), + candidates(&ranked, &primary, &mut claimed), + &sizes, + ).unwrap(); assert_eq!(plan.selected, [(0, 1), (1, 5), (3, 3)]); assert_eq!(plan.slot_of(1, 5), 1); assert_eq!(plan.slot_of(1, 2), -1); @@ -73,29 +83,35 @@ fn open_failures_leave_claimed_untouched() { // the boundary is inclusive let none = |_: i32, _: i32| false; let need = 2 * 1_382_400 + RESERVE_BYTES; - assert!(plan_open(dev(1, 2, need), shape(2, 4, 8), cand(&[(0, 0), (0, 1)], &none, &mut claimed), &sizes).is_ok()); + let ranked = [(0, 0), (0, 1)]; + let candidates = candidates(&ranked, &none, &mut claimed); + assert!(plan_open(remote_device(1, 2, need), open_shape(2, 4, 8), candidates, &sizes).is_ok()); } fn assert_bad_arguments_refused(claimed: &mut [u8], sizes: &ExpertSizes) { let none = |_: i32, _: i32| false; let bad = Err(RemoteError::BadArguments); - assert_eq!(plan_open(dev(0, 2, 1 << 40), shape(2, 4, 8), cand(&[(0, 0)], &none, claimed), sizes), bad); - assert_eq!(plan_open(dev(2, 2, 1 << 40), shape(2, 4, 8), cand(&[(0, 0)], &none, claimed), sizes), bad); - assert_eq!(plan_open(dev(1, 2, 1 << 40), shape(0, 4, 8), cand(&[(0, 0)], &none, claimed), sizes), bad); - assert_eq!(plan_open(dev(1, 2, 1 << 40), shape(2, 4, 8), cand(&[], &none, claimed), sizes), bad); - assert_eq!(plan_open(dev(1, 2, 1 << 40), shape(2, 4, 7), cand(&[(0, 0)], &none, claimed), sizes), bad); + let mut open = |device: RemoteDevice, size: OpenShape, ranked: &[(i32, i32)]| { + plan_open(device, size, candidates(ranked, &none, claimed), sizes) + }; + assert_eq!(open(remote_device(0, 2, 1 << 40), open_shape(2, 4, 8), &[(0, 0)]), bad); + assert_eq!(open(remote_device(2, 2, 1 << 40), open_shape(2, 4, 8), &[(0, 0)]), bad); + assert_eq!(open(remote_device(1, 2, 1 << 40), open_shape(0, 4, 8), &[(0, 0)]), bad); + assert_eq!(open(remote_device(1, 2, 1 << 40), open_shape(2, 4, 8), &[]), bad); + assert_eq!(open(remote_device(1, 2, 1 << 40), open_shape(2, 4, 7), &[(0, 0)]), bad); } fn assert_resource_failures(claimed: &mut [u8], sizes: &ExpertSizes) { let none = |_: i32, _: i32| false; let all = |_: i32, _: i32| true; + let plan = candidates(&[(0, 0)], &all, claimed); assert_eq!( - plan_open(dev(1, 2, 1 << 40), shape(2, 4, 8), cand(&[(0, 0)], &all, claimed), sizes), + plan_open(remote_device(1, 2, 1 << 40), open_shape(2, 4, 8), plan, sizes), Err(RemoteError::NoUnclaimedExperts) ); // 2 slots of 1.38 MB plus 512 MiB do not fit in 512 MiB - let e = - plan_open(dev(1, 2, 512 << 20), shape(2, 4, 8), cand(&[(0, 0), (0, 1)], &none, claimed), sizes).unwrap_err(); + let two = candidates(&[(0, 0), (0, 1)], &none, claimed); + let e = plan_open(remote_device(1, 2, 512 << 20), open_shape(2, 4, 8), two, sizes).unwrap_err(); assert!(matches!(e, RemoteError::SlotsLeaveLessThanReserve { .. })); assert_eq!( e.message(1), @@ -110,9 +126,9 @@ fn native_packs_round_slots_up_to_256_and_keep_each_layers_size() { assert_eq!(sizes.slot_cost(1), 1280); let mut claimed = vec![0u8; 4 * 2]; let none = |_: i32, _: i32| false; - let plan = - plan_open(dev(1, 2, 1 << 30), shape(3, 4, 2), cand(&[(1, 0), (3, 1), (0, 0)], &none, &mut claimed), &sizes) - .unwrap(); + let ranked = [(1, 0), (3, 1), (0, 0)]; + let candidates = candidates(&ranked, &none, &mut claimed); + let plan = plan_open(remote_device(1, 2, 1 << 30), open_shape(3, 4, 2), candidates, &sizes).unwrap(); assert_eq!(plan.slot_sizes, [1025, 513, 1000]); assert_eq!(plan.needed_bytes, 1280 + 768 + 1024); } @@ -122,9 +138,9 @@ fn plan_for_dispatch() -> RemotePlan { let none = |_: i32, _: i32| false; // layer 1 holds experts 4, 9, 2 (slots 0, 1, 2); layer 0 holds expert 7 (slot 3) plan_open( - dev(1, 2, 1 << 40), - shape(4, 3, 16), - cand(&[(1, 4), (1, 9), (1, 2), (0, 7)], &none, &mut claimed), + remote_device(1, 2, 1 << 40), + open_shape(4, 3, 16), + candidates(&[(1, 4), (1, 9), (1, 2), (0, 7)], &none, &mut claimed), &canonical(), ) .unwrap() @@ -137,7 +153,7 @@ fn dispatch_groups_by_expert_in_first_appearance_order() { let mut ids = vec![0i32; 20]; ids[..10].copy_from_slice(&[4, 3, 9, 5, 6, 8, 10, 11, 12, 13]); ids[10..].copy_from_slice(&[9, 4, 1, 2, 0, 3, 5, 6, 7, 8]); - let d = dispatch(&plan, 1, &ids, route(2, 10), NO_PRIMARY).unwrap(); + let d = dispatch(&plan, 1, &ids, route_shape(2, 10), NO_PRIMARY).unwrap(); assert_eq!(d.groups, [Group { expert: 4, slot: 0 }, Group { expert: 9, slot: 1 }, Group { expert: 2, slot: 2 }]); assert_eq!(d.start, [0, 2, 4, 5]); assert_eq!(d.original_row, [0, 11, 2, 10, 13]); @@ -155,19 +171,19 @@ fn dispatch_respects_kind_primary_residency_and_missing_layers() { let ids: Vec = vec![4, 9, 2, 0, 1, 3, 5, 6, 8, 10]; let mut kind = vec![-1i32; 10]; kind[1] = 2; // expert 9 was already served on the primary - let d = dispatch(&plan, 1, &ids, route(1, 10), PrimaryView { kind: Some(&kind), res: None }).unwrap(); + let d = dispatch(&plan, 1, &ids, route_shape(1, 10), PrimaryView { kind: Some(&kind), res: None }).unwrap(); assert_eq!(d.original_row, [0, 2]); // the primary holds expert 4 of layer 1 let mut res = vec![-1i32; 3 * 16]; res[16 + 4] = 5; - let d = dispatch(&plan, 1, &ids, route(1, 10), PrimaryView { kind: None, res: Some(&res) }).unwrap(); + let d = dispatch(&plan, 1, &ids, route_shape(1, 10), PrimaryView { kind: None, res: Some(&res) }).unwrap(); assert_eq!(d.original_row, [1, 2]); // a layer the helper holds nothing of - let d = dispatch(&plan, 2, &ids, route(1, 10), NO_PRIMARY).unwrap(); + let d = dispatch(&plan, 2, &ids, route_shape(1, 10), NO_PRIMARY).unwrap(); assert!(d.is_empty() && d.owned.iter().all(|o| *o == 0)); assert!(d.start.is_empty()); // out-of-range experts are ignored - let d = dispatch(&plan, 1, &[-3, 99, 4, 4, 4, 4, 4, 4, 4, 4], route(1, 10), NO_PRIMARY).unwrap(); + let d = dispatch(&plan, 1, &[-3, 99, 4, 4, 4, 4, 4, 4, 4, 4], route_shape(1, 10), NO_PRIMARY).unwrap(); assert_eq!(d.groups.len(), 1); assert_eq!(d.original_row.len(), 8); } @@ -178,19 +194,19 @@ fn dispatch_validation() { let ids = vec![0i32; 100]; for (layer, n_tok, k) in [(1, 0, 10), (1, 9, 10), (1, 1, 9), (-1, 1, 10), (3, 1, 10)] { assert_eq!( - dispatch(&plan, layer, &ids, route(n_tok, k), NO_PRIMARY), + dispatch(&plan, layer, &ids, route_shape(n_tok, k), NO_PRIMARY), Err(RemoteError::InvalidDispatch), "{layer} {n_tok} {k}" ); } - assert!(dispatch(&plan, 1, &ids, route(8, 10), NO_PRIMARY).is_ok()); + assert!(dispatch(&plan, 1, &ids, route_shape(8, 10), NO_PRIMARY).is_ok()); } #[test] fn meta_image_and_scatter() { let plan = plan_for_dispatch(); let ids: Vec = vec![4, 9, 4, 0, 1, 3, 5, 6, 8, 10]; - let d = dispatch(&plan, 1, &ids, route(1, 10), NO_PRIMARY).unwrap(); + let d = dispatch(&plan, 1, &ids, route_shape(1, 10), NO_PRIMARY).unwrap(); let img = RemoteMeta::to_bytes(&d, &|slot| 0x1000_0000 + slot as u64 * 0x10_0000); assert_eq!(u64::from_le_bytes(img[0..8].try_into().unwrap()), 0x1000_0000); assert_eq!(u64::from_le_bytes(img[8..16].try_into().unwrap()), 0x1010_0000); @@ -215,7 +231,7 @@ fn device_buffers_fit_a_small_budget() { assert_eq!(moe_hit_grouped_scratch_bytes(0, 2560, 640), 0); assert_eq!(native_expert_scratch_bytes(80, 640), 3 * 204_800 + ((80 * 20 * 36 + 255) & !255)); let mut t = Totals::default(); - let d = dispatch(&plan_for_dispatch(), 1, &[4; 10], route(1, 10), NO_PRIMARY).unwrap(); + let d = dispatch(&plan_for_dispatch(), 1, &[4; 10], route_shape(1, 10), NO_PRIMARY).unwrap(); t.record(&d); assert_eq!((t.computed, t.launched_layers), (10, 1)); } diff --git a/crates/experimental-ref/tests/emulated_kernels.rs b/crates/experimental-ref/tests/emulated_kernels.rs index 7c9a0e6a..ebb9b015 100644 --- a/crates/experimental-ref/tests/emulated_kernels.rs +++ b/crates/experimental-ref/tests/emulated_kernels.rs @@ -90,16 +90,16 @@ fn gqa_tensors(ids: &[i32], deq: &dyn Fn(&[i32]) -> Vec) -> Vec { } /// The dequantizers of one attention case: the K and V values at the selected cells. -struct Dequant<'a> { +struct KvDequantizers<'a> { k: &'a dyn Fn(&[i32]) -> Vec, v: &'a dyn Fn(&[i32]) -> Vec, } -fn check_attention(name: &str, got: &[f32], q: &[Vec], selections: &[Vec], deq: Dequant) { +fn check_attention(name: &str, got: &[f32], q: &[Vec], selections: &[Vec], deq: KvDequantizers) { assert_eq!(got.len(), NQ * NH * 256); for b in 0..NQ { let ids = &selections[b]; - let shape = attn::AttnShape { n_head: NH, n_head_kv: 2, n_ids: ids.len() }; + let shape = attn::ReferenceAttentionShape { head_count: NH, kv_head_count: 2, attended_count: ids.len() }; let want = attn::reference(&q[b], &gqa_tensors(ids, deq.k), &gqa_tensors(ids, deq.v), shape); let (l2, max) = attn::errors(&got[b * NH * 256..(b + 1) * NH * 256], &want); eprintln!("{name} query {b}: relative L2 {l2:e}, max abs {max:e}"); diff --git a/crates/experimental-ref/tests/emulated_kernels/cvec_reduction.rs b/crates/experimental-ref/tests/emulated_kernels/cvec_reduction.rs index d59b171a..4cc6d2b5 100644 --- a/crates/experimental-ref/tests/emulated_kernels/cvec_reduction.rs +++ b/crates/experimental-ref/tests/emulated_kernels/cvec_reduction.rs @@ -72,7 +72,7 @@ impl CvecCase { let t = self.table(spec.table.mode, dirv, spec.table.scale); let mut r = self.r0.clone(); let pending = if spec.write { Some((&self.bo[..], self.n, &self.inj[..], self.hc)) } else { None }; - let rows = cvec::CvecRows { r: &mut r, t_count: self.t_count, r_ld: self.hc * self.n }; + let rows = cvec::CvecRows { residual: &mut r, row_count: self.t_count, row_stride: self.hc * self.n }; cvec::apply(rows, &t, spec.on, layer_used, pending); r } @@ -93,10 +93,12 @@ struct TableSpec { scale: f32, } -const fn tab(mode: CvecMode, unit: bool, scale: f32) -> TableSpec { +/// The table of a test case from its mode, direction and scale. +const fn table_spec(mode: CvecMode, unit: bool, scale: f32) -> TableSpec { TableSpec { mode, unit, scale } } +/// One case of the fixture from its name, table, steering flag and pending-write flag. const fn spec(name: &'static str, table: TableSpec, on: bool, write: bool) -> CaseSpec { CaseSpec { name, table, on, write } } @@ -104,14 +106,14 @@ const fn spec(name: &'static str, table: TableSpec, on: bool, write: bool) -> Ca /// The eight cases of the fixture; the last one runs on layer 1, which has no direction. fn case_specs() -> [CaseSpec; 8] { [ - spec("project_s1", tab(CvecMode::Project, true, 1.0), true, false), - spec("project_s2", tab(CvecMode::Project, true, 2.0), true, false), - spec("add", tab(CvecMode::Add, false, 1.0), true, false), - spec("off", tab(CvecMode::Project, true, 1.0), false, false), - spec("off_write", tab(CvecMode::Project, true, 1.0), false, true), - spec("project_write", tab(CvecMode::Project, true, 1.0), true, true), - spec("add_write", tab(CvecMode::Add, false, 1.0), true, true), - spec("no_direction_layer", tab(CvecMode::Project, true, 1.0), true, false), + spec("project_s1", table_spec(CvecMode::Project, true, 1.0), true, false), + spec("project_s2", table_spec(CvecMode::Project, true, 2.0), true, false), + spec("add", table_spec(CvecMode::Add, false, 1.0), true, false), + spec("off", table_spec(CvecMode::Project, true, 1.0), false, false), + spec("off_write", table_spec(CvecMode::Project, true, 1.0), false, true), + spec("project_write", table_spec(CvecMode::Project, true, 1.0), true, true), + spec("add_write", table_spec(CvecMode::Add, false, 1.0), true, true), + spec("no_direction_layer", table_spec(CvecMode::Project, true, 1.0), true, false), ] } diff --git a/crates/experimental-ref/tests/emulated_kernels/fwht_and_q4_append.rs b/crates/experimental-ref/tests/emulated_kernels/fwht_and_q4_append.rs index c64ecac2..f74db44b 100644 --- a/crates/experimental-ref/tests/emulated_kernels/fwht_and_q4_append.rs +++ b/crates/experimental-ref/tests/emulated_kernels/fwht_and_q4_append.rs @@ -34,7 +34,7 @@ fn append_cells_one_by_one(f: &serde_json::Value, ks: &[Vec], vs: &[Vec Result Result (f64, u32) { fn run_gpu(model: &Model, accel: &mut GpuPrefill, prompt: &[u32]) -> (f64, u32) { let mut state = State::new(&model.config, prompt.len() + 1); let t = Instant::now(); + let accelerate = leleka_gptoss::PrefillOffload { + accelerator: accel, + min_tokens: 1, + }; let r = model - .prefill_reuse_accelerated(&mut state, prompt, accel, 1, &mut |_, _| true) + .prefill_reuse_accelerated(&mut state, prompt, accelerate, &mut |_, _| true) .expect("gpu prefill") .expect("not cancelled"); (t.elapsed().as_secs_f64(), r.next) @@ -124,8 +128,12 @@ fn warm_up(model: &Model, accel: &mut GpuPrefill, prompt: &[u32]) { let p = &prompt[..warm_n]; let _ = model.prefill_reuse(&mut state, p).expect("warm cpu"); let mut state = State::new(&model.config, warm_n + 1); + let accelerate = leleka_gptoss::PrefillOffload { + accelerator: accel, + min_tokens: 1, + }; let _ = model - .prefill_reuse_accelerated(&mut state, p, accel, 1, &mut |_, _| true) + .prefill_reuse_accelerated(&mut state, p, accelerate, &mut |_, _| true) .expect("warm gpu"); } diff --git a/crates/gptoss-igpu/examples/admission_check.rs b/crates/gptoss-igpu/examples/admission_check.rs index 5d5534d0..615c2548 100644 --- a/crates/gptoss-igpu/examples/admission_check.rs +++ b/crates/gptoss-igpu/examples/admission_check.rs @@ -35,8 +35,12 @@ fn run_with_memory(label: &str, available: u64, model: &Model, prompt: &[u32]) { .with_memory_probe(Box::new(move || Some(available))); let admitted = accel.admit(model, prompt.len()); let mut state = State::new(&model.config, 64); + let accelerate = leleka_gptoss::PrefillOffload { + accelerator: &mut accel, + min_tokens: 1, + }; let reuse = model - .prefill_reuse_accelerated(&mut state, prompt, &mut accel, 1, &mut |_, _| true) + .prefill_reuse_accelerated(&mut state, prompt, accelerate, &mut |_, _| true) .expect("prefill") .expect("not cancelled"); println!( diff --git a/crates/gptoss-igpu/examples/gpu_prefill.rs b/crates/gptoss-igpu/examples/gpu_prefill.rs index 596dee7f..600f5a77 100644 --- a/crates/gptoss-igpu/examples/gpu_prefill.rs +++ b/crates/gptoss-igpu/examples/gpu_prefill.rs @@ -59,8 +59,12 @@ fn load_model(path: &Path) -> Model { fn gpu_prefill(model: &Model, accel: &mut GpuPrefill, prompt: &[u32], capacity: usize) -> (State, u32, f64) { let mut state = State::new(&model.config, capacity); let t = Instant::now(); + let accelerate = leleka_gptoss::PrefillOffload { + accelerator: accel, + min_tokens: 1, + }; let reuse = model - .prefill_reuse_accelerated(&mut state, prompt, accel, 1, &mut |_, _| true) + .prefill_reuse_accelerated(&mut state, prompt, accelerate, &mut |_, _| true) .expect("gpu prefill") .expect("not cancelled"); (state, reuse.next, t.elapsed().as_secs_f64()) diff --git a/crates/gptoss-igpu/examples/layer0_probe.rs b/crates/gptoss-igpu/examples/layer0_probe.rs index cc626dac..dc441785 100644 --- a/crates/gptoss-igpu/examples/layer0_probe.rs +++ b/crates/gptoss-igpu/examples/layer0_probe.rs @@ -7,7 +7,7 @@ use leleka_cpu_kernels::Dispatch; use leleka_cpu_sys::mapping::Mapping; use leleka_gguf::Gguf; use leleka_gptoss::{Kind, Model, ops}; -use leleka_igpu::{Gpu, WeightKind}; +use leleka_igpu::{Gpu, NormBufs, NormShape, Operands, ProductOutput, WeightKind}; use std::fs::File; use std::io::BufReader; use std::path::Path; @@ -60,8 +60,11 @@ fn gpu_stages(model: &Model, x: &[f32], m: usize) -> GpuStages { let bias = gpu.buf_f32(lv.bk); let kb = gpu.zeros(m * wk.rows); let mut rec = gpu.recorder(); - rec.rmsnorm_quant(&xb, &wb, c.rms_eps, m, e, &hb, &act).unwrap(); - rec.matmul(&wkm, &act, &kb, Some(&bias), false).unwrap(); + let norm = NormBufs { x: &xb, weight: &wb, normalized: &hb, act: &act }; + let shape = NormShape { epsilon: c.rms_eps, row_count: m, width: e }; + rec.rmsnorm_quant(norm, shape).unwrap(); + let io = ProductOutput { out: &kb, bias: Some(&bias) }; + rec.matmul(Operands { w: &wkm, a: &act }, io, false).unwrap(); rec.submit().unwrap(); let gh = gpu.read_f32(&hb).unwrap(); let (words, scales) = gpu.read_activations(&act).unwrap(); diff --git a/crates/gptoss-igpu/src/lib.rs b/crates/gptoss-igpu/src/lib.rs index 1b186e8a..864fde69 100644 --- a/crates/gptoss-igpu/src/lib.rs +++ b/crates/gptoss-igpu/src/lib.rs @@ -13,11 +13,13 @@ //! passes (`benchmarks/quality`). use leleka_gptoss::{ - Kind, LayerCache, LayerView, Model, ModelError, PrefillAccelerator, SWIGLU_ALPHA, SWIGLU_LIMIT, - State, WeightView, + Kind, LayerCache, LayerView, Model, ModelError, PrefillAccelerator, PrefillJob, PrefillSpan, + SWIGLU_ALPHA, SWIGLU_LIMIT, State, WeightView, }; use leleka_igpu::{ - AttentionShape, Buf, Gpu, GpuActivations, GpuError, GpuMatrix, SwigluParams, WeightKind, + AttentionBufs, AttentionShape, Buf, CombineBufs, Gpu, GpuActivations, GpuError, GpuMatrix, KvStoreShape, + MoePlan, NormBufs, NormShape, Operands, ProductOutput, RopeShape, RouterBufs, SwigluBufs, SwigluParams, + WeightKind, }; use std::time::{Duration, Instant}; @@ -261,11 +263,11 @@ impl PrefillAccelerator for GpuPrefill { &mut self, model: &Model, state: &mut State, - tokens: &[u32], - pos0: usize, + span: PrefillSpan, progress: &mut dyn FnMut(f64) -> bool, ) -> Result>, ModelError> { - self.prefill_part(model, state, tokens, pos0, progress, false) + let job = PrefillJob { model, cache: state, span, all_hidden: false }; + self.prefill_part(job, progress) } fn admit(&mut self, model: &Model, tokens: usize) -> bool { let Some(probe) = self.memory_probe.as_ref() else { diff --git a/crates/gptoss-igpu/src/prefill_pass.rs b/crates/gptoss-igpu/src/prefill_pass.rs index 49ca7989..3458643b 100644 --- a/crates/gptoss-igpu/src/prefill_pass.rs +++ b/crates/gptoss-igpu/src/prefill_pass.rs @@ -14,9 +14,13 @@ impl GpuPrefill { tokens: &[u32], pos0: usize, ) -> Result, ModelError> { - Ok(self - .prefill_part(model, state, tokens, pos0, &mut |_| true, true)? - .expect("not cancelled")) + let job = PrefillJob { + model, + cache: state, + span: PrefillSpan { tokens, pos0 }, + all_hidden: true, + }; + Ok(self.prefill_part(job, &mut |_| true)?.expect("not cancelled")) } /// Prefill `tokens` at positions `pos0..` reading the earlier rows from and storing this run's rows into `cache` @@ -24,13 +28,11 @@ impl GpuPrefill { /// when `progress` asked to stop. [`PrefillAccelerator::prefill`] is this with the decoder's own cache. pub fn prefill_part( &mut self, - model: &Model, - cache: &dyn LayerCache, - tokens: &[u32], - pos0: usize, + job: PrefillJob, mut progress: &mut dyn FnMut(f64) -> bool, - all_hidden: bool, ) -> Result>, ModelError> { + let PrefillJob { model, cache, span, all_hidden } = job; + let PrefillSpan { tokens, pos0 } = span; Self::check(model)?; let started = Instant::now(); self.timings = Timings { diff --git a/crates/gptoss-igpu/src/prefill_run.rs b/crates/gptoss-igpu/src/prefill_run.rs index 8292dfb6..93aa76e8 100644 --- a/crates/gptoss-igpu/src/prefill_run.rs +++ b/crates/gptoss-igpu/src/prefill_run.rs @@ -7,6 +7,14 @@ use leleka_gptoss::Config; use leleka_igpu::Recorder; use std::sync::mpsc::{Receiver, SyncSender}; +/// One batch of the chunk: its index, its first row and its rows. +#[derive(Clone, Copy)] +struct BatchSpan { + batch_index: usize, + first_row: usize, + row_count: usize, +} + /// The batches of the chunk (first row, rows) with their embeddings and rotation tables on the GPU. pub(super) struct Inputs { batches: Vec<(usize, usize)>, @@ -184,7 +192,7 @@ impl<'a> PrefillRun<'a> { let mut rec = gpu.recorder(); self.record_projections(&mut rec, lw, bi, m)?; self.record_rope_and_cache(&mut rec, bi, (b0, m))?; - self.record_attention(&mut rec, lw, bi, (b0, m), window)?; + self.record_attention(&mut rec, lw, BatchSpan { batch_index: bi, first_row: b0, row_count: m }, window)?; rec.submit().map_err(gpu_error)?; gpu.read_u32_at(&self.s.ids, 0, m * self.c.n_expert_used) .map_err(gpu_error) @@ -193,15 +201,27 @@ impl<'a> PrefillRun<'a> { /// Attention norm and the Q, K and V projections. fn record_projections(&self, rec: &mut Recorder, lw: &GpuLayer, bi: usize, m: usize) -> Result<(), ModelError> { let (c, s) = (self.c, &self.s); - let x = &self.inputs.xs[bi]; - rec.rmsnorm_quant(x, &lw.attn_norm, c.rms_eps, m, c.n_embd, &s.h, &s.act) - .map_err(gpu_error)?; - rec.matmul_rows(&lw.wq, &s.act, m, &s.q, Some(&lw.bq), false) - .map_err(gpu_error)?; - rec.matmul_rows(&lw.wk, &s.act, m, &s.k, Some(&lw.bk), false) - .map_err(gpu_error)?; - rec.matmul_rows(&lw.wv, &s.act, m, &s.v, Some(&lw.bv), false) - .map_err(gpu_error) + let norm = NormBufs { x: &self.inputs.xs[bi], weight: &lw.attn_norm, normalized: &s.h, act: &s.act }; + let shape = NormShape { epsilon: c.rms_eps, row_count: m, width: c.n_embd }; + rec.rmsnorm_quant(norm, shape).map_err(gpu_error)?; + let q = ProductOutput { out: &s.q, bias: Some(&lw.bq) }; + self.record_projection(rec, &lw.wq, q, m)?; + let k = ProductOutput { out: &s.k, bias: Some(&lw.bk) }; + self.record_projection(rec, &lw.wk, k, m)?; + let v = ProductOutput { out: &s.v, bias: Some(&lw.bv) }; + self.record_projection(rec, &lw.wv, v, m) + } + + /// The first `row_count` rows of the normalized activations times `weights`, with bias, into `output`. + fn record_projection( + &self, + rec: &mut Recorder, + weights: &GpuMatrix, + output: ProductOutput, + row_count: usize, + ) -> Result<(), ModelError> { + let operands = Operands { w: weights, a: &self.s.act }; + rec.matmul_rows(operands, row_count, output, false).map_err(gpu_error) } /// RoPE on Q and K, then K and V into the caches. @@ -209,12 +229,12 @@ impl<'a> PrefillRun<'a> { let (c, s) = (self.c, &self.s); let (hd, kw) = (c.head_dim, c.kv_width()); let rot = &self.inputs.rots[bi]; - rec.rope(&s.q, rot, m, c.n_head, hd).map_err(gpu_error)?; - rec.rope(&s.k, rot, m, c.n_head_kv, hd).map_err(gpu_error)?; - rec.kv_store(&s.k, &self.kcache, m, kw, self.pos0 + b0) - .map_err(gpu_error)?; - rec.kv_store(&s.v, &self.vcache, m, kw, self.pos0 + b0) - .map_err(gpu_error) + let rope_shape = |head_count| RopeShape { token_count: m, head_count, head_dim: hd }; + rec.rope(&s.q, rot, rope_shape(c.n_head)).map_err(gpu_error)?; + rec.rope(&s.k, rot, rope_shape(c.n_head_kv)).map_err(gpu_error)?; + let store = KvStoreShape { row_count: m, kv_width: kw, first_position: self.pos0 + b0 }; + rec.kv_store(&s.k, &self.kcache, store).map_err(gpu_error)?; + rec.kv_store(&s.v, &self.vcache, store).map_err(gpu_error) } /// Attention over the caches, the output projection (added to the residual) and the router. @@ -222,13 +242,12 @@ impl<'a> PrefillRun<'a> { &self, rec: &mut Recorder, lw: &GpuLayer, - bi: usize, - (b0, m): (usize, usize), + batch: BatchSpan, window: usize, ) -> Result<(), ModelError> { + let BatchSpan { batch_index: bi, first_row: b0, row_count: m } = batch; let (c, s) = (self.c, &self.s); let (qw, kw) = (c.q_width(), c.kv_width()); - let x = &self.inputs.xs[bi]; let shape = AttentionShape { m, pos0: self.pos0 + b0, @@ -237,39 +256,73 @@ impl<'a> PrefillRun<'a> { q_width: qw, scale: 1.0 / (c.head_dim as f32).sqrt(), }; - rec.attention(shape, &s.q, &self.kcache, &self.vcache, &lw.sinks, &s.attn) - .map_err(gpu_error)?; + let bufs = AttentionBufs { + queries: &s.q, + keys: &self.kcache, + values: &self.vcache, + sinks: &lw.sinks, + out: &s.attn, + }; + rec.attention(shape, bufs).map_err(gpu_error)?; rec.quantize(&s.attn, m, qw, &s.act_attn).map_err(gpu_error)?; - rec.matmul_rows(&lw.wo, &s.act_attn, m, x, Some(&lw.bo), true) - .map_err(gpu_error)?; - rec.rmsnorm_quant(x, &lw.post_norm, c.rms_eps, m, c.n_embd, &s.h, &s.act) - .map_err(gpu_error)?; - rec.router(&s.h, &lw.router_w, &lw.router_b, m, c.n_embd, &s.ids, &s.weights) - .map_err(gpu_error) + self.record_output_and_router(rec, lw, (bi, m)) + } + + /// The output projection added to the residual, the post-attention norm of the residual and the router. + fn record_output_and_router( + &self, + rec: &mut Recorder, + lw: &GpuLayer, + (bi, m): (usize, usize), + ) -> Result<(), ModelError> { + let (c, s) = (self.c, &self.s); + let x = &self.inputs.xs[bi]; + let ops = Operands { w: &lw.wo, a: &s.act_attn }; + let io = ProductOutput { out: x, bias: Some(&lw.bo) }; + rec.matmul_rows(ops, m, io, true).map_err(gpu_error)?; + let norm = NormBufs { x, weight: &lw.post_norm, normalized: &s.h, act: &s.act }; + let shape = NormShape { epsilon: c.rms_eps, row_count: m, width: c.n_embd }; + rec.rmsnorm_quant(norm, shape).map_err(gpu_error)?; + let bufs = RouterBufs { + h: &s.h, + weights: &lw.router_w, + bias: &lw.router_b, + ids: &s.ids, + expert_weights: &s.weights, + }; + rec.router(bufs, m, c.n_embd).map_err(gpu_error) } /// The expert products of one batch for the experts `chosen`, combined into the residual. fn run_experts(&self, lw: &GpuLayer, bi: usize, chosen: &[u32]) -> Result<(), ModelError> { let (gpu, c, s) = (self.gpu, self.c, &self.s); - let (e, ff) = (c.n_embd, c.n_ff); + let plan = gpu.plan_moe(chosen, c.n_expert_used, c.n_expert).map_err(gpu_error)?; + let mut rec = gpu.recorder(); + self.record_expert_products(&mut rec, lw, &plan)?; + let bufs = CombineBufs { down: &s.down, expert_weights: &s.weights, x: &self.inputs.xs[bi] }; + rec.moe_combine(&plan, bufs, c.n_embd).map_err(gpu_error)?; + rec.submit().map_err(gpu_error) + } + + /// The gate and up products, the activation and the down product of the experts of `plan`. + fn record_expert_products(&self, rec: &mut Recorder, lw: &GpuLayer, plan: &MoePlan) -> Result<(), ModelError> { + let (s, ff) = (&self.s, self.c.n_ff); let activation = SwigluParams { alpha: SWIGLU_ALPHA, limit: SWIGLU_LIMIT, }; - let plan = gpu.plan_moe(chosen, c.n_expert_used, c.n_expert).map_err(gpu_error)?; - let entries = plan.entries(); - let mut rec = gpu.recorder(); - rec.moe_matmul(&lw.gate, &s.act, &plan, true, Some(&lw.gate_b), &s.gate) + let gate = ProductOutput { out: &s.gate, bias: Some(&lw.gate_b) }; + let ops = Operands { w: &lw.gate, a: &s.act }; + rec.moe_matmul(ops, plan, true, gate).map_err(gpu_error)?; + let up = ProductOutput { out: &s.up, bias: Some(&lw.up_b) }; + let ops = Operands { w: &lw.up, a: &s.act }; + rec.moe_matmul(ops, plan, true, up).map_err(gpu_error)?; + let bufs = SwigluBufs { gate: &s.gate, up: &s.up, act: &s.act_ff }; + rec.swiglu_quant(bufs, plan.entries(), ff, activation) .map_err(gpu_error)?; - rec.moe_matmul(&lw.up, &s.act, &plan, true, Some(&lw.up_b), &s.up) - .map_err(gpu_error)?; - rec.swiglu_quant(&s.gate, &s.up, entries, ff, activation, &s.act_ff) - .map_err(gpu_error)?; - rec.moe_matmul(&lw.down, &s.act_ff, &plan, false, Some(&lw.down_b), &s.down) - .map_err(gpu_error)?; - rec.moe_combine(&s.down, &plan, &s.weights, &self.inputs.xs[bi], e) - .map_err(gpu_error)?; - rec.submit().map_err(gpu_error) + let down = ProductOutput { out: &s.down, bias: Some(&lw.down_b) }; + let ops = Operands { w: &lw.down, a: &s.act_ff }; + rec.moe_matmul(ops, plan, false, down).map_err(gpu_error) } /// The hidden state of the last token, or of every token. diff --git a/crates/gptoss-npu/examples/ab_prefill_npu.rs b/crates/gptoss-npu/examples/ab_prefill_npu.rs index 86e0d0d4..cf329a17 100644 --- a/crates/gptoss-npu/examples/ab_prefill_npu.rs +++ b/crates/gptoss-npu/examples/ab_prefill_npu.rs @@ -111,8 +111,12 @@ fn run_cpu(model: &Model, prompt: &[u32]) -> (f64, u32) { fn run_npu(model: &Model, accel: &mut NpuPrefill, prompt: &[u32]) -> (f64, u32) { let mut state = State::new(&model.config, prompt.len() + 1); let t = Instant::now(); + let accelerate = leleka_gptoss::PrefillOffload { + accelerator: accel, + min_tokens: 1, + }; let r = model - .prefill_reuse_accelerated(&mut state, prompt, accel, 1, &mut |_, _| true) + .prefill_reuse_accelerated(&mut state, prompt, accelerate, &mut |_, _| true) .expect("npu prefill") .expect("not cancelled"); (t.elapsed().as_secs_f64(), r.next) @@ -125,8 +129,12 @@ fn warm_up(model: &Model, accel: &mut NpuPrefill, prompt: &[u32]) { let p = &prompt[..warm_n]; let _ = model.prefill_reuse(&mut state, p).expect("warm cpu"); let mut state = State::new(&model.config, warm_n + 1); + let accelerate = leleka_gptoss::PrefillOffload { + accelerator: accel, + min_tokens: 1, + }; let _ = model - .prefill_reuse_accelerated(&mut state, p, accel, 1, &mut |_, _| true) + .prefill_reuse_accelerated(&mut state, p, accelerate, &mut |_, _| true) .expect("warm npu"); } diff --git a/crates/gptoss-npu/examples/npu_prefill.rs b/crates/gptoss-npu/examples/npu_prefill.rs index b9b1d1bb..24722ef1 100644 --- a/crates/gptoss-npu/examples/npu_prefill.rs +++ b/crates/gptoss-npu/examples/npu_prefill.rs @@ -76,8 +76,12 @@ fn start_accelerator(a: &[String], path: &Path, batch: usize) -> NpuPrefill { fn npu_prefill(model: &Model, accel: &mut NpuPrefill, prompt: &[u32], capacity: usize) -> (State, u32) { let mut npu_state = State::new(&model.config, capacity); let t = Instant::now(); + let accelerate = leleka_gptoss::PrefillOffload { + accelerator: accel, + min_tokens: 1, + }; let npu = model - .prefill_reuse_accelerated(&mut npu_state, prompt, accel, 1, &mut |_, _| true) + .prefill_reuse_accelerated(&mut npu_state, prompt, accelerate, &mut |_, _| true) .expect("npu prefill") .expect("not cancelled"); let s = t.elapsed().as_secs_f64(); diff --git a/crates/gptoss-npu/examples/numerics_probe.rs b/crates/gptoss-npu/examples/numerics_probe.rs index 481c7c3c..ffca951d 100644 --- a/crates/gptoss-npu/examples/numerics_probe.rs +++ b/crates/gptoss-npu/examples/numerics_probe.rs @@ -9,7 +9,7 @@ use leleka_cpu_kernels::Dispatch; use leleka_cpu_sys::mapping::Mapping; use leleka_gguf::Gguf; use leleka_gptoss::{Model, ops}; -use leleka_gptoss_npu::client::{Client, ServiceConfig}; +use leleka_gptoss_npu::client::{Client, ProductRegions, ServiceConfig, ServiceTensor}; use std::fs::File; use std::io::BufReader; use std::path::{Path, PathBuf}; @@ -85,8 +85,9 @@ fn probe_device(config: &ServiceConfig, halves: &[u16], reference: &[f64], n_tok let mut client = Client::start(config, 64).unwrap(); client.put(client.layout.input_a, halves).unwrap(); let (input, out) = (client.layout.input_a, client.layout.out[0]); + let tensor = ServiceTensor { name: "blk.0.attn_v.weight", expert: None }; let shifts = client - .product("blk.0.attn_v.weight", None, n_tokens, n, input, out) + .product(tensor, n_tokens, n, ProductRegions { input, out }) .unwrap(); let y = client.get(out, n_tokens * n).unwrap(); let (num, per_token) = device_errors(&y, shifts.as_deref(), reference, n_tokens); diff --git a/crates/gptoss-npu/src/accelerator.rs b/crates/gptoss-npu/src/accelerator.rs index 5d9b76f7..16d2c518 100644 --- a/crates/gptoss-npu/src/accelerator.rs +++ b/crates/gptoss-npu/src/accelerator.rs @@ -8,11 +8,11 @@ impl PrefillAccelerator for NpuPrefill { &mut self, model: &Model, state: &mut State, - tokens: &[u32], - pos0: usize, + span: PrefillSpan, progress: &mut dyn FnMut(f64) -> bool, ) -> Result>, ModelError> { - self.prefill_part(model, state, tokens, pos0, progress, false) + let job = PrefillJob { model, cache: state, span, all_hidden: false }; + self.prefill_part(job, progress) } fn admit(&mut self, model: &Model, tokens: usize) -> bool { diff --git a/crates/gptoss-npu/src/client.rs b/crates/gptoss-npu/src/client.rs index 96571657..c765fec1 100644 --- a/crates/gptoss-npu/src/client.rs +++ b/crates/gptoss-npu/src/client.rs @@ -64,6 +64,20 @@ impl Layout { } } +/// The tensor a product multiplies by: its `name` and, for a stacked tensor, the `expert`. +#[derive(Clone, Copy, Debug)] +pub struct ServiceTensor<'a> { + pub name: &'a str, + pub expert: Option, +} + +/// Where a product reads its rows and writes its result. +#[derive(Clone, Copy, Debug)] +pub struct ProductRegions { + pub input: Region, + pub out: Region, +} + /// One product of a batch: `rows` rows from the byte offset `input` times the tensor, `cols` result columns /// written at the byte offset `out`. #[derive(Clone, Debug)] @@ -290,13 +304,13 @@ impl Client { /// (divide column `c` of the result by `2^shifts[c]`), `None` otherwise. pub fn product( &mut self, - name: &str, - expert: Option, + tensor: ServiceTensor, rows: usize, cols: usize, - input: Region, - out: Region, + io: ProductRegions, ) -> Result>, String> { + let ServiceTensor { name, expert } = tensor; + let ProductRegions { input, out } = io; let e = expert.map_or("-".to_owned(), |e| e.to_string()); let answer = self.ask(&format!("MM {name} {e} {rows} {} {}", input.offset, out.offset))?; let mut fields = answer.split_whitespace(); diff --git a/crates/gptoss-npu/src/construction_and_estimates.rs b/crates/gptoss-npu/src/construction_and_estimates.rs index 5dfdcd37..69e5092d 100644 --- a/crates/gptoss-npu/src/construction_and_estimates.rs +++ b/crates/gptoss-npu/src/construction_and_estimates.rs @@ -81,8 +81,12 @@ impl NpuPrefill { tokens: &[u32], pos0: usize, ) -> Result, ModelError> { - Ok(self - .prefill_part(model, state, tokens, pos0, &mut |_| true, true)? - .expect("not cancelled")) + let job = PrefillJob { + model, + cache: state, + span: PrefillSpan { tokens, pos0 }, + all_hidden: true, + }; + Ok(self.prefill_part(job, &mut |_| true)?.expect("not cancelled")) } } diff --git a/crates/gptoss-npu/src/expert_pass.rs b/crates/gptoss-npu/src/expert_pass.rs index bf1cd026..9cf65dbf 100644 --- a/crates/gptoss-npu/src/expert_pass.rs +++ b/crates/gptoss-npu/src/expert_pass.rs @@ -1,5 +1,6 @@ //! The expert products of one layer through the service and reading their results. +use super::prefill_part_pass::LayerCtx; #[allow(unused_imports)] use super::*; @@ -84,17 +85,15 @@ impl NpuPrefill { /// the activation runs on all cores, then the down products go as another batch. Because the service sees the /// whole list it prepares each product's weights while the device runs the one before it. Returns the /// weighted expert outputs per token (`m * e`). - #[allow(clippy::too_many_arguments)] // the pieces of one layer step, passed explicitly pub(super) fn experts( &mut self, - dispatch: &Dispatch, - view: &LayerView<'_>, - layer: usize, + ctx: &LayerCtx, per_expert: &[Vec<(usize, f32)>], h2f: &[u16], m: usize, - (e, ff): (usize, usize), ) -> Result, ModelError> { + let (dispatch, view, layer) = (&ctx.dispatch, &ctx.view, ctx.l); + let (e, ff) = (ctx.c.n_embd, ctx.c.n_ff); let layout = self.client.layout; let t0 = Instant::now(); let plan = ExpertPlan::new(per_expert, m); @@ -104,7 +103,7 @@ impl NpuPrefill { self.timings.part(5, t0.elapsed()); let shifts = self.timed_products(&specs)?; let t2 = Instant::now(); - let act = self.activation(dispatch, view, &plan, (&at.gate, &at.up), &shifts, ff)?; + let act = self.activation(ctx, &plan, (&at.gate, &at.up), &shifts)?; self.put_activations(dispatch, &act)?; let down_specs = down_specs(&layout, layer, &plan.chunks, &at.down, (e, ff)); self.timings.part(6, t2.elapsed()); @@ -159,13 +158,12 @@ impl NpuPrefill { /// The gated activation of every entry from the gate and up results at the given offsets. fn activation( &self, - dispatch: &Dispatch, - view: &LayerView<'_>, + ctx: &LayerCtx, plan: &ExpertPlan, (gate_at, up_at): (&[usize], &[usize]), shifts: &[Option>], - ff: usize, ) -> Result, ModelError> { + let (dispatch, view, ff) = (&ctx.dispatch, &ctx.view, ctx.c.n_ff); let gate_shifts: Vec<_> = shifts.iter().step_by(2).collect(); let up_shifts: Vec<_> = shifts.iter().skip(1).step_by(2).collect(); let mut gate = self.read_results(&plan.chunks, gate_at, ff, &gate_shifts)?; diff --git a/crates/gptoss-npu/src/lib.rs b/crates/gptoss-npu/src/lib.rs index 7d0e1843..f9017c53 100644 --- a/crates/gptoss-npu/src/lib.rs +++ b/crates/gptoss-npu/src/lib.rs @@ -14,11 +14,11 @@ pub mod client; mod half; mod par; -use client::{Client, Layout, Region, ServiceConfig, Spec}; +use client::{Client, ProductRegions, Layout, Region, ServiceConfig, Spec, ServiceTensor}; use leleka_cpu_kernels::Dispatch; use leleka_gptoss::{ - LayerCache, LayerView, Model, ModelError, PrefillAccelerator, SWIGLU_ALPHA, SWIGLU_LIMIT, - State, ops, + LayerCache, LayerView, Model, ModelError, PrefillAccelerator, PrefillJob, PrefillSpan, SWIGLU_ALPHA, + SWIGLU_LIMIT, State, ops, }; use std::time::{Duration, Instant}; diff --git a/crates/gptoss-npu/src/prefill_batch.rs b/crates/gptoss-npu/src/prefill_batch.rs index 55a96984..3e3f01ba 100644 --- a/crates/gptoss-npu/src/prefill_batch.rs +++ b/crates/gptoss-npu/src/prefill_batch.rs @@ -32,7 +32,7 @@ impl NpuPrefill { xs: &mut [f32], span: (usize, usize), ) -> Result<(), ModelError> { - let (e, ff) = (ctx.c.n_embd, ctx.c.n_ff); + let e = ctx.c.n_embd; self.qkv_products(ctx, xs, span)?; let q = self.qkv_to_caches(ctx, kv, span)?; let attn = self.attend_batch(ctx, kv, &q, span); @@ -42,7 +42,7 @@ impl NpuPrefill { self.timings.part(3, t4.elapsed()); // --- experts --- - let moe = self.experts(&ctx.dispatch, &ctx.view, ctx.l, &per_expert, &h2f, span.1, (e, ff))?; + let moe = self.experts(ctx, &per_expert, &h2f, span.1)?; let t5 = Instant::now(); par::for_chunks(&mut xs[span.0 * e..(span.0 + span.1) * e], e, |t, row| { for (x, d) in row.iter_mut().zip(&moe[t * e..(t + 1) * e]) { @@ -70,9 +70,10 @@ impl NpuPrefill { self.put_floats(&ctx.dispatch, ctx.layout.input_a, &h)?; self.timings.part(0, t0.elapsed()); let layout = ctx.layout; - self.product(&ctx.name("attn_q"), None, m, (e, qw), layout.input_a, layout.out[0])?; - self.product(&ctx.name("attn_k"), None, m, (e, kw), layout.input_a, layout.out[1])?; - self.product(&ctx.name("attn_v"), None, m, (e, kw), layout.input_a, layout.out[2]) + let io = |i: usize| ProductRegions { input: layout.input_a, out: layout.out[i] }; + self.product(ServiceTensor { name: &ctx.name("attn_q"), expert: None }, m, (e, qw), io(0))?; + self.product(ServiceTensor { name: &ctx.name("attn_k"), expert: None }, m, (e, kw), io(1))?; + self.product(ServiceTensor { name: &ctx.name("attn_v"), expert: None }, m, (e, kw), io(2)) } /// Fetch Q, K and V, add the biases, rotate Q and K and store K and V into the layer's half precision caches. @@ -111,10 +112,11 @@ impl NpuPrefill { let group = ctx.c.n_head / ctx.c.n_head_kv; // --- attention over the cache --- let t2 = Instant::now(); + let batch = AttendedBatch { caches: kv, queries: q, first_row: b0 }; let parts = par::dynamic( m * ctx.c.n_head_kv, || (Vec::::new(), Vec::<(usize, usize, Vec)>::new()), - |item, (scores, done)| done.push(attend_item(ctx, kv, q, b0, item, scores)), + |item, (scores, done)| done.push(attend_item(ctx, &batch, item, scores)), ); let mut attn = vec![0.0f32; m * qw]; for (_, done) in parts { @@ -133,14 +135,9 @@ impl NpuPrefill { self.put_floats(&ctx.dispatch, ctx.layout.input_a, attn)?; self.timings.part(2, t3.elapsed()); let (qw, e) = (ctx.c.q_width(), ctx.c.n_embd); - self.product( - &ctx.name("attn_output"), - None, - m, - (qw, e), - ctx.layout.input_a, - ctx.layout.out[3], - )?; + let tensor = ServiceTensor { name: &ctx.name("attn_output"), expert: None }; + let io = ProductRegions { input: ctx.layout.input_a, out: ctx.layout.out[3] }; + self.product(tensor, m, (qw, e), io)?; Ok(Instant::now()) } @@ -201,15 +198,22 @@ fn route_row(ctx: &LayerCtx, h: &[f32]) -> Vec<(usize, f32)> { ops::route_top_k(&logits, c.n_expert_used) } +/// What the attention of a batch reads: the layer's caches, the batch's queries and its first row. +#[derive(Clone, Copy)] +struct AttendedBatch<'a> { + caches: &'a KvBuffers, + queries: &'a [f32], + first_row: usize, +} + /// The query heads of one KV head for one row of the batch, attended together: (row, KV head, output). fn attend_item( ctx: &LayerCtx, - kv: &KvBuffers, - q: &[f32], - b0: usize, + batch: &AttendedBatch, item: usize, scores: &mut Vec, ) -> (usize, usize, Vec) { + let AttendedBatch { caches: kv, queries: q, first_row: b0 } = *batch; let c = ctx.c; let (hd, kw) = (c.head_dim, c.kv_width()); let group = c.n_head / c.n_head_kv; @@ -220,8 +224,7 @@ fn attend_item( let start = first * kw + kvh * hd; ops::attend_group_with_sink( query_group(ctx, q, t, kvh), - kv_rows(kv, start, kw), - attended, + kv_rows(kv, start, kw, attended), &ctx.dispatch, scores, &mut out, @@ -243,10 +246,11 @@ fn query_group<'a>(ctx: &'a LayerCtx<'_>, q: &'a [f32], t: usize, kvh: usize) -> } /// The cached keys and values from position offset `start`. -fn kv_rows(kv: &KvBuffers, start: usize, stride: usize) -> ops::KvRows<'_> { +fn kv_rows(kv: &KvBuffers, start: usize, stride: usize, n: usize) -> ops::KvRows<'_> { ops::KvRows { keys: &kv.kc[start..], values: &kv.vc[start..], stride, + n, } } diff --git a/crates/gptoss-npu/src/prefill_part_pass.rs b/crates/gptoss-npu/src/prefill_part_pass.rs index 49b9b3a2..5abf7e93 100644 --- a/crates/gptoss-npu/src/prefill_part_pass.rs +++ b/crates/gptoss-npu/src/prefill_part_pass.rs @@ -48,13 +48,11 @@ impl NpuPrefill { /// when `progress` asked to stop. [`PrefillAccelerator::prefill`] is this with the decoder's own cache. pub fn prefill_part( &mut self, - model: &Model, - cache: &dyn LayerCache, - tokens: &[u32], - pos0: usize, + job: PrefillJob, progress: &mut dyn FnMut(f64) -> bool, - all_hidden: bool, ) -> Result>, ModelError> { + let PrefillJob { model, cache, span, all_hidden } = job; + let PrefillSpan { tokens, pos0 } = span; let started = Instant::now(); self.timings = Timings::starting(tokens.len()); let c = &model.config; @@ -66,7 +64,7 @@ impl NpuPrefill { } let rotations = rotation_table(c, n, pos0); for l in 0..c.blocks { - self.prefill_layer(model, cache, l, (pos0, &rotations), &mut xs)?; + self.prefill_layer(&job, l, &rotations, &mut xs)?; if !progress((l + 1) as f64 / c.blocks as f64) { self.timings.total = started.elapsed(); return Ok(None); @@ -104,12 +102,12 @@ impl NpuPrefill { /// One layer for the whole chunk, in batches of rows; the layer's new keys and values go to `cache`. fn prefill_layer( &mut self, - model: &Model, - cache: &(impl LayerCache + ?Sized), + job: &PrefillJob, l: usize, - (pos0, rotations): (usize, &[(f32, f32)]), + rotations: &[(f32, f32)], xs: &mut [f32], ) -> Result<(), ModelError> { + let PrefillJob { model, cache, span: PrefillSpan { pos0, .. }, .. } = *job; let c = &model.config; let (kw, n) = (c.kv_width(), xs.len() / c.n_embd); let ctx = LayerCtx { diff --git a/crates/gptoss-npu/src/service_transfers.rs b/crates/gptoss-npu/src/service_transfers.rs index 0448a7b9..5c413320 100644 --- a/crates/gptoss-npu/src/service_transfers.rs +++ b/crates/gptoss-npu/src/service_transfers.rs @@ -28,15 +28,14 @@ impl NpuPrefill { pub(super) fn product( &mut self, - name: &str, - expert: Option, + tensor: ServiceTensor, rows: usize, (k, n): (usize, usize), - input: Region, - out: Region, + io: ProductRegions, ) -> Result<(), ModelError> { + let ProductRegions { input, out } = io; let started = Instant::now(); - let shifts = self.client.product(name, expert, rows, n, input, out).map_err(fail)?; + let shifts = self.client.product(tensor, rows, n, io).map_err(fail)?; match shifts { Some(s) => { self.shifts.insert(out.offset, s); @@ -47,6 +46,7 @@ impl NpuPrefill { } self.timings.npu += started.elapsed(); if let Some(mut shadow) = self.shadow.take() { + let ServiceTensor { name, expert } = tensor; self.compare_with_shadow(&mut shadow, (name, expert), (rows, k, n), (input, out))?; self.shadow = Some(shadow); } @@ -65,9 +65,8 @@ impl NpuPrefill { let ours = self.fetch(out, rows, n)?; let sl = shadow.layout; shadow.put(sl.input_a, &x).map_err(fail)?; - let their_shifts = shadow - .product(name, expert, rows, n, sl.input_a, sl.out[0]) - .map_err(fail)?; + let io = ProductRegions { input: sl.input_a, out: sl.out[0] }; + let their_shifts = shadow.product(ServiceTensor { name, expert }, rows, n, io).map_err(fail)?; let halves = shadow.get(sl.out[0], rows * n).map_err(fail)?; let mut theirs = vec![0.0f32; rows * n]; half::to_f32(&halves, &mut theirs); diff --git a/crates/gptoss/src/forward_attention.rs b/crates/gptoss/src/forward_attention.rs index 8848df72..43af6215 100644 --- a/crates/gptoss/src/forward_attention.rs +++ b/crates/gptoss/src/forward_attention.rs @@ -59,8 +59,8 @@ impl AttentionRegion { keys: &kc[start..], values: &vc[start..], stride: kw, + n: attended, }, - attended, &self.dispatch, scores, &mut out, diff --git a/crates/gptoss/src/lib.rs b/crates/gptoss/src/lib.rs index 371fd16c..f2406fa6 100644 --- a/crates/gptoss/src/lib.rs +++ b/crates/gptoss/src/lib.rs @@ -45,7 +45,7 @@ mod weights; use weights::{Bias, Layer, QMatrix}; pub use weights::{Kind, LayerView, WeightView}; mod tensor_loading; -use tensor_loading::{SharedBytes, f32_tensor, q_tensor}; +use tensor_loading::{MatrixSpec, SharedBytes, f32_tensor, q_tensor}; mod quant_probes; use quant_probes::{ fake_bits_for, fake_quantize_q8_0, kar_expert_levels_for, kar_levels_for, kar_roundtrip_mxfp4, kar_roundtrip_q8_0, @@ -55,7 +55,7 @@ pub use model::Model; mod profile; pub use profile::Profile; mod state_and_cache; -pub use state_and_cache::{LayerCache, PrefillAccelerator, Reuse, State}; +pub use state_and_cache::{LayerCache, PrefillAccelerator, PrefillJob, PrefillOffload, PrefillSpan, Reuse, State}; mod numeric_helpers; use numeric_helpers::{argmax, dequantize_q8_0_row, f32_to_half_bits, half_to_f32}; mod parallel_jobs; diff --git a/crates/gptoss/src/model.rs b/crates/gptoss/src/model.rs index 68347217..377af0c7 100644 --- a/crates/gptoss/src/model.rs +++ b/crates/gptoss/src/model.rs @@ -61,10 +61,10 @@ fn attention_matrices( Ok(( f32_tensor(file.as_ref(), g, &n("attn_norm.weight"), &[e as u64])?, [ - q_tensor(file, g, &n("attn_q.weight"), Kind::Q8_0, e, qw)?, - q_tensor(file, g, &n("attn_k.weight"), Kind::Q8_0, e, kw)?, - q_tensor(file, g, &n("attn_v.weight"), Kind::Q8_0, e, kw)?, - q_tensor(file, g, &n("attn_output.weight"), Kind::Q8_0, qw, e)?, + q_tensor(file, g, &n("attn_q.weight"), MatrixSpec::q8(e, qw))?, + q_tensor(file, g, &n("attn_k.weight"), MatrixSpec::q8(e, kw))?, + q_tensor(file, g, &n("attn_v.weight"), MatrixSpec::q8(e, kw))?, + q_tensor(file, g, &n("attn_output.weight"), MatrixSpec::q8(qw, e))?, ], )) } @@ -104,9 +104,9 @@ fn expert_matrices(file: &SharedBytes, g: &Gguf, c: &Config, l: usize) -> Result let (e, ff, ne) = (c.n_embd, c.n_ff, c.n_expert); let n = |s: &str| format!("blk.{l}.{s}"); Ok([ - q_tensor(file, g, &n("ffn_gate_exps.weight"), Kind::Mxfp4, e, ne * ff)?, - q_tensor(file, g, &n("ffn_up_exps.weight"), Kind::Mxfp4, e, ne * ff)?, - q_tensor(file, g, &n("ffn_down_exps.weight"), Kind::Mxfp4, ff, ne * e)?, + q_tensor(file, g, &n("ffn_gate_exps.weight"), MatrixSpec::mxfp4(e, ne * ff))?, + q_tensor(file, g, &n("ffn_up_exps.weight"), MatrixSpec::mxfp4(e, ne * ff))?, + q_tensor(file, g, &n("ffn_down_exps.weight"), MatrixSpec::mxfp4(ff, ne * e))?, ]) } @@ -133,8 +133,8 @@ impl Model { layers.push(load_layer(&file, g, &c, l)?); } Ok(Self { - embd: q_tensor(&file, g, "token_embd.weight", Kind::Q8_0, e, vocab)?, - output: q_tensor(&file, g, "output.weight", Kind::Q8_0, e, vocab)?, + embd: q_tensor(&file, g, "token_embd.weight", MatrixSpec::q8(e, vocab))?, + output: q_tensor(&file, g, "output.weight", MatrixSpec::q8(e, vocab))?, output_norm: f32_tensor(f, g, "output_norm.weight", &[e as u64])?, layers, config: c, diff --git a/crates/gptoss/src/ops.rs b/crates/gptoss/src/ops.rs index 42e5f7fe..a00837db 100644 --- a/crates/gptoss/src/ops.rs +++ b/crates/gptoss/src/ops.rs @@ -97,18 +97,19 @@ pub struct Head<'q> { } /// The attended part of a key/value cache for one KV head, stored as IEEE half floats: both slices begin -/// at the first attended position's slice of this head, and consecutive positions are `stride` elements apart. +/// at the first attended position's slice of this head, consecutive positions are `stride` elements apart +/// and `n` positions are attended. pub struct KvRows<'a> { pub keys: &'a [u16], pub values: &'a [u16], pub stride: usize, + pub n: usize, } -/// Attention of `head` over `n` cached positions (see [`attend_group_with_sink`]). +/// Attention of `head` over the `kv.n` cached positions (see [`attend_group_with_sink`]). pub fn attend_with_sink( head: Head<'_>, kv: KvRows<'_>, - n: usize, dispatch: &Dispatch, scores: &mut [f32], out: &mut [f32], @@ -121,7 +122,6 @@ pub fn attend_with_sink( scale, }, kv, - n, dispatch, scores, out, @@ -136,19 +136,18 @@ pub struct Group<'a> { pub scale: f32, } -/// Attention of a group of heads over `n` cached positions. `scores` is scratch of at least +/// Attention of a group of heads over the `kv.n` cached positions. `scores` is scratch of at least /// `heads * n` entries and `out` receives `heads * head_dim` values. The keys and values are read once /// for the whole group (the kernels block over positions); the softmax normalisation is applied once to /// each head's weighted sum. pub fn attend_group_with_sink( group: Group<'_>, kv: KvRows<'_>, - n: usize, dispatch: &Dispatch, scores: &mut [f32], out: &mut [f32], ) -> Result<(), KernelError> { - let heads = group.sinks.len(); + let (heads, n) = (group.sinks.len(), kv.n); if n == 0 { out.fill(0.0); return Ok(()); diff --git a/crates/gptoss/src/ops/tests.rs b/crates/gptoss/src/ops/tests.rs index c45cbcd9..545af4b8 100644 --- a/crates/gptoss/src/ops/tests.rs +++ b/crates/gptoss/src/ops/tests.rs @@ -105,23 +105,16 @@ fn to_bits(values: &[f32]) -> Vec { } /// One `attend_with_sink` run at one kernel level. -fn attend_at(dispatch: &Dispatch, head: Head, kv: KvRows, n: usize) -> Vec { - let mut scores = vec![0.0f32; n.max(1)]; +fn attend_at(dispatch: &Dispatch, head: Head, kv: KvRows) -> Vec { + let mut scores = vec![0.0f32; kv.n.max(1)]; let mut out = vec![9.0f32; head.query.len()]; - attend_with_sink(head, kv, n, dispatch, &mut scores, &mut out).unwrap(); + attend_with_sink(head, kv, dispatch, &mut scores, &mut out).unwrap(); out } /// Runs `attend_with_sink` at every kernel level this machine supports. -fn attend_everywhere( - query: &[f32], - scale: f32, - sink: f32, - keys: &[f32], - values: &[f32], - stride: usize, - n: usize, -) -> Vec> { +fn attend_everywhere(head: Head, keys: &[f32], values: &[f32], stride: usize, n: usize) -> Vec> { + let Head { query, scale, sink } = head; let (keys, values) = (to_bits(keys), to_bits(values)); let mut results = Vec::new(); for isa in leleka_cpu_kernels::Isa::ALL { @@ -132,8 +125,9 @@ fn attend_everywhere( keys: &keys, values: &values, stride, + n, }; - results.push(attend_at(&dispatch, Head { query, scale, sink }, kv, n)); + results.push(attend_at(&dispatch, Head { query, scale, sink }, kv)); } results } @@ -143,7 +137,7 @@ fn attention_with_a_huge_sink_attends_to_nothing_and_a_very_negative_sink_is_pla let q = [1.0f32, 0.0]; let ks = flat(&[[1.0f32, 0.0], [0.0, 1.0], [2.0, 0.0]]); let vs = flat(&[[1.0f32, 10.0], [2.0, 20.0], [3.0, 30.0]]); - for out in attend_everywhere(&q, 1.0, 1000.0, &ks, &vs, 2, 3) { + for out in attend_everywhere(Head { query: &q, scale: 1.0, sink: 1000.0 }, &ks, &vs, 2, 3) { assert!( out.iter().all(|v| v.abs() < 1e-6), "sink absorbs all weight: {out:?}" @@ -152,7 +146,7 @@ fn attention_with_a_huge_sink_attends_to_nothing_and_a_very_negative_sink_is_pla let e: Vec = [1.0f64, 0.0, 2.0].iter().map(|s| s.exp()).collect(); let z: f64 = e.iter().sum(); let expected0 = (e[0] * 1.0 + e[1] * 2.0 + e[2] * 3.0) / z; - for out in attend_everywhere(&q, 1.0, -1000.0, &ks, &vs, 2, 3) { + for out in attend_everywhere(Head { query: &q, scale: 1.0, sink: -1000.0 }, &ks, &vs, 2, 3) { assert!((f64::from(out[0]) - expected0).abs() < 1e-5); } } @@ -178,7 +172,7 @@ fn attention_with_a_finite_sink_matches_an_f64_reference() { .collect(); let m = logits.iter().cloned().fold(f64::from(sink), f64::max); let z: f64 = logits.iter().map(|l| (l - m).exp()).sum::() + (f64::from(sink) - m).exp(); - for out in attend_everywhere(&q, scale, sink, &kf[3..], &vf[3..], 3, 5) { + for out in attend_everywhere(Head { query: &q, scale, sink }, &kf[3..], &vf[3..], 3, 5) { for d in 0..3 { let expected: f64 = (1..6) .map(|p| (logits[p - 1] - m).exp() / z * f64::from(vf[p * 3 + d])) @@ -231,6 +225,7 @@ impl GroupCase { keys: &self.keys, values: &self.values, stride: self.dims.1, + n: self.dims.2, } } @@ -244,13 +239,13 @@ impl GroupCase { scale: 0.125, }; let mut scores = vec![0.0; heads * n]; - attend_group_with_sink(group, self.kv(), n, dispatch, &mut scores, &mut grouped).unwrap(); + attend_group_with_sink(group, self.kv(), dispatch, &mut scores, &mut grouped).unwrap(); grouped } /// The grouped kernel equals the single-head kernel head by head. fn check(&self, isa: leleka_cpu_kernels::Isa, dispatch: &Dispatch) { - let (hd, _stride, n, heads) = self.dims; + let (hd, heads) = (self.dims.0, self.dims.3); let grouped = self.grouped(dispatch); for g in 0..heads { let head = Head { @@ -258,7 +253,7 @@ impl GroupCase { scale: 0.125, sink: self.sinks[g], }; - let single = attend_at(dispatch, head, self.kv(), n); + let single = attend_at(dispatch, head, self.kv()); assert_eq!( &grouped[g * hd..(g + 1) * hd], &single[..], @@ -295,7 +290,7 @@ fn attention_over_a_realistic_cache_agrees_across_kernel_levels() { .map(|_| rnd()) .collect::>(), ); - let results = attend_everywhere(&q, 0.125, 0.5, &ks, &vs, stride, n); + let results = attend_everywhere(Head { query: &q, scale: 0.125, sink: 0.5 }, &ks, &vs, stride, n); assert!(!results.is_empty()); for out in &results[1..] { for (a, b) in results[0].iter().zip(out) { diff --git a/crates/gptoss/src/prefill.rs b/crates/gptoss/src/prefill.rs index bd329775..51a45ce9 100644 --- a/crates/gptoss/src/prefill.rs +++ b/crates/gptoss/src/prefill.rs @@ -81,17 +81,18 @@ impl Model { &self, state: &mut State, prompt: &[u32], - accelerator: &mut dyn PrefillAccelerator, - min_tokens: usize, + accelerate: PrefillOffload, progress: &mut dyn FnMut(usize, usize) -> bool, ) -> Result, ModelError> { + let PrefillOffload { accelerator, min_tokens } = accelerate; let reused = Self::reusable_prefix(state, prompt)?; if prompt.len() - reused < min_tokens || !accelerator.admit(self, prompt.len() - reused) { return self.prefill_reuse_with(state, prompt, progress); } state.truncate(reused); let total = prompt.len(); - let hidden = accelerator.prefill(self, state, &prompt[reused..], reused, &mut |fraction| { + let span = PrefillSpan { tokens: &prompt[reused..], pos0: reused }; + let hidden = accelerator.prefill(self, state, span, &mut |fraction| { progress(reused + ((total - reused) as f64 * fraction) as usize, total) })?; let Some(hidden) = hidden else { diff --git a/crates/gptoss/src/state_and_cache.rs b/crates/gptoss/src/state_and_cache.rs index c247b9b0..ad4dd0dc 100644 --- a/crates/gptoss/src/state_and_cache.rs +++ b/crates/gptoss/src/state_and_cache.rs @@ -122,17 +122,40 @@ impl LayerCache for State { } } -/// A prefill that runs on other hardware (the integrated GPU). It runs `tokens` at positions `pos0..` -/// through all layers, stores their keys and values into `state` (it must not change the cached token list), -/// and returns the hidden state of the last token, or `None` when `progress` (given the finished fraction -/// of the work, in 0..=1) asked to stop. +/// An accelerator and the number of prompt tokens to compute from which it is used (see +/// [`Model::prefill_reuse_accelerated`]). +pub struct PrefillOffload<'a> { + pub accelerator: &'a mut dyn PrefillAccelerator, + pub min_tokens: usize, +} + +/// A chunk of prompt tokens and where it starts: `tokens` run at positions `pos0..`. +#[derive(Clone, Copy, Debug)] +pub struct PrefillSpan<'a> { + pub tokens: &'a [u32], + pub pos0: usize, +} + +/// One accelerator pass over a [`PrefillSpan`]: the model, the cache the pass reads earlier rows from and stores +/// its own into, and whether the result is the hidden state of every token (else of the last one only). +#[derive(Clone, Copy)] +pub struct PrefillJob<'a> { + pub model: &'a Model, + pub cache: &'a dyn LayerCache, + pub span: PrefillSpan<'a>, + pub all_hidden: bool, +} + +/// A prefill that runs on other hardware (the integrated GPU). It runs `span.tokens` at positions +/// `span.pos0..` through all layers, stores their keys and values into `state` (it must not change the cached +/// token list), and returns the hidden state of the last token, or `None` when `progress` (given the finished +/// fraction of the work, in 0..=1) asked to stop. pub trait PrefillAccelerator { fn prefill( &mut self, model: &Model, state: &mut State, - tokens: &[u32], - pos0: usize, + span: PrefillSpan, progress: &mut dyn FnMut(f64) -> bool, ) -> Result>, ModelError>; diff --git a/crates/gptoss/src/tensor_loading.rs b/crates/gptoss/src/tensor_loading.rs index 6554d605..101c698b 100644 --- a/crates/gptoss/src/tensor_loading.rs +++ b/crates/gptoss/src/tensor_loading.rs @@ -81,14 +81,28 @@ fn check_matrix_layout(name: &str, t: &TensorInfo, kind: Kind, cols: usize, rows Ok(()) } -pub(super) fn q_tensor( - file: &SharedBytes, - g: &Gguf, - name: &str, - kind: Kind, - cols: usize, - rows: usize, -) -> Result { +/// The layout a quantized tensor must have: its block `kind`, `cols` columns and `rows` rows. +#[derive(Clone, Copy)] +pub(super) struct MatrixSpec { + pub(super) kind: Kind, + pub(super) cols: usize, + pub(super) rows: usize, +} + +impl MatrixSpec { + /// A Q8_0 matrix of `cols` columns and `rows` rows. + pub(super) fn q8(cols: usize, rows: usize) -> Self { + Self { kind: Kind::Q8_0, cols, rows } + } + + /// An MXFP4 matrix of `cols` columns and `rows` rows. + pub(super) fn mxfp4(cols: usize, rows: usize) -> Self { + Self { kind: Kind::Mxfp4, cols, rows } + } +} + +pub(super) fn q_tensor(file: &SharedBytes, g: &Gguf, name: &str, spec: MatrixSpec) -> Result { + let MatrixSpec { kind, cols, rows } = spec; let t = g.tensor(name).ok_or_else(|| ModelError::Missing(name.into()))?; check_matrix_layout(name, t, kind, cols, rows)?; let (offset, len) = bytes_of(file.as_ref(), g, t, name)?; diff --git a/crates/gpu-npu-worker/examples/split_prefill.rs b/crates/gpu-npu-worker/examples/split_prefill.rs index bd466f81..ae266eb7 100644 --- a/crates/gpu-npu-worker/examples/split_prefill.rs +++ b/crates/gpu-npu-worker/examples/split_prefill.rs @@ -10,7 +10,7 @@ use leleka_cpu_kernels::Dispatch; use leleka_cpu_sys::mapping::Mapping; use leleka_gguf::Gguf; -use leleka_gptoss::{Model, PrefillAccelerator, State}; +use leleka_gptoss::{Model, PrefillAccelerator, PrefillSpan, State}; use leleka_gptoss_igpu::GpuPrefill; use leleka_gptoss_npu::NpuPrefill; use leleka_gptoss_npu::client::ServiceConfig; @@ -103,14 +103,14 @@ fn run_once( if prefix > 0 { split.set_npu_share(0.0); split - .prefill(model, &mut state, &ids[..prefix], 0, &mut |_| true) + .prefill(model, &mut state, PrefillSpan { tokens: &ids[..prefix], pos0: 0 }, &mut |_| true) .expect("prefix") .expect("not cancelled"); } split.set_npu_share(npu_share); let t = Instant::now(); let hidden = split - .prefill(model, &mut state, &ids[prefix..], prefix, &mut |_| true) + .prefill(model, &mut state, PrefillSpan { tokens: &ids[prefix..], pos0: prefix }, &mut |_| true) .expect("prefill") .expect("not cancelled"); let seconds = t.elapsed().as_secs_f64(); diff --git a/crates/gpu-npu-worker/src/lib.rs b/crates/gpu-npu-worker/src/lib.rs index a1d49575..1b0f086d 100644 --- a/crates/gpu-npu-worker/src/lib.rs +++ b/crates/gpu-npu-worker/src/lib.rs @@ -8,7 +8,7 @@ //! layer `l` while the NPU part runs layer `l + 1`: a two-stage pipeline with one layer of lag. Each part keeps its //! own numerics, so the result is that of the NPU path for the first tokens and of the GPU path for the rest. -use leleka_gptoss::{LayerCache, Model, ModelError, PrefillAccelerator, State}; +use leleka_gptoss::{LayerCache, Model, ModelError, PrefillAccelerator, PrefillJob, PrefillSpan, State}; use leleka_gptoss_igpu::GpuPrefill; use leleka_gptoss_npu::NpuPrefill; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; @@ -209,20 +209,22 @@ impl GpuNpuPrefill { tokens: &[u32], pos0: usize, ) -> Result, ModelError> { - Ok(self - .run(model, state, tokens, pos0, &mut |_| true, true)? - .expect("not cancelled")) + let job = PrefillJob { + model, + cache: state, + span: PrefillSpan { tokens, pos0 }, + all_hidden: true, + }; + Ok(self.run(job, &mut |_| true)?.expect("not cancelled")) } fn run( &mut self, - model: &Model, - cache: &dyn LayerCache, - tokens: &[u32], - pos0: usize, + job: PrefillJob, mut progress: &mut dyn FnMut(f64) -> bool, - all_hidden: bool, ) -> Result>, ModelError> { + let PrefillJob { model, cache, span, all_hidden } = job; + let PrefillSpan { tokens, pos0 } = span; let started = Instant::now(); let n = tokens.len(); let s = self.npu_tokens(n); @@ -252,9 +254,13 @@ impl GpuNpuPrefill { progress: &mut impl FnMut(f64) -> bool, started: Instant, ) -> Result>, ModelError> { - let out = self - .gpu - .prefill_part(job.model, second.cache, job.tokens, job.pos0, progress, job.all_hidden); + let part = PrefillJob { + model: job.model, + cache: second.cache, + span: PrefillSpan { tokens: job.tokens, pos0: job.pos0 }, + all_hidden: job.all_hidden, + }; + let out = self.gpu.prefill_part(part, progress); self.timings.gpu = started.elapsed(); self.timings.total = self.timings.gpu; out @@ -287,11 +293,11 @@ impl PrefillAccelerator for GpuNpuPrefill { &mut self, model: &Model, state: &mut State, - tokens: &[u32], - pos0: usize, + span: PrefillSpan, progress: &mut dyn FnMut(f64) -> bool, ) -> Result>, ModelError> { - let out = self.run(model, state, tokens, pos0, progress, false); + let job = PrefillJob { model, cache: state, span, all_hidden: false }; + let out = self.run(job, progress); if std::env::var_os("LELEKA_SPLIT_LOG").is_some() { eprintln!("leleka-gpu-npu: {}", self.timings.report()); } diff --git a/crates/gpu-npu-worker/src/split_run.rs b/crates/gpu-npu-worker/src/split_run.rs index aee76c5c..c3b5f0ad 100644 --- a/crates/gpu-npu-worker/src/split_run.rs +++ b/crates/gpu-npu-worker/src/split_run.rs @@ -59,21 +59,20 @@ fn run_gpu_part( (npu_done, stop): (&AtomicU64, &AtomicBool), ) -> PartOutcome { let t = Instant::now(); - let result = gpu.prefill_part( - job.model, - second, - &job.tokens[job.split..], - job.pos0 + job.split, - &mut |fraction| { - let npu_fraction = npu_done.load(Ordering::Relaxed) as f64 / 1e6; - let go_on = progress(fraction.min(npu_fraction)); - if !go_on { - stop.store(true, Ordering::Relaxed); - } - go_on - }, - job.all_hidden, - ); + let part = PrefillJob { + model: job.model, + cache: second, + span: PrefillSpan { tokens: &job.tokens[job.split..], pos0: job.pos0 + job.split }, + all_hidden: job.all_hidden, + }; + let result = gpu.prefill_part(part, &mut |fraction| { + let npu_fraction = npu_done.load(Ordering::Relaxed) as f64 / 1e6; + let go_on = progress(fraction.min(npu_fraction)); + if !go_on { + stop.store(true, Ordering::Relaxed); + } + go_on + }); let time = t.elapsed(); if !matches!(result, Ok(Some(_))) { stop.store(true, Ordering::Relaxed); @@ -90,17 +89,16 @@ fn run_npu_part( stop: &AtomicBool, ) -> PartOutcome { let t = Instant::now(); - let result = npu.prefill_part( - job.model, - first, - &job.tokens[..job.split], - job.pos0, - &mut |fraction| { - npu_done.store((fraction * 1e6) as u64, Ordering::Relaxed); - !stop.load(Ordering::Relaxed) - }, - job.all_hidden, - ); + let part = PrefillJob { + model: job.model, + cache: first, + span: PrefillSpan { tokens: &job.tokens[..job.split], pos0: job.pos0 }, + all_hidden: job.all_hidden, + }; + let result = npu.prefill_part(part, &mut |fraction| { + npu_done.store((fraction * 1e6) as u64, Ordering::Relaxed); + !stop.load(Ordering::Relaxed) + }); if !matches!(result, Ok(Some(_))) { first.handoff.abandon(); } diff --git a/crates/igpu/examples/attn_bench.rs b/crates/igpu/examples/attn_bench.rs index ad2619b9..2280653e 100644 --- a/crates/igpu/examples/attn_bench.rs +++ b/crates/igpu/examples/attn_bench.rs @@ -3,7 +3,7 @@ //! //! Reports milliseconds for one layer's attention over a batch of `m` tokens ending at position `end`. -use leleka_igpu::{AttentionShape, Buf, Gpu}; +use leleka_igpu::{AttentionBufs, AttentionShape, Buf, Gpu}; /// Time five runs of one layer's attention over a batch of `m` tokens ending at `end`. fn time_case(gpu: &Gpu, caches: &Caches, (end, m, window): (usize, usize, usize)) { @@ -18,11 +18,11 @@ fn time_case(gpu: &Gpu, caches: &Caches, (end, m, window): (usize, usize, usize) q_width: qw, scale: 0.125, }; + let bufs = AttentionBufs { queries: &q, keys: &caches.k, values: &caches.v, sinks: &caches.sinks, out: &out }; let run = |count: usize| { let mut rec = gpu.recorder(); for _ in 0..count { - rec.attention(shape, &q, &caches.k, &caches.v, &caches.sinks, &out) - .unwrap(); + rec.attention(shape, bufs).unwrap(); } rec.submit().unwrap(); }; diff --git a/crates/igpu/src/lib.rs b/crates/igpu/src/lib.rs index 03876511..374f33bf 100644 --- a/crates/igpu/src/lib.rs +++ b/crates/igpu/src/lib.rs @@ -27,6 +27,8 @@ mod handles; pub use handles::{Buf, GpuActivations, GpuMatrix}; mod params; pub use params::AttentionShape; +pub use params::{AttentionBufs, CombineBufs, KvStoreShape, NormBufs, NormShape, Operands, ProductOutput}; +pub use params::{RopeShape, RouterBufs, SwigluBufs}; pub use params::MoePlan; use params::SwigluUniform; use params::{AttentionParams, Quad}; diff --git a/crates/igpu/src/matrices_and_moe_plan.rs b/crates/igpu/src/matrices_and_moe_plan.rs index 74c8e8d8..833c4806 100644 --- a/crates/igpu/src/matrices_and_moe_plan.rs +++ b/crates/igpu/src/matrices_and_moe_plan.rs @@ -162,7 +162,7 @@ impl Gpu { } let out = self.zeros(a.m * w.rows); let mut rec = self.recorder(); - rec.matmul(w, a, &out, None, false)?; + rec.matmul(Operands { w, a }, ProductOutput { out: &out, bias: None }, false)?; rec.submit()?; self.read_f32(&out) } @@ -177,7 +177,7 @@ impl Gpu { let run = |count: usize| -> Result<(), GpuError> { let mut rec = self.recorder(); for _ in 0..count { - rec.matmul(w, a, &out, None, false)?; + rec.matmul(Operands { w, a }, ProductOutput { out: &out, bias: None }, false)?; } rec.submit() }; diff --git a/crates/igpu/src/params.rs b/crates/igpu/src/params.rs index 1937f47b..ee71ceb5 100644 --- a/crates/igpu/src/params.rs +++ b/crates/igpu/src/params.rs @@ -35,6 +35,90 @@ pub struct AttentionShape { pub scale: f32, } +/// The buffers of an attention call (see [`Recorder::attention`]). +#[derive(Clone, Copy)] +pub struct AttentionBufs<'a> { + pub queries: &'a Buf, + pub keys: &'a Buf, + pub values: &'a Buf, + pub sinks: &'a Buf, + pub out: &'a Buf, +} + +/// A weight matrix and the quantized activations it multiplies. +#[derive(Clone, Copy)] +pub struct Operands<'a> { + pub w: &'a GpuMatrix, + pub a: &'a GpuActivations, +} + +/// The output buffer of a product with its optional bias. +#[derive(Clone, Copy)] +pub struct ProductOutput<'a> { + pub out: &'a Buf, + pub bias: Option<&'a Buf>, +} + +/// The shape of a RoPE pass: `token_count` tokens of `head_count` heads of `head_dim` floats each. +#[derive(Clone, Copy, Debug)] +pub struct RopeShape { + pub token_count: usize, + pub head_count: usize, + pub head_dim: usize, +} + +/// The shape of a KV store: `row_count` rows of `kv_width` floats into the cache at positions `first_position..`. +#[derive(Clone, Copy, Debug)] +pub struct KvStoreShape { + pub row_count: usize, + pub kv_width: usize, + pub first_position: usize, +} + +/// The buffers of the weighted combine of expert outputs: the compact `down` rows, the experts' weights and the +/// residual `x` they are added to. +#[derive(Clone, Copy)] +pub struct CombineBufs<'a> { + pub down: &'a Buf, + pub expert_weights: &'a Buf, + pub x: &'a Buf, +} + +/// The buffers of an RMSNorm-and-quantize pass. +#[derive(Clone, Copy)] +pub struct NormBufs<'a> { + pub x: &'a Buf, + pub weight: &'a Buf, + pub normalized: &'a Buf, + pub act: &'a GpuActivations, +} + +/// The shape of an RMSNorm-and-quantize pass: `row_count` rows of `width` floats, with the `epsilon`. +#[derive(Clone, Copy, Debug)] +pub struct NormShape { + pub epsilon: f32, + pub row_count: usize, + pub width: usize, +} + +/// The buffers of a SwiGLU-and-quantize pass. +#[derive(Clone, Copy)] +pub struct SwigluBufs<'a> { + pub gate: &'a Buf, + pub up: &'a Buf, + pub act: &'a GpuActivations, +} + +/// The buffers of a router pass: the input rows, the router weights and bias, and the chosen ids and weights. +#[derive(Clone, Copy)] +pub struct RouterBufs<'a> { + pub h: &'a Buf, + pub weights: &'a Buf, + pub bias: &'a Buf, + pub ids: &'a Buf, + pub expert_weights: &'a Buf, +} + #[repr(C)] #[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)] pub(super) struct AttentionParams { diff --git a/crates/igpu/src/recorder_attention_and_submit.rs b/crates/igpu/src/recorder_attention_and_submit.rs index 9a2aacdd..4f5996e1 100644 --- a/crates/igpu/src/recorder_attention_and_submit.rs +++ b/crates/igpu/src/recorder_attention_and_submit.rs @@ -68,7 +68,8 @@ impl Recorder<'_> { /// Rotate `m` tokens' `heads` heads of `hd` floats each in place with the per-token `(cos, sin)` table /// `rot` (`[m][hd / 2][2]`). - pub fn rope(&mut self, x: &Buf, rot: &Buf, m: usize, heads: usize, hd: usize) -> Result<(), GpuError> { + pub fn rope(&mut self, x: &Buf, rot: &Buf, shape: RopeShape) -> Result<(), GpuError> { + let RopeShape { token_count: m, head_count: heads, head_dim: hd } = shape; if hd == 0 || !hd.is_multiple_of(2) || x.len < m * heads * hd || rot.len < m * hd { return Err(GpuError::Shape(format!("rope of {m} x {heads} x {hd}"))); } @@ -88,7 +89,8 @@ impl Recorder<'_> { } /// Store `m` rows of `kw` floats as half precision into `cache` at positions `pos0..`. - pub fn kv_store(&mut self, src: &Buf, cache: &Buf, m: usize, kw: usize, pos0: usize) -> Result<(), GpuError> { + pub fn kv_store(&mut self, src: &Buf, cache: &Buf, shape: KvStoreShape) -> Result<(), GpuError> { + let KvStoreShape { row_count: m, kv_width: kw, first_position: pos0 } = shape; if kw == 0 || !kw.is_multiple_of(2) || src.len < m * kw || cache.len < (pos0 + m) * kw / 2 { return Err(GpuError::Shape(format!("kv store of {m} x {kw} at position {pos0}"))); } @@ -111,15 +113,8 @@ impl Recorder<'_> { /// per KV head. `queries` and `out` are `[m][q_width]`; the caches hold `[position][kv_width]` halves /// (two per word) and must already contain the keys and values of positions up to `pos0 + m - 1`; /// `sinks` has one logit per query head. - pub fn attention( - &mut self, - shape: AttentionShape, - queries: &Buf, - keys: &Buf, - values: &Buf, - sinks: &Buf, - out: &Buf, - ) -> Result<(), GpuError> { + pub fn attention(&mut self, shape: AttentionShape, bufs: AttentionBufs) -> Result<(), GpuError> { + let AttentionBufs { queries, keys, values, sinks, out } = bufs; check_attention(shape, (queries, keys, values), (sinks, out))?; let gpu = self.gpu; self.run_simple( diff --git a/crates/igpu/src/recorder_core.rs b/crates/igpu/src/recorder_core.rs index bb2a19a0..3d88ceb5 100644 --- a/crates/igpu/src/recorder_core.rs +++ b/crates/igpu/src/recorder_core.rs @@ -92,28 +92,21 @@ impl Recorder<'_> { /// `out[m][n] = a x w^T`, plus `bias[n]` when given, plus the previous contents of `out` when /// `accumulate` is set (the residual add of a projection). - pub fn matmul( - &mut self, - w: &GpuMatrix, - a: &GpuActivations, - out: &Buf, - bias: Option<&Buf>, - accumulate: bool, - ) -> Result<(), GpuError> { - self.matmul_rows(w, a, a.m, out, bias, accumulate) + pub fn matmul(&mut self, ops: Operands, out: ProductOutput, accumulate: bool) -> Result<(), GpuError> { + self.matmul_rows(ops, ops.a.m, out, accumulate) } /// As [`Recorder::matmul`] for the first `m` rows of `a` (scratch activations are sized for the largest /// batch). pub fn matmul_rows( &mut self, - w: &GpuMatrix, - a: &GpuActivations, + ops: Operands, m: usize, - out: &Buf, - bias: Option<&Buf>, + io: ProductOutput, accumulate: bool, ) -> Result<(), GpuError> { + let Operands { w, a } = ops; + let ProductOutput { out, bias } = io; check_matmul(w, a, m, out, bias)?; let n = w.rows; let flags = u32::from(bias.is_some()) | (u32::from(accumulate) << 1); diff --git a/crates/igpu/src/recorder_moe.rs b/crates/igpu/src/recorder_moe.rs index 2f9c9b00..7717557a 100644 --- a/crates/igpu/src/recorder_moe.rs +++ b/crates/igpu/src/recorder_moe.rs @@ -58,13 +58,13 @@ impl Recorder<'_> { /// else row `i` of `a`, times the rows of its expert; plus the expert's slice of `bias` when given. pub fn moe_matmul( &mut self, - w: &GpuMatrix, - a: &GpuActivations, + ops: Operands, plan: &MoePlan, gather: bool, - bias: Option<&Buf>, - out: &Buf, + io: ProductOutput, ) -> Result<(), GpuError> { + let Operands { w, a } = ops; + let ProductOutput { out, bias } = io; let n = check_moe_matmul(w, a, plan, gather, (bias, out))?; if plan.entries == 0 { return Ok(()); @@ -85,14 +85,8 @@ impl Recorder<'_> { /// Add each token's weighted expert outputs (`down`, compact `[entries][e]`) to its residual row of `x`, /// in slot order. - pub fn moe_combine( - &mut self, - down: &Buf, - plan: &MoePlan, - expert_weights: &Buf, - x: &Buf, - e: usize, - ) -> Result<(), GpuError> { + pub fn moe_combine(&mut self, plan: &MoePlan, bufs: CombineBufs, e: usize) -> Result<(), GpuError> { + let CombineBufs { down, expert_weights, x } = bufs; let m = plan.tokens; if down.len < plan.entries * e || expert_weights.len < m * plan.used || x.len < m * e { return Err(GpuError::Shape(format!("moe combine of {m} x {e}"))); diff --git a/crates/igpu/src/recorder_norm_and_routing.rs b/crates/igpu/src/recorder_norm_and_routing.rs index cff79f36..80039920 100644 --- a/crates/igpu/src/recorder_norm_and_routing.rs +++ b/crates/igpu/src/recorder_norm_and_routing.rs @@ -54,17 +54,9 @@ fn check_router( impl Recorder<'_> { /// RMSNorm of `x` (`rows` rows of `e` floats) with `weight`, written to `normalized` and quantized to /// Q8_0 into `act` (which must have at least `rows` rows and `e` columns). - #[allow(clippy::too_many_arguments)] // mirrors the kernel's bindings - pub fn rmsnorm_quant( - &mut self, - x: &Buf, - weight: &Buf, - eps: f32, - rows: usize, - e: usize, - normalized: &Buf, - act: &GpuActivations, - ) -> Result<(), GpuError> { + pub fn rmsnorm_quant(&mut self, bufs: NormBufs, shape: NormShape) -> Result<(), GpuError> { + let NormBufs { x, weight, normalized, act } = bufs; + let NormShape { epsilon: eps, row_count: rows, width: e } = shape; check_norm((x, weight, normalized), rows, e, act)?; let params = self.uniform(&NormParams { m: rows as u32, @@ -111,13 +103,12 @@ impl Recorder<'_> { /// The expert activation of `gate` and `up` (`rows` x `n` each) quantized to Q8_0 into `act`. pub fn swiglu_quant( &mut self, - gate: &Buf, - up: &Buf, + bufs: SwigluBufs, rows: usize, n: usize, activation: SwigluParams, - act: &GpuActivations, ) -> Result<(), GpuError> { + let SwigluBufs { gate, up, act } = bufs; check_swiglu((gate, up), rows, n, act)?; let gpu = self.gpu; self.run_simple( @@ -137,17 +128,8 @@ impl Recorder<'_> { } /// Router logits and top-4 selection for 32 experts: `ids` and `weights` receive `[m][4]` entries. - #[allow(clippy::too_many_arguments)] // mirrors the kernel's bindings - pub fn router( - &mut self, - h: &Buf, - weights: &Buf, - bias: &Buf, - m: usize, - e: usize, - ids: &Buf, - expert_weights: &Buf, - ) -> Result<(), GpuError> { + pub fn router(&mut self, bufs: RouterBufs, m: usize, e: usize) -> Result<(), GpuError> { + let RouterBufs { h, weights, bias, ids, expert_weights } = bufs; check_router((h, weights, bias), (m, e), (ids, expert_weights))?; let gpu = self.gpu; self.run_simple( diff --git a/crates/igpu/tests/attention.rs b/crates/igpu/tests/attention.rs index 25dd578f..f9333739 100644 --- a/crates/igpu/tests/attention.rs +++ b/crates/igpu/tests/attention.rs @@ -8,7 +8,7 @@ use leleka_cpu_kernels::Dispatch; use leleka_gptoss::ops::{self, Group, KvRows, Yarn}; -use leleka_igpu::{AttentionShape, Gpu}; +use leleka_igpu::{AttentionBufs, AttentionShape, Gpu, KvStoreShape, RopeShape}; struct Rng(u64); @@ -65,7 +65,7 @@ fn rope_matches_the_decoders_rotation() { let flat: Vec = table.iter().flat_map(|(c, s)| [*c, *s]).collect(); let (xb, rb) = (gpu.buf_f32(&x), gpu.buf_f32(&flat)); let mut rec = gpu.recorder(); - rec.rope(&xb, &rb, m, heads, hd).unwrap(); + rec.rope(&xb, &rb, RopeShape { token_count: m, head_count: heads, head_dim: hd }).unwrap(); rec.submit().unwrap(); let got = gpu.read_f32(&xb).unwrap(); let mut want = x.clone(); @@ -94,7 +94,7 @@ fn kv_store_rounds_to_half_like_the_cpu() { let cache = gpu.zeros((pos0 + m + 2) * kw / 2); let src = gpu.buf_f32(&x); let mut rec = gpu.recorder(); - rec.kv_store(&src, &cache, m, kw, pos0).unwrap(); + rec.kv_store(&src, &cache, KvStoreShape { row_count: m, kv_width: kw, first_position: pos0 }).unwrap(); rec.submit().unwrap(); let words = gpu.read_u32(&cache).unwrap(); assert!(words[..pos0 * kw / 2].iter().all(|w| *w == 0)); @@ -166,7 +166,8 @@ fn gpu_attention(gpu: &Gpu, data: &AttnData, (pos0, m, window): (usize, usize, u q_width: QW, scale, }; - rec.attention(shape, &qb, &kb, &vb, &sb, &out).unwrap(); + let bufs = AttentionBufs { queries: &qb, keys: &kb, values: &vb, sinks: &sb, out: &out }; + rec.attention(shape, bufs).unwrap(); rec.submit().unwrap(); gpu.read_f32(&out).unwrap() } @@ -193,8 +194,9 @@ fn cpu_head(d: &Dispatch, data: &AttnData, window: usize, pos: usize, kvh: usize keys: &data.kh[start..], values: &data.vh[start..], stride: KW, + n: attended, }; - ops::attend_group_with_sink(queries, kv, attended, d, &mut scores, &mut want).unwrap(); + ops::attend_group_with_sink(queries, kv, d, &mut scores, &mut want).unwrap(); want } @@ -252,8 +254,9 @@ fn attention_refuses_shapes_it_does_not_implement() { q_width, scale: 0.125, }; - assert!(rec.attention(shape(64, 512), &q, &c, &c, &s, &o).is_ok()); - assert!(rec.attention(shape(64, 256), &q, &c, &c, &s, &o).is_err()); // group is not 8 - assert!(rec.attention(shape(60, 480), &q, &c, &c, &s, &o).is_err()); // head dim is not 64 + let bufs = AttentionBufs { queries: &q, keys: &c, values: &c, sinks: &s, out: &o }; + assert!(rec.attention(shape(64, 512), bufs).is_ok()); + assert!(rec.attention(shape(64, 256), bufs).is_err()); // group is not 8 + assert!(rec.attention(shape(60, 480), bufs).is_err()); // head dim is not 64 rec.submit().unwrap(); } diff --git a/crates/igpu/tests/gemm.rs b/crates/igpu/tests/gemm.rs index 5d27e8e9..51cb2706 100644 --- a/crates/igpu/tests/gemm.rs +++ b/crates/igpu/tests/gemm.rs @@ -6,7 +6,7 @@ use leleka_cpu_kernels::Dispatch; use leleka_cpu_sys::simd::{e8m0_half, f16_to_f32}; -use leleka_igpu::{Gpu, WeightKind}; +use leleka_igpu::{Gpu, Operands, ProductOutput, WeightKind}; struct Rng(u64); @@ -94,7 +94,15 @@ fn exact_output( (exact, magnitude) } -fn check(gpu: &Gpu, kind: WeightKind, m: usize, n: usize, blocks: usize, seed: u64) { +/// The size of a product: `m` activation rows, `n` weight rows, `blocks` blocks per row. +struct ProductSize { + activation_rows: usize, + weight_rows: usize, + blocks: usize, +} + +fn check(gpu: &Gpu, kind: WeightKind, shape: ProductSize, seed: u64) { + let ProductSize { activation_rows: m, weight_rows: n, blocks } = shape; let d = Dispatch::best(); let mut rng = Rng(seed); let (w, block_bytes) = match kind { @@ -134,14 +142,8 @@ fn q8_0_products_match_the_cpu_kernels_on_awkward_shapes() { (65, 129, 3), (7, 200, 11), ] { - check( - &gpu, - WeightKind::Q8_0, - m, - n, - blocks, - 1000 + (m * 31 + n) as u64, - ); + let shape = ProductSize { activation_rows: m, weight_rows: n, blocks }; + check(&gpu, WeightKind::Q8_0, shape, 1000 + (m * 31 + n) as u64); } } @@ -156,14 +158,8 @@ fn mxfp4_products_match_the_cpu_kernels_on_awkward_shapes() { (65, 129, 3), (7, 200, 11), ] { - check( - &gpu, - WeightKind::Mxfp4, - m, - n, - blocks, - 2000 + (m * 31 + n) as u64, - ); + let shape = ProductSize { activation_rows: m, weight_rows: n, blocks }; + check(&gpu, WeightKind::Mxfp4, shape, 2000 + (m * 31 + n) as u64); } } @@ -233,8 +229,8 @@ fn run_epilogue( let bias_buf = gpu.buf_f32(bias); let out = gpu.buf_f32(start); let mut rec = gpu.recorder(); - rec.matmul(wm, am, &out, use_bias.then_some(&bias_buf), accumulate) - .unwrap(); + let io = ProductOutput { out: &out, bias: use_bias.then_some(&bias_buf) }; + rec.matmul(Operands { w: wm, a: am }, io, accumulate).unwrap(); rec.submit().unwrap(); gpu.read_f32(&out).unwrap() } diff --git a/crates/igpu/tests/moe.rs b/crates/igpu/tests/moe.rs index 45c0f8ee..9f66d9de 100644 --- a/crates/igpu/tests/moe.rs +++ b/crates/igpu/tests/moe.rs @@ -6,7 +6,9 @@ use leleka_cpu_kernels::Dispatch; use leleka_cpu_sys::simd::{e8m0_half, f16_to_f32}; use leleka_gptoss::ops; -use leleka_igpu::{Gpu, MoePlan, SwigluParams, WeightKind}; +use leleka_igpu::{ + CombineBufs, Gpu, MoePlan, Operands, ProductOutput, RouterBufs, SwigluBufs, SwigluParams, WeightKind, +}; struct Rng(u64); @@ -100,7 +102,8 @@ fn swiglu_quant_matches_the_cpu_activation() { let (gb, ub) = (gpu.buf_f32(&gate), gpu.buf_f32(&up)); let out = gpu.new_activations(rows, n).unwrap(); let mut rec = gpu.recorder(); - rec.swiglu_quant(&gb, &ub, rows, n, SwigluParams { alpha, limit }, &out) + let bufs = SwigluBufs { gate: &gb, up: &ub, act: &out }; + rec.swiglu_quant(bufs, rows, n, SwigluParams { alpha, limit }) .unwrap(); rec.submit().unwrap(); compare_quantized(&gpu, &out, &cpu, "swiglu"); @@ -118,7 +121,8 @@ fn router_picks_the_cpu_experts_and_weights() { let (hb, wb, bb) = (gpu.buf_f32(&h), gpu.buf_f32(&w), gpu.buf_f32(&bias)); let (ids, weights) = (gpu.zeros(m * 4), gpu.zeros(m * 4)); let mut rec = gpu.recorder(); - rec.router(&hb, &wb, &bb, m, e, &ids, &weights).unwrap(); + let bufs = RouterBufs { h: &hb, weights: &wb, bias: &bb, ids: &ids, expert_weights: &weights }; + rec.router(bufs, m, e).unwrap(); rec.submit().unwrap(); let (got_ids, got_w) = (gpu.read_u32(&ids).unwrap(), gpu.read_f32(&weights).unwrap()); for t in 0..m { @@ -232,7 +236,8 @@ fn check_expert_products(gpu: &Gpu, d: &Dispatch, inp: &MoeInputs, plan: &MoePla let am = gpu.upload_activations(M, BLOCKS * 32, &inp.a).unwrap(); let out = gpu.zeros(plan.entries() * N); let mut rec = gpu.recorder(); - rec.moe_matmul(&wm, &am, plan, true, Some(&bb), &out) + let io = ProductOutput { out: &out, bias: Some(&bb) }; + rec.moe_matmul(Operands { w: &wm, a: &am }, plan, true, io) .unwrap(); rec.submit().unwrap(); let got = gpu.read_f32(&out).unwrap(); @@ -280,7 +285,8 @@ fn check_combine(gpu: &Gpu, rng: &mut Rng, inp: &MoeInputs, plan: &MoePlan) { gpu.buf_f32(&resid), ); let mut rec = gpu.recorder(); - rec.moe_combine(&db, plan, &wb, &xb, E).unwrap(); + let bufs = CombineBufs { down: &db, expert_weights: &wb, x: &xb }; + rec.moe_combine(plan, bufs, E).unwrap(); rec.submit().unwrap(); let got = gpu.read_f32(&xb).unwrap(); let entry_of = entry_indices(&inp.chosen); diff --git a/crates/igpu/tests/norm.rs b/crates/igpu/tests/norm.rs index a7d54940..73aeecb8 100644 --- a/crates/igpu/tests/norm.rs +++ b/crates/igpu/tests/norm.rs @@ -10,7 +10,7 @@ use leleka_cpu_kernels::Dispatch; use leleka_cpu_sys::simd::f16_to_f32; use leleka_gptoss::ops::rms_norm; -use leleka_igpu::Gpu; +use leleka_igpu::{Gpu, NormBufs, NormShape}; struct Rng(u64); @@ -38,8 +38,8 @@ fn run_gpu_norm(gpu: &Gpu, x: &[f32], w: &[f32], (rows, e): (usize, usize), eps: let normalized = gpu.zeros(rows * e); let act = gpu.new_activations(rows, e).unwrap(); let mut rec = gpu.recorder(); - rec.rmsnorm_quant(&xb, &wb, eps, rows, e, &normalized, &act) - .unwrap(); + let bufs = NormBufs { x: &xb, weight: &wb, normalized: &normalized, act: &act }; + rec.rmsnorm_quant(bufs, NormShape { epsilon: eps, row_count: rows, width: e }).unwrap(); rec.submit().unwrap(); let h = gpu.read_f32(&normalized).unwrap(); let (words, scales) = gpu.read_activations(&act).unwrap(); @@ -128,8 +128,9 @@ fn zero_rows_quantize_to_zero_without_nan() { let normalized = gpu.zeros(e); let act = gpu.new_activations(1, e).unwrap(); let mut rec = gpu.recorder(); - rec.rmsnorm_quant(&xb, &wb, 1e-5, 1, e, &normalized, &act) - .unwrap(); + let bufs = NormBufs { x: &xb, weight: &wb, normalized: &normalized, act: &act }; + let shape = NormShape { epsilon: 1e-5, row_count: 1, width: e }; + rec.rmsnorm_quant(bufs, shape).unwrap(); rec.submit().unwrap(); assert!(gpu.read_f32(&normalized).unwrap().iter().all(|v| *v == 0.0)); let (words, scales) = gpu.read_activations(&act).unwrap(); diff --git a/crates/igpu/tests/real_weights.rs b/crates/igpu/tests/real_weights.rs index f9ef905c..7d3dc73b 100644 --- a/crates/igpu/tests/real_weights.rs +++ b/crates/igpu/tests/real_weights.rs @@ -60,7 +60,15 @@ fn random_activations(d: &Dispatch, m: usize, blocks: usize) -> Vec { a } -fn compare(gpu: &Gpu, kind: WeightKind, weights: &[u8], rows: usize, m: usize, label: &str) { +/// The raw bytes of a weight matrix of `rows` rows, with the block kind they are in. +struct WeightBytes<'a> { + kind: WeightKind, + bytes: &'a [u8], + rows: usize, +} + +fn compare(gpu: &Gpu, matrix: WeightBytes, m: usize, label: &str) { + let WeightBytes { kind, bytes: weights, rows } = matrix; let blocks = 90; let block_bytes = if kind == WeightKind::Q8_0 { 34 } else { 17 }; assert_eq!(weights.len(), rows * blocks * block_bytes, "{label}"); @@ -100,7 +108,8 @@ fn open_model(path: &Path) -> (Gguf, Mapping) { fn compare_expert(gpu: &Gpu, all: &[u8], index: usize, m: usize, label: &str) { let expert = 2880 * 90 * 17; let weights = &all[index * expert..(index + 1) * expert]; - compare(gpu, WeightKind::Mxfp4, weights, 2880, m, label); + let matrix = WeightBytes { kind: WeightKind::Mxfp4, bytes: weights, rows: 2880 }; + compare(gpu, matrix, m, label); } #[test] @@ -123,7 +132,8 @@ fn real_attention_and_expert_weights_match_the_cpu_kernels() { // attention query projection of layer 3 (Q8_0): 4096 rows of 2880 let (q, dims) = tensor("blk.3.attn_q.weight"); assert_eq!(dims, vec![2880, 4096]); - compare(&gpu, WeightKind::Q8_0, q, 4096, 37, "blk.3.attn_q (Q8_0)"); + let matrix = WeightBytes { kind: WeightKind::Q8_0, bytes: q, rows: 4096 }; + compare(&gpu, matrix, 37, "blk.3.attn_q (Q8_0)"); // one expert's gate and up projections of layer 5 (MXFP4): 2880 rows of 2880 each let (gate, dims) = tensor("blk.5.ffn_gate_exps.weight"); assert_eq!(dims, vec![2880, 2880, 32]); diff --git a/crates/npu-service/tests/service.rs b/crates/npu-service/tests/service.rs index 0b102cb4..033f035e 100644 --- a/crates/npu-service/tests/service.rs +++ b/crates/npu-service/tests/service.rs @@ -230,7 +230,16 @@ fn read_output(svc: &mut Service, out_off: usize, (rows, n): (usize, usize), shi (out, shifts) } -fn compare(env: &Env, svc: &mut Service, name: &str, expert: Option, rows: usize, seed: u64) { +/// One product to check: the tensor (and expert of a stacked one), the activation rows and the seed that makes them. +struct ProductCheck<'a> { + name: &'a str, + expert: Option, + rows: usize, + seed: u64, +} + +fn compare(env: &Env, svc: &mut Service, case: ProductCheck) { + let ProductCheck { name, expert, rows, seed } = case; let info_dims = tensor_dims(env, name); let (n, first) = match expert { None => (info_dims[1..].iter().product::() as usize, 0), @@ -266,13 +275,13 @@ fn products_match_the_dequantized_reference() { let mut svc = Service::start(&env); assert_eq!(svc.ask("PING"), "PONG"); // Q8_0 attention weights, a row count that is not a bucket - compare(&env, &mut svc, "blk.0.attn_k.weight", None, 37, 1); - compare(&env, &mut svc, "blk.0.attn_q.weight", None, 37, 5); - compare(&env, &mut svc, "blk.0.attn_output.weight", None, 37, 6); + compare(&env, &mut svc, ProductCheck { name: "blk.0.attn_k.weight", expert: None, rows: 37, seed: 1 }); + compare(&env, &mut svc, ProductCheck { name: "blk.0.attn_q.weight", expert: None, rows: 37, seed: 5 }); + compare(&env, &mut svc, ProductCheck { name: "blk.0.attn_output.weight", expert: None, rows: 37, seed: 6 }); // MXFP4 experts: two different experts, then the first again (reload), another row count - compare(&env, &mut svc, "blk.2.ffn_down_exps.weight", Some(5), 70, 2); - compare(&env, &mut svc, "blk.2.ffn_down_exps.weight", Some(9), 70, 3); - compare(&env, &mut svc, "blk.2.ffn_down_exps.weight", Some(5), 33, 4); + compare(&env, &mut svc, ProductCheck { name: "blk.2.ffn_down_exps.weight", expert: Some(5), rows: 70, seed: 2 }); + compare(&env, &mut svc, ProductCheck { name: "blk.2.ffn_down_exps.weight", expert: Some(9), rows: 70, seed: 3 }); + compare(&env, &mut svc, ProductCheck { name: "blk.2.ffn_down_exps.weight", expert: Some(5), rows: 33, seed: 4 }); // errors are replies, not crashes assert!(svc.ask("MM blk.0.nope.weight - 4 0 8").starts_with("ERR")); assert!(svc.ask("MM blk.0.attn_k.weight - 5000 0 8").starts_with("ERR"));