Merge branch 'claude/par-p04' into claude/hexagonal-finish-14ee3a

This commit is contained in:
Pavlo Ratushnyi
2026-11-08 01:17:15 +01:00
64 changed files with 997 additions and 610 deletions
+5 -7
View File
@@ -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!(
@@ -12,7 +12,7 @@ use super::experimental_gpu::{
};
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},
@@ -132,7 +132,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 { 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 {
return (name, m);
@@ -318,11 +320,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,
query_count: STREAM_QUERIES as usize,
capacity: STREAM_CAP as usize,
page_size: 4,
},
&leleka_experimental_ref::kv_stream::MissOrder::Canonical,
)
.expect("cpu resolve");
+36 -19
View File
@@ -29,31 +29,46 @@ 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;
/// 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<f64> {
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 head counts and the number of attended cells of one reference attention.
#[derive(Clone, Copy, Debug)]
pub struct ReferenceAttentionShape {
pub head_count: usize,
pub kv_head_count: usize,
pub attended_count: usize,
}
/// 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<f64> {
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>() * 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<f64> {
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>() * 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<f64> = 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]);
}
@@ -96,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, nh, nkv, 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);
}
@@ -110,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, nh, nkv, 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);
}
}
+75 -62
View File
@@ -114,13 +114,49 @@ 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],
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, head_dim: 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.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;
}
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 page_table: &'a [i32],
pub position: 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 +176,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 { 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);
@@ -174,16 +208,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<Q8Slabs>, at: CellAt, x: &[f32]) -> Result<(), CacheError> {
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);
@@ -196,10 +222,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 +233,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),
}
+25 -7
View File
@@ -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 { page_table: &table, position: 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 { 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));
// 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 { page_table: &table, position: 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 { 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));
}
@@ -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 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
/// `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 { 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];
+23 -20
View File
@@ -136,7 +136,17 @@ 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 {
embedding_width: usize,
stream_count: usize,
steered_layer: usize,
layer_count: usize,
}
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);
@@ -154,17 +164,8 @@ fn tables(mode: CvecMode, n: usize, hc: usize, layer: usize, l: usize, scale: f3
}
}
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]
@@ -172,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<f32> = (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 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(&mut r, &tp, false, 2, t_count, r_ld, 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(&mut r, &tp, true, 1, t_count, r_ld, 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, n, hc, 2, 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(&mut r, tp, true, 2, t_count, r_ld, 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)
@@ -203,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(&mut r, ta, true, 2, t_count, r_ld, 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 {
@@ -219,9 +221,10 @@ fn pending_write_is_applied_even_when_the_vector_is_off() {
let r0: Vec<f32> = (0..hc * n).map(|i| (i % 11) as f32 * 0.1).collect();
let bo: Vec<f32> = (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 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(&mut r, &tp, false, 2, 1, hc * n, 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 {
+21 -2
View File
@@ -84,6 +84,25 @@ pub enum MissOrder {
Observed(Vec<i32>),
}
/// 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 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 first_block: usize,
pub end_block: usize,
pub slot_count: usize,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ResolveReport {
pub epoch: i32,
@@ -122,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::*;
@@ -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 };
@@ -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<ResolveReport, StreamError> {
/// One `resolve_kernel` call over the selections of `batch`.
pub fn resolve(&mut self, batch: ResolveBatch, order: &MissOrder) -> Result<ResolveReport, StreamError> {
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<i32>), StreamError> {
fn claim_misses(&mut self, batch: &ResolveBatch, epoch: i32) -> Result<(usize, Vec<i32>), StreamError> {
let ResolveBatch { ids, steps, query_count: n_q, capacity: cap, page_size } = *batch;
let mut lookups = 0usize;
let mut misses: Vec<i32> = Vec::new();
for q in 0..n_q {
@@ -231,15 +216,8 @@ pub fn ring_table(n_blocks: usize, n_slots: usize) -> Vec<i32> {
/// `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 { 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");
+25 -15
View File
@@ -4,6 +4,11 @@ use super::*;
const S: QsaShapes = QsaShapes::real();
/// 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]
fn plan_matches_the_documented_modes() {
let sw = PlanSwitches::default();
@@ -67,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(&ids, &steps, n_q, cap, 4, &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
@@ -92,9 +97,9 @@ fn eviction_keeps_the_map_consistent_and_counters_add_up() {
// a repeated call is all hits
let ids: Vec<i32> = (0..40).collect();
let steps = [0, 0, 0, 40];
map.resolve(&ids, &steps, 1, 40, 4, &MissOrder::Canonical).unwrap();
map.resolve(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(resolve_batch(&ids, &steps, 1, 40), &MissOrder::Canonical).unwrap();
assert_eq!(r.misses, 0);
assert_eq!(map.counters().misses, before);
}
@@ -107,14 +112,14 @@ fn a_slot_used_by_the_call_is_never_a_victim() {
let first = chunk * 40;
let ids: Vec<i32> = (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(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<i32> = (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(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 +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(&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(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();
@@ -142,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(&sorted, &steps, 1, sorted.len(), 4, &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)
);
}
@@ -152,10 +157,8 @@ fn too_many_distinct_blocks_for_the_slots_is_refused() {
let mut map = StreamMap::new(5000, 1024);
let ids: Vec<i32> = (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)
);
let refused = map.resolve(resolve_batch(&ids, &steps, 1, ids.len()), &MissOrder::Canonical);
assert_eq!(refused, Err(StreamError::CallTooLarge));
}
#[test]
@@ -171,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, 6, 10, 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;
@@ -182,8 +185,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);
+51 -19
View File
@@ -127,22 +127,41 @@ impl RemotePlan {
}
}
/// The remote device of `plan_open`: its index, the visible device count and its free memory.
#[derive(Clone, Copy, Debug)]
pub struct RemoteDevice {
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: RemoteDevice,
shape: OpenShape,
candidates: Candidates,
sizes: &ExpertSizes,
) -> Result<RemotePlan, RemoteError> {
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()) {
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 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
/// 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<Dispatch, RemoteError> {
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);
if plan.layers_present[layer as usize] == 0 {
@@ -2,6 +2,33 @@
use super::*;
/// 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 }
}
/// The slot count and table size of a test tier.
fn open_shape(slots: i32, layers: i64, experts: i64) -> OpenShape {
OpenShape { slots, layers, experts }
}
/// 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],
) -> Candidates<'a> {
Candidates { ranked, primary_has, claimed }
}
/// 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 {
ExpertSizes { native: false, max_blob: 1_382_400, blob_bytes: Vec::new() }
}
@@ -23,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(1, 2, 24 << 30, 3, 4, 8, &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);
@@ -51,28 +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(1, 2, need, 2, 4, 8, &[(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(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);
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(1, 2, 1 << 40, 2, 4, 8, &[(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(1, 2, 512 << 20, 2, 4, 8, &[(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),
@@ -87,7 +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(1, 2, 1 << 30, 3, 4, 2, &[(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);
}
@@ -96,7 +137,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(
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()
}
#[test]
@@ -106,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, 2, 10, None, None).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]);
@@ -124,19 +171,19 @@ fn dispatch_respects_kind_primary_residency_and_missing_layers() {
let ids: Vec<i32> = 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_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, 1, 10, None, 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, 1, 10, None, None).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], 1, 10, None, None).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);
}
@@ -147,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, n_tok, k, None, None),
dispatch(&plan, layer, &ids, route_shape(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_shape(8, 10), NO_PRIMARY).is_ok());
}
#[test]
fn meta_image_and_scatter() {
let plan = plan_for_dispatch();
let ids: Vec<i32> = 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_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);
@@ -184,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], 1, 10, None, None).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));
}
@@ -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<f32>) -> Vec<f32> {
deq(ids)
}
fn check_attention(
name: &str,
got: &[f32],
q: &[Vec<f32>],
selections: &[Vec<i32>],
k: &dyn Fn(&[i32]) -> Vec<f32>,
v: &dyn Fn(&[i32]) -> Vec<f32>,
) {
/// The dequantizers of one attention case: the K and V values at the selected cells.
struct KvDequantizers<'a> {
k: &'a dyn Fn(&[i32]) -> Vec<f32>,
v: &'a dyn Fn(&[i32]) -> Vec<f32>,
}
fn check_attention(name: &str, got: &[f32], q: &[Vec<f32>], selections: &[Vec<i32>], deq: KvDequantizers) {
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::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}");
assert!(
@@ -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<f32> {
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 { residual: &mut r, row_count: self.t_count, row_stride: self.hc * self.n };
cvec::apply(rows, &t, spec.on, layer_used, pending);
r
}
}
@@ -80,28 +81,39 @@ 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,
}
/// 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 }
}
/// 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", 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),
]
}
@@ -33,8 +33,9 @@ fn append_cells_one_by_one(f: &serde_json::Value, ks: &[Vec<f32>], vs: &[Vec<f32
let mut host = q4_pool();
for pos in 0..12 {
let (k, v) = (rotate(&ks[pos]), rotate(&vs[pos]));
let target = Some(&mut host);
cache::append_cell(KvFormat::Q4_0, &mut pools, target, &Q4_TABLE, pos as i64, &k, &v, &S, C).unwrap();
let target = PoolTarget { pools: &mut pools, host: Some(&mut host) };
let at = CellAt { page_table: &Q4_TABLE, position: pos as i64, shapes: &S };
cache::append_cell(KvFormat::Q4_0, target, at, CellKv { k: &k, v: &v }, C).unwrap();
}
(pools, host)
}
@@ -50,8 +51,9 @@ fn check_batch_path(f: &serde_json::Value) {
let mut bhost = q4_pool();
for t in 0..6 {
let (k, v) = (&kr[t * 512..(t + 1) * 512], &vr[t * 512..(t + 1) * 512]);
let target = Some(&mut bhost);
cache::append_cell(KvFormat::Q4_0, &mut batch, target, &Q4_TABLE, 3 + t as i64, k, v, &S, C).unwrap();
let target = PoolTarget { pools: &mut batch, host: Some(&mut bhost) };
let at = CellAt { page_table: &Q4_TABLE, position: 3 + t as i64, shapes: &S };
cache::append_cell(KvFormat::Q4_0, target, at, CellKv { k, v }, C).unwrap();
}
assert_hex_eq("batch_k", &batch.k_q4, &f["batch_k"]);
assert_hex_eq("batch_v", &batch.v_q4, &f["batch_v"]);
@@ -24,7 +24,9 @@ impl Cells {
for pos in 0..12 {
let v = value(&self.vs[pos]);
let host = host.as_deref_mut();
cache::append_cell(format, pools, host, table, pos as i64, &self.ks[pos], &v, &S, C).unwrap();
let target = PoolTarget { pools: &mut *pools, host };
let at = CellAt { page_table: table, position: pos as i64, shapes: &S };
cache::append_cell(format, target, at, CellKv { k: &self.ks[pos], v: &v }, C).unwrap();
}
}
@@ -49,7 +49,8 @@ fn replay_calls(f: &serde_json::Value, map: &mut StreamMap, (slots, host): (&mut
for (call, rec) in recorded.iter().enumerate() {
let (ids, steps) = call_queries(&mut g, call);
let order = recorded_i32s(&rec["order"]);
let report = map.resolve(&ids, &steps, N_Q, CAP, 4, &MissOrder::Observed(order.clone())).unwrap();
let batch = kv_stream::ResolveBatch { ids: &ids, steps: &steps, query_count: N_Q, capacity: CAP, page_size: 4 };
let report = map.resolve(batch, &MissOrder::Observed(order.clone())).unwrap();
assert_eq!(report.placed, order.len(), "call {call}");
map.copy_missed(slots, host, &S, StreamFormat::Int8);
assert_eq!(map.ctl.to_vec(), recorded_i32s(&rec["ctl"]), "ctl after call {call}");
@@ -36,7 +36,9 @@ impl AttnCase {
let mut pools = PoolSet::new(format, &S, 18 * S.rows_per_page()).unwrap();
for c in 0..CELLS {
let (k, v) = keys_values(c);
cache::append_cell(format, &mut pools, None, &self.table, c as i64, &k, &v, &S, C).unwrap();
let target = PoolTarget { pools: &mut pools, host: None };
let at = CellAt { page_table: &self.table, position: c as i64, shapes: &S };
cache::append_cell(format, target, at, CellKv { k: &k, v: &v }, C).unwrap();
}
pools
}
@@ -58,8 +60,10 @@ fn mode2(f: &serde_json::Value, case: &AttnCase) {
&got,
&qr,
&case.selections,
&|ids| cache::dequant_q4(&pools.k_q4, table, ids, &S).unwrap(),
&|ids| cache::dequant_q4(&pools.v_q4, table, ids, &S).unwrap(),
KvDequantizers {
k: &|ids| cache::dequant_q4(&pools.k_q4, table, ids, &S).unwrap(),
v: &|ids| cache::dequant_q4(&pools.v_q4, table, ids, &S).unwrap(),
},
);
}
@@ -73,8 +77,10 @@ fn mode3(f: &serde_json::Value, case: &AttnCase) {
&got,
&per_q(&case.q),
&case.selections,
&|ids| cache::dequant_q8(&pools.k_q, &pools.k_scale, table, ids, &S).unwrap(),
&|ids| cache::dequant_q4(&pools.v_q4, table, ids, &S).unwrap(),
KvDequantizers {
k: &|ids| cache::dequant_q8(&pools.k_q, &pools.k_scale, table, ids, &S).unwrap(),
v: &|ids| cache::dequant_q4(&pools.v_q4, table, ids, &S).unwrap(),
},
);
}
@@ -122,7 +128,7 @@ fn mode4(f: &serde_json::Value, case: &AttnCase) {
}
out
};
check_attention(key, &got, &per_q(&routed), &kids, &keys, &value);
check_attention(key, &got, &per_q(&routed), &kids, KvDequantizers { k: &keys, v: &value });
}
}
+10 -11
View File
@@ -6,7 +6,8 @@ mod common;
use common::fixture;
use leleka_experimental_ref::remote_experts::{
Dispatch, ExpertSizes, H, RemoteError, RemoteMeta, RemotePlan, dispatch, plan_open, scatter,
Candidates, Dispatch, ExpertSizes, H, RemoteDevice, OpenShape, PrimaryView, RemoteError, RemoteMeta, RemotePlan,
RouteShape, dispatch, plan_open, scatter,
};
use serde_json::Value;
@@ -45,7 +46,9 @@ fn open_with_free(c: &Value, free: u64, claimed: &mut [u8]) -> Result<RemotePlan
let has = |l: i32, e: i32| primary[l as usize * EXPERTS + e as usize] != 0;
let slots = c["slots"].as_i64().unwrap() as i32;
let (layers, experts) = (LAYERS as i64, EXPERTS as i64);
plan_open(1, 2, free, slots, layers, experts, &ranked, &has, claimed, &sizes_of(c))
let helper = RemoteDevice { device: 1, device_count: 2, free_bytes: free };
let candidates = Candidates { ranked: &ranked, primary_has: &has, claimed };
plan_open(helper, OpenShape { slots, layers, experts }, candidates, &sizes_of(c))
}
fn open_case(c: &Value) -> (RemotePlan, Vec<u8>) {
@@ -89,15 +92,11 @@ fn dispatch_case(plan: &RemotePlan, primary: &[u8], c: &Value) -> Result<Dispatc
let ids: Vec<i32> = ints(&c["ids"]).iter().map(|&x| x as i32).collect();
let kind: Vec<i32> = 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 { token_count: n_tok, experts_per_token: k }, primary)
}
/// The grouping arrays of a launched dispatch equal the original's.
+2 -1
View File
@@ -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
}
+10 -2
View File
@@ -110,8 +110,12 @@ fn run_cpu(model: &Model, prompt: &[u32]) -> (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");
}
@@ -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!(
+5 -1
View File
@@ -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())
+6 -3
View File
@@ -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();
+8 -6
View File
@@ -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<Option<Vec<f32>>, 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 {
+10 -8
View File
@@ -14,9 +14,13 @@ impl GpuPrefill {
tokens: &[u32],
pos0: usize,
) -> Result<Vec<f32>, 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<Option<Vec<f32>>, ModelError> {
let PrefillJob { model, cache, span, all_hidden } = job;
let PrefillSpan { tokens, pos0 } = span;
Self::check(model)?;
let started = Instant::now();
self.timings = Timings {
+94 -41
View File
@@ -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.
+10 -2
View File
@@ -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");
}
+5 -1
View File
@@ -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();
+3 -2
View File
@@ -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);
+3 -3
View File
@@ -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<Option<Vec<f32>>, 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 {
+18 -4
View File
@@ -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<usize>,
}
/// 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<usize>,
tensor: ServiceTensor,
rows: usize,
cols: usize,
input: Region,
out: Region,
io: ProductRegions,
) -> Result<Option<Vec<u8>>, 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();
@@ -81,8 +81,12 @@ impl NpuPrefill {
tokens: &[u32],
pos0: usize,
) -> Result<Vec<f32>, 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"))
}
}
+7 -9
View File
@@ -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<Vec<f32>, 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<Vec<u8>>],
ff: usize,
) -> Result<Vec<f32>, 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)?;
+3 -3
View File
@@ -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};
+24 -20
View File
@@ -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::<f32>::new(), Vec::<(usize, usize, Vec<f32>)>::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())
}
@@ -209,15 +206,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<f32>,
) -> (usize, usize, Vec<f32>) {
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;
@@ -228,8 +232,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,
@@ -251,10 +254,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,
}
}
+7 -9
View File
@@ -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<Option<Vec<f32>>, 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 {
+7 -8
View File
@@ -28,15 +28,14 @@ impl NpuPrefill {
pub(super) fn product(
&mut self,
name: &str,
expert: Option<usize>,
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);
+1 -1
View File
@@ -59,8 +59,8 @@ impl AttentionRegion {
keys: &kc[start..],
values: &vc[start..],
stride: kw,
n: attended,
},
attended,
&self.dispatch,
scores,
&mut out,
+2 -2
View File
@@ -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;
+9 -9
View File
@@ -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,
+6 -7
View File
@@ -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(());
+15 -20
View File
@@ -105,23 +105,16 @@ fn to_bits(values: &[f32]) -> Vec<u16> {
}
/// One `attend_with_sink` run at one kernel level.
fn attend_at(dispatch: &Dispatch, head: Head, kv: KvRows, n: usize) -> Vec<f32> {
let mut scores = vec![0.0f32; n.max(1)];
fn attend_at(dispatch: &Dispatch, head: Head, kv: KvRows) -> Vec<f32> {
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<Vec<f32>> {
fn attend_everywhere(head: Head, keys: &[f32], values: &[f32], stride: usize, n: usize) -> Vec<Vec<f32>> {
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<f64> = [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>() + (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::<Vec<_>>(),
);
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) {
+4 -3
View File
@@ -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<Option<Reuse>, 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 {
+29 -6
View File
@@ -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<Option<Vec<f32>>, ModelError>;
+22 -8
View File
@@ -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<QMatrix, ModelError> {
/// 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<QMatrix, ModelError> {
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)?;
@@ -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();
+21 -15
View File
@@ -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<Vec<f32>, 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<Option<Vec<f32>>, 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<Option<Vec<f32>>, 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<Option<Vec<f32>>, 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());
}
+24 -26
View File
@@ -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();
}
+3 -3
View File
@@ -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();
};
+2
View File
@@ -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};
+2 -2
View File
@@ -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()
};
+84
View File
@@ -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 {
@@ -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(
+6 -13
View File
@@ -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);
+6 -12
View File
@@ -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}")));
+7 -25
View File
@@ -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(
+11 -8
View File
@@ -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<f32> = 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();
}
+16 -20
View File
@@ -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()
}
+11 -5
View File
@@ -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);
@@ -101,7 +103,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");
@@ -119,7 +122,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 {
@@ -238,7 +242,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();
@@ -286,7 +291,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);
+6 -5
View File
@@ -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();
+13 -3
View File
@@ -60,7 +60,15 @@ fn random_activations(d: &Dispatch, m: usize, blocks: usize) -> Vec<u8> {
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]);
+16 -7
View File
@@ -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<usize>, 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<usize>,
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::<u64>() 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"));