diff --git a/crates/native-cpu-expert/examples/kernel_ab/cmd_compare_fn.rs b/crates/native-cpu-expert/examples/kernel_ab/cmd_compare_fn.rs index 8c94cf38..7cb7a30f 100644 --- a/crates/native-cpu-expert/examples/kernel_ab/cmd_compare_fn.rs +++ b/crates/native-cpu-expert/examples/kernel_ab/cmd_compare_fn.rs @@ -284,10 +284,8 @@ pub(super) fn mono_ns() -> u64 { } /// The core clock in GHz from a chain of dependent steps (safe code: the C++ chain of dependent adds needs inline -/// assembly). A plain -/// chain of multiplies by an opaque constant is folded by LLVM (measured: 175 GHz), so every step also xors in a -/// shifted copy of the -/// running value, which no reassociation can remove. +/// assembly). A plain chain of multiplies by an opaque constant is folded by LLVM (measured: 175 GHz), so every +/// step also xors in a shifted copy of the running value, which no reassociation can remove. pub(super) fn core_ghz() -> f64 { let k = std::hint::black_box(0x9E37_79B9_7F4A_7C15u64 | 1); let mut x = std::hint::black_box(1u64); diff --git a/crates/native-cpu-expert/examples/kernel_ab/cmd_time_fn.rs b/crates/native-cpu-expert/examples/kernel_ab/cmd_time_fn.rs index a6cbbfe0..8cc1eb71 100644 --- a/crates/native-cpu-expert/examples/kernel_ab/cmd_time_fn.rs +++ b/crates/native-cpu-expert/examples/kernel_ab/cmd_time_fn.rs @@ -79,9 +79,8 @@ struct Measured { output_sha: String, } -/// Pins the process to `t.pin` before any buffer or pool exists (so the pool's threads inherit the mask), then reads -/// the -/// facts about the pin. +/// Pins the process to `t.pin` before any buffer or pool exists (so the pool's threads inherit the mask), then +/// reads the facts about the pin. fn pin_and_probe(t: &TimeArgs) -> Result { if rust_topology::pin_current_thread(t.pin as i32) < 0 { return Err(format!("the pin to CPU {} was refused", t.pin)); diff --git a/crates/native-cpu-expert/examples/kernel_ab/describe_cpp_tree_fn.rs b/crates/native-cpu-expert/examples/kernel_ab/describe_cpp_tree_fn.rs index 6f3469cb..d5c12c03 100644 --- a/crates/native-cpu-expert/examples/kernel_ab/describe_cpp_tree_fn.rs +++ b/crates/native-cpu-expert/examples/kernel_ab/describe_cpp_tree_fn.rs @@ -212,10 +212,9 @@ pub(super) fn equality_block(c: &CaseEntry, o: &Outcome) -> String { ) } -/// The A/A equality: the same implementation in two fresh processes. Rust: the output hashes of the two processes (and -/// each one's -/// selfcheck); C++: each process's timed composition equals `compose_expert()` bit for bit (selfcheck), which is the -/// same function. +/// The A/A equality: the same implementation in two fresh processes. Rust: the output hashes of the two processes +/// (and each one's selfcheck); C++: each process's timed composition equals `compose_expert()` bit for bit +/// (selfcheck), which is the same function. pub(super) fn aa_outcome(a: &ProcOut, b: &ProcOut, rows: usize) -> (Outcome, String) { let compared = rows * H; let selfchecks = diff --git a/crates/native-cpu-expert/examples/kernel_ab/impl_impl.rs b/crates/native-cpu-expert/examples/kernel_ab/impl_impl.rs index 69e5035f..62a306a3 100644 --- a/crates/native-cpu-expert/examples/kernel_ab/impl_impl.rs +++ b/crates/native-cpu-expert/examples/kernel_ab/impl_impl.rs @@ -47,12 +47,10 @@ pub(super) fn procs_for(trees: &[&'static str]) -> Vec { v } -/// The environment a cell needs and nothing else. The avx2 trees set `STRATA_FORCE_AVX2=1`, which both implementations -/// honour. The -/// Rust cells run `DirectCpuPool::new(1)`, a worker thread plus the draining caller, both confined to the one pinned -/// CPU: the pool must -/// not re-pin its caller (`LELEKA_CPU_POOL_PIN_HOST=off`, so the pin is the requested one) and its worker must not spin -/// after a batch +/// The environment a cell needs and nothing else. The avx2 trees set `STRATA_FORCE_AVX2=1`, which both +/// implementations honour. The Rust cells run `DirectCpuPool::new(1)`, a worker thread plus the draining +/// caller, both confined to the one pinned CPU: the pool must not re-pin its caller +/// (`LELEKA_CPU_POOL_PIN_HOST=off`, so the pin is the requested one) and its worker must not spin after a batch /// (`STRATA_POOL_SPIN_US=0`; with the 20 ms default the worker spins on the caller's only CPU and costs it half its /// time). pub(super) fn cell_env(p: &Proc) -> Vec<(String, String)> { @@ -121,10 +119,9 @@ pub(super) fn splitmix(state: &mut u64) -> u64 { z ^ (z >> 31) } -/// The schedule of one batch: round `i` (0-based) rotates a seeded permutation by `i mod n`; every block of `n` rounds -/// draws a fresh -/// permutation, so each process takes each position equally often within a block. A pure function of (seed, batch, -/// rounds, procs). +/// The schedule of one batch: round `i` (0-based) rotates a seeded permutation by `i mod n`; every block of `n` +/// rounds draws a fresh permutation, so each process takes each position equally often within a block. A pure +/// function of (seed, batch, rounds, procs). pub(super) fn make_schedule(seed: u64, batch: u32, rounds: u32, procs: &[Proc]) -> Vec> { let n = procs.len(); let mut out = Vec::new(); diff --git a/crates/native-cpu-expert/examples/kernel_ab/in_magic_types.rs b/crates/native-cpu-expert/examples/kernel_ab/in_magic_types.rs index 3359f5e9..05040901 100644 --- a/crates/native-cpu-expert/examples/kernel_ab/in_magic_types.rs +++ b/crates/native-cpu-expert/examples/kernel_ab/in_magic_types.rs @@ -15,9 +15,9 @@ pub(super) const MAX_FILE_BYTES: u64 = 16 << 20; pub(super) const MAX_MANIFEST_BYTES: u64 = 8 << 20; pub(super) const MAX_CASES: usize = 1024; pub(super) const TOLERANCE_METRIC: &str = "max_abs_error_over_max_abs_reference"; -/// Marker of every schema-required timing field this part does not measure (STRA-318 fills them): a text marker where -/// the schema takes -/// text, the smallest positive double (`5e-324`) where it takes a positive number, 1 where it takes a positive count. +/// Marker of every schema-required timing field this part does not measure (STRA-318 fills them): a text marker +/// where the schema takes text, the smallest positive double (`5e-324`) where it takes a positive number, 1 +/// where it takes a positive count. pub(super) const NOT_MEASURED: &str = "NOT_MEASURED (filled by STRA-318, the alternation runner)"; pub(super) const TREES: [&str; 2] = ["avx512", "avx2"]; @@ -174,13 +174,11 @@ pub(super) struct Options { pub(super) case: Option, } -// ------------------------------------------------------------------------------------------------ flags (time, -// alternate) +// --------------------------------------------------------------------------------- flags (time, alternate) pub(super) struct Flags(pub(super) Vec<(String, String)>); -// ------------------------------------------------------------------------------------------------ clocks and host -// facts +// ----------------------------------------------------------------------------------- clocks and host facts /// The 60 ms slice of `tq_cpu_parity.cpp:461` (`slice_ms = quick ? 40 : 60`), the same value `kab time` uses. pub(super) const DEFAULT_SLICE_MS: f64 = 60.0; @@ -190,13 +188,13 @@ pub(super) const CLOCK_MOVED_FRACTION: f64 = 0.05; /// An SMT sibling busier than this fraction is not idle (the 5 percent rule of `sibling_idle`). pub(super) const SIBLING_BUSY_LIMIT: f64 = 0.05; pub(super) const ALIGN: usize = 4096; -/// Cycles of one step of the calibration chain `x = (x * k) ^ (x >> 17)`: a 64-bit multiply (3 cycles on Intel Skylake -/// to Golden Cove -/// and AMD Zen 1 to 5) then an xor (1 cycle); the shift runs beside the multiply. +/// Cycles of one step of the calibration chain `x = (x * k) ^ (x >> 17)`: a 64-bit multiply (3 cycles on Intel +/// Skylake to Golden Cove and AMD Zen 1 to 5) then an xor (1 cycle); the shift runs beside the multiply. pub(super) const CHAIN_STEP_CYCLES: f64 = 4.0; -pub(super) const CLOCK_METHOD: &str = - "chain of dependent steps x = (x * k) ^ (x >> 17), 4 cycles per step (3 multiply + 1 xor), 1000000 iterations of \ - 4 steps, ghz = 4 * 4e6 / (elapsed ns); before and after every slice"; +pub(super) const CLOCK_METHOD: &str = concat!( + "chain of dependent steps x = (x * k) ^ (x >> 17), 4 cycles per step (3 multiply + 1 xor), ", + "1000000 iterations of 4 steps, ghz = 4 * 4e6 / (elapsed ns); before and after every slice" +); pub(super) struct Llc { pub(super) level: u32, @@ -204,8 +202,7 @@ pub(super) struct Llc { pub(super) source: String, } -// ------------------------------------------------------------------------------------------------ time (one fresh -// process) +// -------------------------------------------------------------------------------- time (one fresh process) #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub(super) enum RegimeSel { diff --git a/crates/native-cpu-expert/examples/kernel_ab/time_args_types.rs b/crates/native-cpu-expert/examples/kernel_ab/time_args_types.rs index b939766a..a3363a7a 100644 --- a/crates/native-cpu-expert/examples/kernel_ab/time_args_types.rs +++ b/crates/native-cpu-expert/examples/kernel_ab/time_args_types.rs @@ -65,8 +65,7 @@ pub(super) struct RegimeSpec<'a> { pub(super) selfcheck: bool, } -// ------------------------------------------------------------------------------------------------ alternate: cells, -// environment, schedule +// ----------------------------------------------------------------- alternate: cells, environment, schedule #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] pub(super) enum Impl { @@ -84,8 +83,7 @@ pub(super) struct Proc { pub(super) const SCHEDULE_MAGIC: &str = "# KAB1-alt schedule v1"; -// ------------------------------------------------------------------------------------------------ alternate: reading a -// process's JSON +// --------------------------------------------------------------------- alternate: reading a process's JSON #[derive(Debug, Clone)] pub(super) struct RegimeStat { @@ -124,8 +122,7 @@ pub(super) struct Expect<'a> { pub(super) pin: usize, } -// ------------------------------------------------------------------------------------------------ alternate: round -// records +// -------------------------------------------------------------------------------- alternate: round records #[derive(Clone)] pub(super) struct Tool { @@ -163,8 +160,7 @@ pub(super) struct BatchCtx<'a> { pub(super) equality: &'a BTreeMap<&'static str, Outcome>, } -// ------------------------------------------------------------------------------------------------ alternate: the -// runner +// ----------------------------------------------------------------------------------- alternate: the runner pub(super) const ALT_FLAGS: [&str; 13] = [ "run-dir", diff --git a/crates/native-cpu-expert/examples/kernel_ab/write_out_fn.rs b/crates/native-cpu-expert/examples/kernel_ab/write_out_fn.rs index af27f80c..353f6c25 100644 --- a/crates/native-cpu-expert/examples/kernel_ab/write_out_fn.rs +++ b/crates/native-cpu-expert/examples/kernel_ab/write_out_fn.rs @@ -4,8 +4,7 @@ #[allow(unused_imports)] use super::*; -// ------------------------------------------------------------------------------------------------ run-tree (one fresh -// process) +// ---------------------------------------------------------------------------- run-tree (one fresh process) pub(super) fn write_out(path: &Path, rows: usize, tree: &str, values: &[f32]) -> Result<(), String> { let tree_id = TREES.iter().position(|t| *t == tree).ok_or("unknown tree")? as u32; @@ -19,9 +18,8 @@ pub(super) fn write_out(path: &Path, rows: usize, tree: &str, values: &[f32]) -> File::create(path).and_then(|mut f| f.write_all(&b)).map_err(|e| format!("{}: {e}", path.display())) } -/// Our kernels on one verified case through the public API: PreparedJob only for the input validation it performs, then -/// one -/// `compute_group` over borrowed bytes (one expert, `rows` tokens, pairs `(t, 0)`, stride 1). +/// Our kernels on one verified case through the public API: PreparedJob only for the input validation it performs, +/// then one `compute_group` over borrowed bytes (one expert, `rows` tokens, pairs `(t, 0)`, stride 1). pub(super) fn compute_case(pool: &mut DirectCpuPool, case: &CaseIn) -> Result, String> { let (gu, down) = (gate_up_row(case.header.gu).ok_or("gate/up type")?.1, down_row(case.header.down).ok_or("down type")?.1); diff --git a/crates/native-cpu-expert/tests/borrowed_group_parity.rs b/crates/native-cpu-expert/tests/borrowed_group_parity.rs index cc8e57fc..98aade84 100644 --- a/crates/native-cpu-expert/tests/borrowed_group_parity.rs +++ b/crates/native-cpu-expert/tests/borrowed_group_parity.rs @@ -8,7 +8,6 @@ use leleka_native_cpu_expert::{ BorrowedExpert, BorrowedGroup, CpuPool, DirectCpuPool, DownFormat, GateUpFormat, PreparedJob, }; -use std::time::Instant; const H: usize = 2560; const FF: usize = 640; @@ -110,63 +109,78 @@ fn plan(ids: &[usize], include: &[bool]) -> Vec<(usize, Vec<(usize, usize)>)> { jobs } -/// The previous serve path: copy every role into owned boxes, build owned inputs, run batches of 12 with -/// a join between them, scatter every expert's rows into the output. -fn owned_path( - pool: &mut CpuPool, +/// One planned expert: its index in the bank and the `(row, slot)` pairs it serves, in ascending order. +type Job = (usize, Vec<(usize, usize)>); + +/// The inputs both group paths run on. +#[derive(Clone, Copy)] +struct Work<'a> { gu: GateUpFormat, down: DownFormat, - bank: &[Expert], - tokens: &[f32], - jobs: &[(usize, Vec<(usize, usize)>)], - out: &mut [f32], -) { - for batch in jobs.chunks(OLD_BATCH) { - let mut prepared = Vec::with_capacity(batch.len()); - for (e, pairs) in batch { - let x = &bank[*e]; - let mut input = Vec::with_capacity(pairs.len() * H); - for &(row, _) in pairs { - input.extend_from_slice(&tokens[row * H..(row + 1) * H]); - } - prepared.push( - PreparedJob::new( - gu, - down, - x.gate.clone().into_boxed_slice(), - x.up.clone().into_boxed_slice(), - x.down.clone().into_boxed_slice(), - input.into_boxed_slice(), - pairs.len(), - ) - .expect("owned job"), - ); - } + bank: &'a [Expert], + tokens: &'a [f32], + jobs: &'a [Job], +} + +/// The tokens of the rows an expert serves, one after the other. +fn gather_input(tokens: &[f32], pairs: &[(usize, usize)]) -> Vec { + let mut input = Vec::with_capacity(pairs.len() * H); + for &(row, _) in pairs { + input.extend_from_slice(&tokens[row * H..(row + 1) * H]); + } + input +} + +/// Writes an expert's `values` (one `H` row per pair) into the `(row, slot)` cells of `out`. +fn scatter_rows(values: &[f32], pairs: &[(usize, usize)], out: &mut [f32]) { + for (i, &(row, slot)) in pairs.iter().enumerate() { + let at = (row * TOP_K + slot) * H; + out[at..at + H].copy_from_slice(&values[i * H..(i + 1) * H]); + } +} + +/// Copies every role into owned boxes and builds the owned input of one expert. +fn prepare_owned(w: &Work, e: usize, pairs: &[(usize, usize)]) -> PreparedJob { + let x = &w.bank[e]; + let input = gather_input(w.tokens, pairs); + PreparedJob::new( + w.gu, + w.down, + x.gate.clone().into_boxed_slice(), + x.up.clone().into_boxed_slice(), + x.down.clone().into_boxed_slice(), + input.into_boxed_slice(), + pairs.len(), + ) + .expect("owned job") +} + +type Prepare = fn(&Work, usize, &[(usize, usize)]) -> PreparedJob; + +/// Runs batches of 12 with a join between them and scatters every expert's rows into the output. +fn run_owned(pool: &mut CpuPool, w: &Work, out: &mut [f32], prepare: Prepare) { + for batch in w.jobs.chunks(OLD_BATCH) { + let prepared: Vec = batch.iter().map(|(e, pairs)| prepare(w, *e, pairs)).collect(); let done = pool.start(prepared, 48 << 20).expect("start").join().expect("join"); for (job, (_, pairs)) in done.into_iter().zip(batch) { - let values = job.into_values(); - for (i, &(row, slot)) in pairs.iter().enumerate() { - let at = (row * TOP_K + slot) * H; - out[at..at + H].copy_from_slice(&values[i * H..(i + 1) * H]); - } + scatter_rows(&job.into_values(), pairs, out); } } } -fn borrowed_path( - pool: &mut DirectCpuPool, - gu: GateUpFormat, - down: DownFormat, - bank: &[Expert], - tokens: &[f32], - jobs: &[(usize, Vec<(usize, usize)>)], - out: &mut [f32], -) { - let experts: Vec> = jobs +/// The previous serve path: copy every role into owned boxes, build owned inputs, run batches of 12 with +/// a join between them, scatter every expert's rows into the output. +fn owned_path(pool: &mut CpuPool, w: &Work, out: &mut [f32]) { + run_owned(pool, w, out, prepare_owned); +} + +fn borrowed_path(pool: &mut DirectCpuPool, w: &Work, out: &mut [f32]) { + let experts: Vec> = w + .jobs .iter() - .map(|(e, pairs)| BorrowedExpert { gate: &bank[*e].gate, up: &bank[*e].up, down: &bank[*e].down, pairs }) + .map(|(e, pairs)| BorrowedExpert { gate: &w.bank[*e].gate, up: &w.bank[*e].up, down: &w.bank[*e].down, pairs }) .collect(); - pool.compute_group(gu, down, &BorrowedGroup { tokens, experts: &experts, stride: TOP_K }, out) + pool.compute_group(w.gu, w.down, &BorrowedGroup { tokens: w.tokens, experts: &experts, stride: TOP_K }, out) .expect("borrowed group"); } @@ -183,151 +197,188 @@ const PAIRS: [(GateUpFormat, DownFormat); 10] = [ (GateUpFormat::Q2_0, DownFormat::Q2_0), ]; +/// The two pools the parity test runs the same groups through. +struct Pools { + owned: CpuPool, + direct: DirectCpuPool, +} + +/// One routed group of the parity test: the formats, the bank and the shape of the routing. +struct Spec<'a> { + gu: GateUpFormat, + down: DownFormat, + bank: &'a [Expert], + rows: usize, + share: usize, +} + +/// The file-mapped source's prefetch phase reads only: the group computes the same bits. +fn prefetch_group(direct: &mut DirectCpuPool, w: &Work) { + let refs: Vec> = w + .jobs + .iter() + .map(|(e, pairs)| BorrowedExpert { gate: &w.bank[*e].gate, up: &w.bank[*e].up, down: &w.bank[*e].down, pairs }) + .collect(); + direct.prefetch(w.gu, w.down, &refs).expect("prefetch"); +} + +fn assert_identical(a: &[f32], b: &[f32], s: &Spec) { + let (gu, down, rows, share) = (s.gu, s.down, s.rows, s.share); + let differing = a.iter().zip(b).filter(|(x, y)| x.to_bits() != y.to_bits()).count(); + assert_eq!(differing, 0, "{gu:?} x {down:?} rows={rows} share={share}: {differing} floats differ"); +} + +/// Prints the digest of every output bit and checks that only the planned rows were written, all finite. +fn check_written(b: &[f32], jobs: &[Job], s: &Spec) { + let (gu, down, rows, share) = (s.gu, s.down, s.rows, s.share); + // A digest of every output bit: compared across builds to prove a kernel change bit-exact. + let digest = + b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, v| (h ^ u64::from(v.to_bits())).wrapping_mul(0x100_0000_01b3)); + eprintln!("DIGEST {gu:?} {down:?} rows={rows} share={share} {digest:016x}"); + let computed: usize = jobs.iter().map(|(_, p)| p.len()).sum(); + assert!( + b.iter().filter(|v| v.is_finite()).count() == computed * H, + "{gu:?} x {down:?}: only planned rows written, all finite" + ); +} + +/// Routes one group, runs it through both paths and compares every output bit; false when nothing was planned. +fn check_group(pools: &mut Pools, rng: &mut Rng, s: &Spec) -> bool { + let (ids, include) = route(rng, s.rows, s.bank.len(), s.share); + let jobs = plan(&ids, &include); + if jobs.is_empty() { + return false; + } + let tokens: Vec = (0..s.rows * H).map(|_| rng.unit()).collect(); + let w = Work { gu: s.gu, down: s.down, bank: s.bank, tokens: &tokens, jobs: &jobs }; + // different sentinels: rows the plan leaves out must stay untouched by both paths + let mut a = vec![f32::from_bits(0x7fc0_0001); s.rows * TOP_K * H]; + let mut b = vec![f32::from_bits(0x7fc0_0001); s.rows * TOP_K * H]; + owned_path(&mut pools.owned, &w, &mut a); + if s.share != 100 { + prefetch_group(&mut pools.direct, &w); + } + borrowed_path(&mut pools.direct, &w, &mut b); + assert_identical(&a, &b, s); + check_written(&b, &jobs, s); + true +} + +/// Every row count and CPU share of one format pair, on a small bank so rows share experts and batches of 12 are +/// crossed; returns the number of groups compared. +fn check_pair(pools: &mut Pools, rng: &mut Rng, (gu, down): (GateUpFormat, DownFormat)) -> usize { + let bank = bank(rng, gu, down, 40); + let mut groups = 0; + for rows in [1usize, 2, 3, 4, 6, 8] { + for share in [100usize, 50] { + groups += usize::from(check_group(pools, rng, &Spec { gu, down, bank: &bank, rows, share })); + } + } + groups +} + #[test] fn borrowed_group_is_bit_identical_to_the_owned_batches() { let workers = std::env::var("PARITY_WORKERS").ok().and_then(|v| v.parse().ok()).unwrap_or(4); - let mut owned = CpuPool::new(workers).expect("owned pool"); - let mut direct = DirectCpuPool::new(workers).expect("direct pool"); + let mut pools = Pools { + owned: CpuPool::new(workers).expect("owned pool"), + direct: DirectCpuPool::new(workers).expect("direct pool"), + }; let mut rng = Rng(0x9e37_79b9_7f4a_7c15); let mut groups = 0; - for (gu, down) in PAIRS { - // a small bank so rows share experts and batches of 12 are crossed - let bank = bank(&mut rng, gu, down, 40); - for rows in [1usize, 2, 3, 4, 6, 8] { - for share in [100usize, 50] { - let (ids, include) = route(&mut rng, rows, bank.len(), share); - let jobs = plan(&ids, &include); - if jobs.is_empty() { - continue; - } - let tokens: Vec = (0..rows * H).map(|_| rng.unit()).collect(); - // different sentinels: rows the plan leaves out must stay untouched by both paths - let mut a = vec![f32::from_bits(0x7fc0_0001); rows * TOP_K * H]; - let mut b = vec![f32::from_bits(0x7fc0_0001); rows * TOP_K * H]; - owned_path(&mut owned, gu, down, &bank, &tokens, &jobs, &mut a); - if share != 100 { - // the file-mapped source's prefetch phase reads only: the group computes the same bits - let refs: Vec> = jobs - .iter() - .map(|(e, pairs)| BorrowedExpert { - gate: &bank[*e].gate, - up: &bank[*e].up, - down: &bank[*e].down, - pairs, - }) - .collect(); - direct.prefetch(gu, down, &refs).expect("prefetch"); - } - borrowed_path(&mut direct, gu, down, &bank, &tokens, &jobs, &mut b); - let differing = a.iter().zip(&b).filter(|(x, y)| x.to_bits() != y.to_bits()).count(); - assert_eq!(differing, 0, "{gu:?} x {down:?} rows={rows} share={share}: {differing} floats differ"); - // A digest of every output bit: compared across builds to prove a kernel change bit-exact. - let digest = b - .iter() - .fold(0xcbf2_9ce4_8422_2325u64, |h, v| (h ^ u64::from(v.to_bits())).wrapping_mul(0x100_0000_01b3)); - eprintln!("DIGEST {gu:?} {down:?} rows={rows} share={share} {digest:016x}"); - let computed: usize = jobs.iter().map(|(_, p)| p.len()).sum(); - assert!( - b.iter().filter(|v| v.is_finite()).count() == computed * H, - "{gu:?} x {down:?}: only planned rows written, all finite" - ); - groups += 1; - } - } + for pair in PAIRS { + groups += check_pair(&mut pools, &mut rng, pair); } eprintln!("bit-identical groups: {groups}"); } -#[test] -fn borrowed_group_refuses_bad_shapes_without_touching_out() { - let mut direct = DirectCpuPool::new(2).expect("direct pool"); - let mut rng = Rng(7); - let (gu, down) = (GateUpFormat::Iq3S, DownFormat::Iq4Nl); - let bank = bank(&mut rng, gu, down, 2); - let tokens = vec![0.25f32; 2 * H]; - let mut out = vec![-3.0f32; 2 * TOP_K * H]; +/// The state a refused group must leave alone: the pool and the output. +struct Sink { + direct: DirectCpuPool, + out: Vec, +} + +const BAD_FORMATS: (GateUpFormat, DownFormat) = (GateUpFormat::Iq3S, DownFormat::Iq4Nl); + +fn expert<'a>(bank: &'a [Expert], i: usize, pairs: &'a [(usize, usize)]) -> BorrowedExpert<'a> { + BorrowedExpert { gate: &bank[i].gate, up: &bank[i].up, down: &bank[i].down, pairs } +} + +/// Runs a group of `experts` over `tokens` in format `gu` (the test's down format) and says whether it was refused. +fn refused(sink: &mut Sink, gu: GateUpFormat, tokens: &[f32], experts: &[BorrowedExpert]) -> bool { + let group = BorrowedGroup { tokens, experts, stride: TOP_K }; + sink.direct.compute_group(gu, BAD_FORMATS.1, &group, &mut sink.out).is_err() +} + +/// Duplicate pairs, rows out of range, slots beyond the stride and an empty group. +fn refuses_bad_pairs(sink: &mut Sink, bank: &[Expert], tokens: &[f32]) { let pairs_a = [(0usize, 1usize)]; let duplicate = [(0usize, 1usize)]; let out_of_rows = [(2usize, 0usize)]; let wide_slot = [(0usize, TOP_K)]; - let x = |pairs| BorrowedExpert { gate: &bank[0].gate, up: &bank[0].up, down: &bank[0].down, pairs }; - let y = |pairs| BorrowedExpert { gate: &bank[1].gate, up: &bank[1].up, down: &bank[1].down, pairs }; + let (x, y) = (|pairs| expert(bank, 0, pairs), |pairs| expert(bank, 1, pairs)); for experts in [vec![x(&pairs_a), y(&duplicate)], vec![x(&out_of_rows)], vec![x(&wide_slot)], vec![]] { - let group = BorrowedGroup { tokens: &tokens, experts: &experts, stride: TOP_K }; - assert!(direct.compute_group(gu, down, &group, &mut out).is_err()); + assert!(refused(sink, BAD_FORMATS.0, tokens, &experts)); } +} + +/// A gate matrix one byte short, and a group of another gate/up format than its bytes. +fn refuses_short_gate_and_wrong_format(sink: &mut Sink, bank: &[Expert], tokens: &[f32]) { + let pairs_a = [(0usize, 1usize)]; let short = BorrowedExpert { gate: &bank[0].gate[1..], up: &bank[0].up, down: &bank[0].down, pairs: &pairs_a }; - assert!( - direct - .compute_group(gu, down, &BorrowedGroup { tokens: &tokens, experts: &[short], stride: TOP_K }, &mut out) - .is_err() - ); - let wrong_format = [x(&pairs_a)]; - assert!( - direct - .compute_group( - GateUpFormat::Iq3Xxs, - down, - &BorrowedGroup { tokens: &tokens, experts: &wrong_format, stride: TOP_K }, - &mut out - ) - .is_err() - ); - let mut nan = tokens.clone(); + assert!(refused(sink, BAD_FORMATS.0, tokens, &[short])); + let wrong_format = [expert(bank, 0, &pairs_a)]; + assert!(refused(sink, GateUpFormat::Iq3Xxs, tokens, &wrong_format)); +} + +fn refuses_nan_tokens(sink: &mut Sink, bank: &[Expert], tokens: &[f32]) { + let pairs_a = [(0usize, 1usize)]; + let wrong_format = [expert(bank, 0, &pairs_a)]; + let mut nan = tokens.to_vec(); nan[5] = f32::NAN; - assert!( - direct - .compute_group(gu, down, &BorrowedGroup { tokens: &nan, experts: &wrong_format, stride: TOP_K }, &mut out) - .is_err() - ); - assert!(out.iter().all(|&v| v == -3.0), "a refused group writes nothing"); + assert!(refused(sink, BAD_FORMATS.0, &nan, &wrong_format)); +} + +fn serves_good_group(sink: &mut Sink, bank: &[Expert], tokens: &[f32]) { + let pairs_a = [(0usize, 1usize)]; + let good = [expert(bank, 0, &pairs_a)]; + let group = BorrowedGroup { tokens, experts: &good, stride: TOP_K }; + sink.direct.compute_group(BAD_FORMATS.0, BAD_FORMATS.1, &group, &mut sink.out).expect("good group"); + assert!(sink.out[H..2 * H].iter().all(|v| v.is_finite())); +} + +#[test] +fn borrowed_group_refuses_bad_shapes_without_touching_out() { + let (gu, down) = BAD_FORMATS; + let mut sink = Sink { direct: DirectCpuPool::new(2).expect("direct pool"), out: vec![-3.0f32; 2 * TOP_K * H] }; + let bank = bank(&mut Rng(7), gu, down, 2); + let tokens = vec![0.25f32; 2 * H]; + refuses_bad_pairs(&mut sink, &bank, &tokens); + refuses_short_gate_and_wrong_format(&mut sink, &bank, &tokens); + refuses_nan_tokens(&mut sink, &bank, &tokens); + assert!(sink.out.iter().all(|&v| v == -3.0), "a refused group writes nothing"); // and the pool still serves a good group afterwards - let good = [x(&pairs_a)]; - direct - .compute_group(gu, down, &BorrowedGroup { tokens: &tokens, experts: &good, stride: TOP_K }, &mut out) - .expect("good group"); - assert!(out[H..2 * H].iter().all(|v| v.is_finite())); + serves_good_group(&mut sink, &bank, &tokens); } /// The previous runtime prepare step per expert also copied each role out of the source (`block`) and /// scanned every block header (`encoded_finite`) before `PreparedJob::new` copied them again. -fn owned_path_with_source_copy( - pool: &mut CpuPool, - gu: GateUpFormat, - down: DownFormat, - bank: &[Expert], - tokens: &[f32], - jobs: &[(usize, Vec<(usize, usize)>)], - out: &mut [f32], -) { - let (_, gb) = gate_up_block(gu); - let (_, db) = down_block(down); +fn prepare_source_copy(w: &Work, e: usize, pairs: &[(usize, usize)]) -> PreparedJob { + let (_, gb) = gate_up_block(w.gu); + let (_, db) = down_block(w.down); let scan = |bytes: &[u8], block: usize| { bytes.chunks_exact(block).all(|b| u16::from_le_bytes([b[0], b[1]]) & 0x7c00 != 0x7c00) }; - for batch in jobs.chunks(OLD_BATCH) { - let mut prepared = Vec::with_capacity(batch.len()); - for (e, pairs) in batch { - let x = &bank[*e]; - let (g, u, d) = - (x.gate.clone().into_boxed_slice(), x.up.clone().into_boxed_slice(), x.down.clone().into_boxed_slice()); - assert!(scan(&g, gb) && scan(&u, gb) && scan(&d, db)); - let mut input = Vec::with_capacity(pairs.len() * H); - for &(row, _) in pairs { - input.extend_from_slice(&tokens[row * H..(row + 1) * H]); - } - prepared - .push(PreparedJob::new(gu, down, g, u, d, input.into_boxed_slice(), pairs.len()).expect("owned job")); - } - let done = pool.start(prepared, 48 << 20).expect("start").join().expect("join"); - for (job, (_, pairs)) in done.into_iter().zip(batch) { - let values = job.into_values(); - for (i, &(row, slot)) in pairs.iter().enumerate() { - let at = (row * TOP_K + slot) * H; - out[at..at + H].copy_from_slice(&values[i * H..(i + 1) * H]); - } - } - } + let x = &w.bank[e]; + let (g, u, d) = + (x.gate.clone().into_boxed_slice(), x.up.clone().into_boxed_slice(), x.down.clone().into_boxed_slice()); + assert!(scan(&g, gb) && scan(&u, gb) && scan(&d, db)); + let input = gather_input(w.tokens, pairs); + PreparedJob::new(w.gu, w.down, g, u, d, input.into_boxed_slice(), pairs.len()).expect("owned job") +} + +fn owned_path_with_source_copy(pool: &mut CpuPool, w: &Work, out: &mut [f32]) { + run_owned(pool, w, out, prepare_source_copy); } /// Model-free cost of one decode round's CPU share: 48 groups of `GROUP_ROWS` rows, `GROUP_SHARE`% of the @@ -335,41 +386,8 @@ fn owned_path_with_source_copy( #[test] #[ignore = "benchmark; prints the cost of both group paths"] fn group_path_cost() { - let env = |name: &str, default: usize| std::env::var(name).ok().and_then(|v| v.parse().ok()).unwrap_or(default); - let workers = env("BENCH_WORKERS", 15) as i32; - let rows = env("GROUP_ROWS", 4); - let share = env("GROUP_SHARE", 50); - let rounds = env("ROUNDS", 5); - let (gu, down) = (GateUpFormat::Iq3S, DownFormat::Iq4Nl); - let mut rng = Rng(42); - let bank = bank(&mut rng, gu, down, env("BANK_EXPERTS", 256)); - let mut owned = CpuPool::new(workers).expect("owned pool"); - let mut direct = DirectCpuPool::new(workers).expect("direct pool"); - let groups: Vec<(Vec, Vec<(usize, Vec<(usize, usize)>)>)> = (0..48 * rounds) - .map(|_| { - let (ids, include) = route(&mut rng, rows, bank.len(), share); - ((0..rows * H).map(|_| rng.unit()).collect(), plan(&ids, &include)) - }) - .collect(); - let experts: usize = groups.iter().map(|(_, j)| j.len()).sum(); - let mut out = vec![0.0f32; rows * TOP_K * H]; - for arm in ["owned+source-copy", "owned", "borrowed", "owned+source-copy", "owned", "borrowed"] { - let started = Instant::now(); - for (tokens, jobs) in &groups { - match arm { - "borrowed" => borrowed_path(&mut direct, gu, down, &bank, tokens, jobs, &mut out), - "owned" => owned_path(&mut owned, gu, down, &bank, tokens, jobs, &mut out), - _ => owned_path_with_source_copy(&mut owned, gu, down, &bank, tokens, jobs, &mut out), - } - } - let ms = started.elapsed().as_secs_f64() * 1e3; - let gb = experts as f64 * (bank[0].gate.len() * 2 + bank[0].down.len()) as f64 / 1e9; - eprintln!( - "BENCH {arm:>18}: workers={workers} rows={rows} share={share}% {:.2} experts/group, {:.2} ms/round (48 \ - groups), {:.1} GB/s of expert bytes", - experts as f64 / groups.len() as f64, - ms / rounds as f64, - gb / (ms / 1e3) - ); - } + bench::run(); } + +#[path = "borrowed_group_parity/bench.rs"] +mod bench; diff --git a/crates/native-cpu-expert/tests/borrowed_group_parity/bench.rs b/crates/native-cpu-expert/tests/borrowed_group_parity/bench.rs new file mode 100644 index 00000000..54e46b84 --- /dev/null +++ b/crates/native-cpu-expert/tests/borrowed_group_parity/bench.rs @@ -0,0 +1,75 @@ +//! The model-free cost benchmark of both group paths, run by the ignored test `group_path_cost`. + +use super::*; +use std::time::Instant; + +fn env(name: &str, default: usize) -> usize { + std::env::var(name).ok().and_then(|v| v.parse().ok()).unwrap_or(default) +} + +/// The shape of the benchmark: workers and per-group rows, CPU share and rounds. +struct Cfg { + workers: i32, + rows: usize, + share: usize, + rounds: usize, +} + +/// The tokens of a group and its planned experts. +type Group = (Vec, Vec); + +fn make_groups(rng: &mut Rng, bank: &[Expert], cfg: &Cfg) -> Vec { + (0..48 * cfg.rounds) + .map(|_| { + let (ids, include) = route(rng, cfg.rows, bank.len(), cfg.share); + ((0..cfg.rows * H).map(|_| rng.unit()).collect(), plan(&ids, &include)) + }) + .collect() +} + +/// Milliseconds one arm needs for every group. +fn time_arm(arm: &str, pools: &mut Pools, base: Work, groups: &[Group], out: &mut [f32]) -> f64 { + let started = Instant::now(); + for (tokens, jobs) in groups { + let w = Work { tokens, jobs, ..base }; + match arm { + "borrowed" => borrowed_path(&mut pools.direct, &w, out), + "owned" => owned_path(&mut pools.owned, &w, out), + _ => owned_path_with_source_copy(&mut pools.owned, &w, out), + } + } + started.elapsed().as_secs_f64() * 1e3 +} + +/// One result line: `per_group` experts per group, `(ms, gb)` the time of the arm and the expert bytes it moved. +fn report(arm: &str, cfg: &Cfg, per_group: f64, (ms, gb): (f64, f64)) { + let (workers, rows, share, rounds) = (cfg.workers, cfg.rows, cfg.share, cfg.rounds); + eprintln!( + "BENCH {arm:>18}: workers={workers} rows={rows} share={share}% {:.2} experts/group, {:.2} ms/round (48 \ + groups), {:.1} GB/s of expert bytes", + per_group, + ms / rounds as f64, + gb / (ms / 1e3) + ); +} + +pub(super) fn run() { + let workers = env("BENCH_WORKERS", 15) as i32; + let cfg = Cfg { workers, rows: env("GROUP_ROWS", 4), share: env("GROUP_SHARE", 50), rounds: env("ROUNDS", 5) }; + let (gu, down) = (GateUpFormat::Iq3S, DownFormat::Iq4Nl); + let mut rng = Rng(42); + let bank = bank(&mut rng, gu, down, env("BANK_EXPERTS", 256)); + let mut pools = Pools { + owned: CpuPool::new(workers).expect("owned pool"), + direct: DirectCpuPool::new(workers).expect("direct pool"), + }; + let groups = make_groups(&mut rng, &bank, &cfg); + let experts: usize = groups.iter().map(|(_, j)| j.len()).sum(); + let mut out = vec![0.0f32; cfg.rows * TOP_K * H]; + let base = Work { gu, down, bank: &bank, tokens: &[], jobs: &[] }; + let gb = experts as f64 * (bank[0].gate.len() * 2 + bank[0].down.len()) as f64 / 1e9; + for arm in ["owned+source-copy", "owned", "borrowed", "owned+source-copy", "owned", "borrowed"] { + let ms = time_arm(arm, &mut pools, base, &groups, &mut out); + report(arm, &cfg, experts as f64 / groups.len() as f64, (ms, gb)); + } +} diff --git a/crates/native-cpu-expert/tests/cpu_pool_probe.rs b/crates/native-cpu-expert/tests/cpu_pool_probe.rs index 2d34aecb..40dcf8ec 100644 --- a/crates/native-cpu-expert/tests/cpu_pool_probe.rs +++ b/crates/native-cpu-expert/tests/cpu_pool_probe.rs @@ -33,6 +33,47 @@ fn down_block(f: DownFormat) -> (usize, usize) { } } +/// A zero-filled job of one format pair (valid FP16 headers, so finite) over a constant activation. +fn new_job(gu: GateUpFormat, down: DownFormat, rows: usize) -> Result { + let (gq, gb) = gate_up_block(gu); + let (dq, db) = down_block(down); + let gsize = H / gq * gb * FF; + let dsize = FF / dq * db * H; + let input = vec![0.5f32; rows * H].into_boxed_slice(); + PreparedJob::new( + gu, + down, + vec![0u8; gsize].into_boxed_slice(), + vec![0u8; gsize].into_boxed_slice(), + vec![0u8; dsize].into_boxed_slice(), + input, + rows, + ) +} + +/// Runs one job of the pair through the pool and reports whether the rows come back finite. +fn probe_pair(pool: &mut CpuPool, rows: usize, gu: GateUpFormat, down: DownFormat) { + let job = match new_job(gu, down, rows) { + Ok(job) => job, + Err(e) => { + eprintln!("PREFLIGHT PreparedJob::new({gu:?}, {down:?}) ERR: {e:?}"); + return; + } + }; + let started = std::time::Instant::now(); + let result = pool.start(vec![job], 48 << 20).and_then(|pending| pending.join()); + match result { + Ok(done) => { + let finite = done.into_iter().all(|j| j.into_values().iter().all(|v| v.is_finite())); + eprintln!( + "PREFLIGHT cpu expert {gu:?} x {down:?} rows={rows} ok finite={finite} in {:?}", + started.elapsed() + ); + } + Err(e) => eprintln!("PREFLIGHT cpu expert {gu:?} x {down:?} ERR: {e:?}"), + } +} + #[test] #[ignore = "bring-up probe; no model"] fn cpu_pool_runs_every_expert_format_pair() { @@ -47,38 +88,7 @@ fn cpu_pool_runs_every_expert_format_pair() { let downs = [DownFormat::Iq4Nl, DownFormat::Q2_0]; for gu in gates { for down in downs { - let (gq, gb) = gate_up_block(gu); - let (dq, db) = down_block(down); - let gsize = H / gq * gb * FF; - let dsize = FF / dq * db * H; - let input = vec![0.5f32; rows * H].into_boxed_slice(); - let job = match PreparedJob::new( - gu, - down, - vec![0u8; gsize].into_boxed_slice(), - vec![0u8; gsize].into_boxed_slice(), - vec![0u8; dsize].into_boxed_slice(), - input, - rows, - ) { - Ok(job) => job, - Err(e) => { - eprintln!("PREFLIGHT PreparedJob::new({gu:?}, {down:?}) ERR: {e:?}"); - continue; - } - }; - let started = std::time::Instant::now(); - let result = pool.start(vec![job], 48 << 20).and_then(|pending| pending.join()); - match result { - Ok(done) => { - let finite = done.into_iter().all(|j| j.into_values().iter().all(|v| v.is_finite())); - eprintln!( - "PREFLIGHT cpu expert {gu:?} x {down:?} rows={rows} ok finite={finite} in {:?}", - started.elapsed() - ); - } - Err(e) => eprintln!("PREFLIGHT cpu expert {gu:?} x {down:?} ERR: {e:?}"), - } + probe_pair(&mut pool, rows, gu, down); } } } diff --git a/crates/native-cpu-expert/tests/cpu_service_bench.rs b/crates/native-cpu-expert/tests/cpu_service_bench.rs index ff8b1e7a..ed3f749a 100644 --- a/crates/native-cpu-expert/tests/cpu_service_bench.rs +++ b/crates/native-cpu-expert/tests/cpu_service_bench.rs @@ -1,10 +1,8 @@ //! Model-free timing of the serve path's CPU expert dispatch (`DirectCpuPool::compute_group`, the call one -//! verify-window layer makes): -//! IQ3_S gate/up and IQ4_NL down experts of the Flash-Next shape (H 2560, FF 640) with random valid blocks, cycled over -//! EXPERTS distinct -//! experts (default 256, ~600 MB, past every L3) so every call reads its weights from DRAM as the decode does. Prints -//! microseconds per call -//! and, with LELEKA_POOL_TIMING=1, the host's stage split (see `POOL_TIMING_NAMES`). +//! verify-window layer makes): IQ3_S gate/up and IQ4_NL down experts of the Flash-Next shape (H 2560, FF 640) with +//! random valid blocks, cycled over EXPERTS distinct experts (default 256, ~600 MB, past every L3) so every +//! call reads its weights from DRAM as the decode does. Prints microseconds per call and, with +//! LELEKA_POOL_TIMING=1, the host's stage split (see `POOL_TIMING_NAMES`). //! //! BENCH_WORKERS (default 15) BENCH_EXPERTS (default 256) BENCH_CALLS (default 2000) //! LELEKA_POOL_TIMING=1 cargo test --release -p leleka-native-cpu-expert --test cpu_service_bench -- --ignored @@ -51,6 +49,152 @@ struct Expert { down: Vec, } +/// The pool, the expert bank (cycled over, so every call reads cold weights) and the buffers of the benchmark. +struct Bench { + pool: DirectCpuPool, + experts: Vec, + tokens: Vec, + out: Vec, + calls: usize, +} + +/// (label, rows in the window, per expert: the token rows it serves) +type Shape<'a> = (&'a str, usize, &'a [&'a [usize]]); + +/// The scan written with an early-exit branch per block (main). +fn scan_early_exit(m: &[u8], block: usize) -> bool { + for b in m.chunks_exact(block) { + if u16::from_le_bytes([b[0], b[1]]) & 0x7c00 == 0x7c00 { + return true; + } + } + false +} + +/// The scan written branch-free. +fn scan_branch_free(m: &[u8], block: usize) -> bool { + let mut acc = 0u32; + for b in m.chunks_exact(block) { + acc |= u32::from(u16::from_le_bytes([b[0], b[1]]) & 0x7c00 == 0x7c00); + } + acc != 0 +} + +/// The single-threaded admission scan of an expert: every block's FP16 scale, as `encoded_finite::validate_row`. +fn scan_expert(x: &Expert, branch_free: bool) -> bool { + let mut bad = false; + for (m, block) in [(&x.gate, 110usize), (&x.up, 110), (&x.down, 18)] { + bad |= if branch_free { scan_branch_free(m, block) } else { scan_early_exit(m, block) }; + } + bad +} + +impl Bench { + /// One window: `members.len()` experts, each serving the listed token rows. + fn shape_call(&mut self, (rows, members): (usize, &[&[usize]]), next: &mut usize) { + let pairs: Vec> = + members.iter().enumerate().map(|(slot, toks)| toks.iter().map(|&t| (t, slot)).collect()).collect(); + let group_experts: Vec> = pairs + .iter() + .map(|p| { + let x = &self.experts[*next % self.experts.len()]; + *next += 1; + BorrowedExpert { gate: &x.gate, up: &x.up, down: &x.down, pairs: p } + }) + .collect(); + let group = BorrowedGroup { tokens: &self.tokens[..rows * H], experts: &group_experts, stride: TOP_K }; + self.pool + .compute_group(GateUpFormat::Iq3S, DownFormat::Iq4Nl, &group, &mut self.out[..rows * TOP_K * H]) + .expect("compute_group"); + } + + /// The result line of one shape: microseconds per call and per expert, GB/s, and the host's stage split. + fn shape_line(&mut self, pass: usize, label: &str, (n_members, us): (usize, f64)) -> String { + let n = n_members as f64; + let mut line = format!( + "pass {pass} {label}: {us:.1} us per call, {:.1} us per expert, {:.1} GB/s", + us / n, + n * 2.33e6 / us / 1e3 + ); + if let Some(t) = self.pool.take_timing() { + line.push_str(" |"); + for (name, ms) in POOL_TIMING_NAMES.iter().zip(t) { + line.push_str(&format!(" {}={:.1}", name.trim_start_matches("cpu.t."), ms * 1e3 / self.calls as f64)); + } + } + line + } + + fn run_shape(&mut self, pass: usize, (label, rows, members): Shape) { + let mut next = 0usize; + let _ = self.pool.take_timing(); + let start = std::time::Instant::now(); + for _ in 0..self.calls { + self.shape_call((rows, members), &mut next); + } + let us = start.elapsed().as_secs_f64() * 1e6 / self.calls as f64; + let line = self.shape_line(pass, label, (members.len(), us)); + eprintln!("{line}"); + } + + /// First use of an expert in the serve path: the single-threaded admission scan then the compute. + fn first_use(&mut self, pass: usize, branch_free: bool) { + let mut next = 0usize; + let pairs = [(0usize, 0usize)]; + let start = std::time::Instant::now(); + let mut t_scan = 0.0f64; + for _ in 0..self.calls { + let x = &self.experts[next % self.experts.len()]; + next += 1; + let t1 = std::time::Instant::now(); + assert!(!std::hint::black_box(scan_expert(x, branch_free))); + t_scan += t1.elapsed().as_secs_f64(); + let e = [BorrowedExpert { gate: &x.gate, up: &x.up, down: &x.down, pairs: &pairs }]; + let group = BorrowedGroup { tokens: &self.tokens[..H], experts: &e, stride: TOP_K }; + self.pool + .compute_group(GateUpFormat::Iq3S, DownFormat::Iq4Nl, &group, &mut self.out[..TOP_K * H]) + .expect("compute_group"); + } + let _ = self.pool.take_timing(); + eprintln!( + "pass {pass} first use, branch_free={branch_free}: {:.1} us per expert (scan {:.1}, compute the rest)", + start.elapsed().as_secs_f64() * 1e6 / self.calls as f64, + t_scan * 1e6 / self.calls as f64 + ); + } +} + +fn make_experts(rng: &mut Rng, count: usize) -> Vec { + (0..count) + .map(|_| Expert { + gate: blocks(rng, FF * H / 256, 110), + up: blocks(rng, FF * H / 256, 110), + down: blocks(rng, H * FF / 32, 18), + }) + .collect() +} + +/// The pool, or None (with a note) where it does not start. +fn open_pool(workers: i32) -> Option { + match DirectCpuPool::new(workers) { + Ok(p) => Some(p), + Err(e) => { + eprintln!("SKIP: pool did not start ({e:?})"); + None + } + } +} + +fn shapes() -> [Shape<'static>; 5] { + [ + ("1 expert x 1 token", 1, &[&[0]]), + ("2 experts x 1 token", 2, &[&[0], &[1]]), + ("3 experts x 1 token", 3, &[&[0], &[1], &[2]]), + ("1 expert x 2 tokens", 2, &[&[0, 1]]), + ("1 expert x 3 tokens", 3, &[&[0, 1, 2]]), + ] +} + #[test] #[ignore = "benchmark; no model"] fn cpu_service_bench() { @@ -58,108 +202,18 @@ fn cpu_service_bench() { let n_experts = env_usize("BENCH_EXPERTS", 256); let calls = env_usize("BENCH_CALLS", 2000); let mut rng = Rng(0x5eed_cafe_f00d_1234); - let experts: Vec = (0..n_experts) - .map(|_| Expert { - gate: blocks(&mut rng, FF * H / 256, 110), - up: blocks(&mut rng, FF * H / 256, 110), - down: blocks(&mut rng, H * FF / 32, 18), - }) - .collect(); - let mut pool = match DirectCpuPool::new(workers) { - Ok(p) => p, - Err(e) => { - eprintln!("SKIP: pool did not start ({e:?})"); - return; - } - }; + let experts = make_experts(&mut rng, n_experts); + let Some(pool) = open_pool(workers) else { return }; let tokens_max = 4usize; let tokens: Vec = (0..tokens_max * H).map(|_| (rng.next() % 2001) as f32 / 1000.0 - 1.0).collect(); - let mut out = vec![0.0f32; tokens_max * TOP_K * H]; - // (label, rows in the window, per expert: the token rows it serves) - let shapes: [(&str, usize, &[&[usize]]); 5] = [ - ("1 expert x 1 token", 1, &[&[0]]), - ("2 experts x 1 token", 2, &[&[0], &[1]]), - ("3 experts x 1 token", 3, &[&[0], &[1], &[2]]), - ("1 expert x 2 tokens", 2, &[&[0, 1]]), - ("1 expert x 3 tokens", 3, &[&[0, 1, 2]]), - ]; + let out = vec![0.0f32; tokens_max * TOP_K * H]; + let mut bench = Bench { pool, experts, tokens, out, calls }; for pass in 0..2 { - for (label, rows, members) in shapes { - let mut next = 0usize; - let _ = pool.take_timing(); - let start = std::time::Instant::now(); - for _ in 0..calls { - let pairs: Vec> = - members.iter().enumerate().map(|(slot, toks)| toks.iter().map(|&t| (t, slot)).collect()).collect(); - let group_experts: Vec> = pairs - .iter() - .map(|p| { - let x = &experts[next % n_experts]; - next += 1; - BorrowedExpert { gate: &x.gate, up: &x.up, down: &x.down, pairs: p } - }) - .collect(); - let group = BorrowedGroup { tokens: &tokens[..rows * H], experts: &group_experts, stride: TOP_K }; - pool.compute_group(GateUpFormat::Iq3S, DownFormat::Iq4Nl, &group, &mut out[..rows * TOP_K * H]) - .expect("compute_group"); - } - let us = start.elapsed().as_secs_f64() * 1e6 / calls as f64; - let n = members.len() as f64; - let mut line = format!( - "pass {pass} {label}: {us:.1} us per call, {:.1} us per expert, {:.1} GB/s", - us / n, - n * 2.33e6 / us / 1e3 - ); - if let Some(t) = pool.take_timing() { - line.push_str(" |"); - for (name, ms) in POOL_TIMING_NAMES.iter().zip(t) { - line.push_str(&format!(" {}={:.1}", name.trim_start_matches("cpu.t."), ms * 1e3 / calls as f64)); - } - } - eprintln!("{line}"); + for shape in shapes() { + bench.run_shape(pass, shape); } - // First use of an expert in the serve path: the single-threaded admission scan (every block's FP16 scale, as - // `encoded_finite::validate_row`) then the compute; the scan written with an early-exit branch per block (main) - // and branch-free. for branch_free in [false, true] { - let mut next = 0usize; - let pairs = [(0usize, 0usize)]; - let start = std::time::Instant::now(); - let mut t_scan = 0.0f64; - for _ in 0..calls { - let x = &experts[next % n_experts]; - next += 1; - let t1 = std::time::Instant::now(); - let mut bad = false; - for (m, block) in [(&x.gate, 110usize), (&x.up, 110), (&x.down, 18)] { - if branch_free { - let mut acc = 0u32; - for b in m.chunks_exact(block) { - acc |= u32::from(u16::from_le_bytes([b[0], b[1]]) & 0x7c00 == 0x7c00); - } - bad |= acc != 0; - } else { - for b in m.chunks_exact(block) { - if u16::from_le_bytes([b[0], b[1]]) & 0x7c00 == 0x7c00 { - bad = true; - break; - } - } - } - } - assert!(!std::hint::black_box(bad)); - t_scan += t1.elapsed().as_secs_f64(); - let e = [BorrowedExpert { gate: &x.gate, up: &x.up, down: &x.down, pairs: &pairs }]; - let group = BorrowedGroup { tokens: &tokens[..H], experts: &e, stride: TOP_K }; - pool.compute_group(GateUpFormat::Iq3S, DownFormat::Iq4Nl, &group, &mut out[..TOP_K * H]) - .expect("compute_group"); - } - let _ = pool.take_timing(); - eprintln!( - "pass {pass} first use, branch_free={branch_free}: {:.1} us per expert (scan {:.1}, compute the rest)", - start.elapsed().as_secs_f64() * 1e6 / calls as f64, - t_scan * 1e6 / calls as f64 - ); + bench.first_use(pass, branch_free); } } } diff --git a/crates/native-cpu-expert/tests/pool_lifecycle.rs b/crates/native-cpu-expert/tests/pool_lifecycle.rs index 888e6fbe..e9e12317 100644 --- a/crates/native-cpu-expert/tests/pool_lifecycle.rs +++ b/crates/native-cpu-expert/tests/pool_lifecycle.rs @@ -109,8 +109,7 @@ fn run( } /// Dropping the pool must stop AND join every worker: no thread may outlive it (a worker that survived `Drop` could -/// still -/// hold raw pointers into caller memory), including after a refused (non-finite) group. +/// still hold raw pointers into caller memory), including after a refused (non-finite) group. #[test] fn dropping_the_pool_joins_every_worker() { let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner()); @@ -131,11 +130,9 @@ fn dropping_the_pool_joins_every_worker() { } /// Back-to-back groups separated by idle gaps shorter and longer than the 20 ms spin window (workers spinning, then -/// asleep -/// on the condvar, then woken while a new epoch is published) must stay bit-identical to the first result. A delayed -/// sleeper carrying an old epoch into the claim, or a host that mutated the batch before every worker parked, would -/// show -/// up as a changed or missing output row. +/// asleep on the condvar, then woken while a new epoch is published) must stay bit-identical to the first +/// result. A delayed sleeper carrying an old epoch into the claim, or a host that mutated the batch before every +/// worker parked, would show up as a changed or missing output row. #[test] fn repeated_groups_across_idle_gaps_are_bit_identical() { let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner()); @@ -177,23 +174,20 @@ fn settles_named(prefix: &str, expected: usize) -> bool { threads_named(prefix) == expected } -/// The owned-batch coordinator (`CpuPool`: a coordinator thread that owns the native pool, jobs moved by value) must -/// join the -/// coordinator and all its workers on drop, after a completed batch. -#[test] -fn owned_pool_drop_joins_coordinator_and_workers() { - use leleka_native_cpu_expert::{CpuPool, PreparedJob}; - let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner()); - assert_eq!(threads_named("leleka-cpu-miss"), 0); - let mut owned = match CpuPool::new(2) { - Ok(pool) => pool, +/// The owned-batch pool of two workers, or None (with a note) where it is unavailable. +fn owned_pool() -> Option { + match leleka_native_cpu_expert::CpuPool::new(2) { + Ok(pool) => Some(pool), Err(error) => { eprintln!("SKIP: CPU expert pool unavailable here: {error:?}"); - return; + None } - }; - let bank = bank(1); - let job = PreparedJob::new( + } +} + +/// The first expert of `bank` as one owned job over a single token row. +fn prepared_job(bank: &[Expert]) -> leleka_native_cpu_expert::PreparedJob { + leleka_native_cpu_expert::PreparedJob::new( GU, DOWN, bank[0].gate.clone().into_boxed_slice(), @@ -202,8 +196,18 @@ fn owned_pool_drop_joins_coordinator_and_workers() { tokens(1).into_boxed_slice(), 1, ) - .expect("prepared job"); - let done = owned.start(vec![job], 64 << 20).expect("start").join().expect("join"); + .expect("prepared job") +} + +/// The owned-batch coordinator (`CpuPool`: a coordinator thread that owns the native pool, jobs moved by value) must +/// join the coordinator and all its workers on drop, after a completed batch. +#[test] +fn owned_pool_drop_joins_coordinator_and_workers() { + let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner()); + assert_eq!(threads_named("leleka-cpu-miss"), 0); + let Some(mut owned) = owned_pool() else { return }; + let bank = bank(1); + let done = owned.start(vec![prepared_job(&bank)], 64 << 20).expect("start").join().expect("join"); assert_eq!(done.len(), 1); assert!(done.into_iter().next().expect("one job").into_values().iter().all(|v| v.is_finite())); assert_eq!(threads_named("leleka-cpu-miss"), 1); diff --git a/crates/native-cpu-expert/tests/token_count_invariance.rs b/crates/native-cpu-expert/tests/token_count_invariance.rs index f52b9abe..a36225a8 100644 --- a/crates/native-cpu-expert/tests/token_count_invariance.rs +++ b/crates/native-cpu-expert/tests/token_count_invariance.rs @@ -1,13 +1,9 @@ //! STRA-329: a token's expert output must not depend on how many other tokens share its expert once the multi-token -//! kernels are in -//! (from `STRATA_IQ_MT_MIN`, default 2 tokens; native_expert.cpp native_gu_rows "#152"). Checks every gate/up x down -//! pair, including the -//! IQ2_XXS / IQ2_XS gate/up the KAB1 `ext` case set adds, at every token count 2..=8: the first two tokens of a group -//! of n tokens must -//! equal, bit for bit, the same two tokens run as a group of two. One token is excluded on purpose (ggml's per-token -//! dot rounds -//! differently, the very reason for the rule). Rust only: no C++ reference, no GPU. Synthetic blobs: random codes, -//! finite FP16 scales. +//! kernels are in (from `STRATA_IQ_MT_MIN`, default 2 tokens; native_expert.cpp native_gu_rows "#152"). Checks +//! every gate/up x down pair, including the IQ2_XXS / IQ2_XS gate/up the KAB1 `ext` case set adds, at every +//! token count 2..=8: the first two tokens of a group of n tokens must equal, bit for bit, the same two tokens +//! run as a group of two. One token is excluded on purpose (ggml's per-token dot rounds differently, the very +//! reason for the rule). Rust only: no C++ reference, no GPU. Synthetic blobs: random codes, finite FP16 scales. //! //! cargo test -p leleka-native-cpu-expert --test token_count_invariance use leleka_native_cpu_expert::{CpuPool, DownFormat, GateUpFormat, PreparedJob}; @@ -55,8 +51,7 @@ fn matrix(rng: &mut Rng, bytes: usize, block: usize) -> Vec { fn run( pool: &mut CpuPool, - gu: GateUpFormat, - down: DownFormat, + (gu, down): (GateUpFormat, DownFormat), blobs: &[Vec; 3], tokens: &[f32], n: usize, @@ -79,41 +74,55 @@ fn run( done.into_iter().next().expect("one job").into_values().to_vec() } +const GATES: [GateUpFormat; 7] = [ + GateUpFormat::Iq2Xxs, + GateUpFormat::Iq2Xs, + GateUpFormat::Iq3Xxs, + GateUpFormat::Iq3S, + GateUpFormat::Iq2S, + GateUpFormat::Iq4Xs, + GateUpFormat::Q2_0, +]; + +/// The gate, up and down blobs of one format pair. +fn blobs_for(rng: &mut Rng, gu: GateUpFormat, down: DownFormat) -> [Vec; 3] { + let (gq, gb) = gate_up_block(gu); + let (dq, db) = down_block(down); + [matrix(rng, H / gq * gb * FF, gb), matrix(rng, H / gq * gb * FF, gb), matrix(rng, FF / dq * db * H, db)] +} + +fn random_tokens(rng: &mut Rng) -> Vec { + (0..8 * H).map(|_| (rng.next() >> 40) as f32 / (1u64 << 24) as f32 * 2.0 - 1.0).collect() +} + +/// The first two tokens of a group of `n` tokens equal, bit for bit, the same two tokens run as a group of two. +fn assert_first_two_equal(base: &[f32], wide: &[f32], (gu, down): (GateUpFormat, DownFormat), n: usize) { + for i in 0..2 * H { + assert_eq!( + wide[i].to_bits(), + base[i].to_bits(), + "{gu:?} + {down:?}: {n} tokens differ from 2 tokens at output {i}" + ); + } +} + +/// One format pair at every token count 3..=8 against the group of two. +fn check_pair(pool: &mut CpuPool, rng: &mut Rng, pair: (GateUpFormat, DownFormat)) { + let blobs = blobs_for(rng, pair.0, pair.1); + let tokens = random_tokens(rng); + let base = run(pool, pair, &blobs, &tokens, 2); + for n in 3..=8 { + assert_first_two_equal(&base, &run(pool, pair, &blobs, &tokens, n), pair, n); + } +} + #[test] fn the_first_two_tokens_do_not_depend_on_the_group_size() { let mut pool = CpuPool::new(1).expect("pool"); let mut rng = Rng(0x0329_5eed_9e37_79b9); - let gates = [ - GateUpFormat::Iq2Xxs, - GateUpFormat::Iq2Xs, - GateUpFormat::Iq3Xxs, - GateUpFormat::Iq3S, - GateUpFormat::Iq2S, - GateUpFormat::Iq4Xs, - GateUpFormat::Q2_0, - ]; - for gu in gates { + for gu in GATES { for down in [DownFormat::Iq4Nl, DownFormat::Q2_0] { - let (gq, gb) = gate_up_block(gu); - let (dq, db) = down_block(down); - let blobs = [ - matrix(&mut rng, H / gq * gb * FF, gb), - matrix(&mut rng, H / gq * gb * FF, gb), - matrix(&mut rng, FF / dq * db * H, db), - ]; - let tokens: Vec = - (0..8 * H).map(|_| ((rng.next() >> 40) as f32 / (1u64 << 24) as f32 * 2.0 - 1.0)).collect(); - let base = run(&mut pool, gu, down, &blobs, &tokens, 2); - for n in 3..=8 { - let wide = run(&mut pool, gu, down, &blobs, &tokens, n); - for i in 0..2 * H { - assert_eq!( - wide[i].to_bits(), - base[i].to_bits(), - "{gu:?} + {down:?}: {n} tokens differ from 2 tokens at output {i}" - ); - } - } + check_pair(&mut pool, &mut rng, (gu, down)); } } }