kernel_ab pool-window: the real CPU expert pool on a large replicated bank, HOT against COLD windows; stub for the kernel resident/streamed and pool-window benchmarks (CPU only); notes on the vanilla trace and the existing tasks-per-thread knob

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-11-12 18:54:53 +01:00
co-authored by Claude Sonnet 5.5
parent 78d148dd31
commit b9d652df56
4 changed files with 225 additions and 2 deletions
@@ -0,0 +1,179 @@
//! `kernel_ab pool-window` (test tooling): the real pool (`DirectCpuPool`, all its workers) on one verified case's
//! expert bytes replicated into a large role-major bank (gate, up and down in three separate arenas, like the GGUF
//! tensors), one `compute_group` per layer window of `k` experts. HOT windows reuse the same `k` experts (their rows
//! stay in the cores' caches: the compute cost of the pool); COLD windows pick `k` distinct random experts of the bank
//! (4 GiB and more, far over every cache: the memory cost). With `LELEKA_POOL_TIMING=layers` the per-phase task times
//! of the pool are printed as well.
//!
//! kernel_ab pool-window --run-dir D --case ID [--workers 15] [--bank-experts 2048] [--ks 1,2,3,4] [--windows 400]
//! [--seed S]
#[allow(unused_imports)]
use super::*;
use leleka_native_cpu_expert::PhaseTrace;
const WARM_UP: usize = 20;
struct WindowArgs {
dir: PathBuf,
case: String,
workers: i32,
bank: usize,
ks: Vec<usize>,
windows: usize,
seed: u64,
}
fn parse_window_args(args: &[String]) -> Result<WindowArgs, String> {
let known = ["run-dir", "case", "workers", "bank-experts", "ks", "windows", "seed"];
let f = Flags::parse(args, &known)?;
let ks = f.get("ks").unwrap_or("1,2,3,4").split(',').map(|s| s.parse::<usize>().map_err(|e| e.to_string()));
Ok(WindowArgs {
dir: PathBuf::from(f.req("run-dir")?),
case: f.req("case")?.to_owned(),
workers: f.number("workers")?.unwrap_or(15),
bank: f.number("bank-experts")?.unwrap_or(2048),
ks: ks.collect::<Result<Vec<_>, _>>()?,
windows: f.number("windows")?.unwrap_or(400),
seed: f.number("seed")?.unwrap_or(1),
})
}
/// The case's gate, up and down matrices copied `n` times into three arenas.
struct Bank {
gate: Vec<u8>,
up: Vec<u8>,
down: Vec<u8>,
sizes: (usize, usize, usize),
}
impl Bank {
fn new(case: &CaseIn, n: usize) -> Self {
let rep = |one: &[u8]| {
let mut v = Vec::with_capacity(one.len() * n);
for _ in 0..n {
v.extend_from_slice(one);
}
v
};
let sizes = (case.gate().len(), case.up().len(), case.down().len());
Self { gate: rep(case.gate()), up: rep(case.up()), down: rep(case.down()), sizes }
}
fn expert<'a>(&'a self, e: usize, pairs: &'a [(usize, usize)]) -> BorrowedExpert<'a> {
let (g, u, d) = self.sizes;
BorrowedExpert {
gate: &self.gate[e * g..(e + 1) * g],
up: &self.up[e * u..(e + 1) * u],
down: &self.down[e * d..(e + 1) * d],
pairs,
}
}
}
/// What one window cost: the caller's wall time and the pool's phase traces (empty unless traced).
struct Sample {
wall_us: f64,
phases: Vec<PhaseTrace>,
}
struct Runner<'a> {
pool: DirectCpuPool,
gu: GateUpFormat,
down: DownFormat,
tokens: &'a [f32],
rows: usize,
}
impl Runner<'_> {
fn window(&mut self, bank: &Bank, ids: &[usize]) -> Result<Sample, String> {
let rows = self.rows;
let pair_list = |s: usize| (0..rows).map(|t| (t, s)).collect::<Vec<_>>();
let pairs: Vec<Vec<(usize, usize)>> = (0..ids.len()).map(pair_list).collect();
let experts: Vec<BorrowedExpert> = ids.iter().zip(&pairs).map(|(&e, p)| bank.expert(e, p)).collect();
let group = BorrowedGroup { tokens: self.tokens, experts: &experts, stride: ids.len() };
let mut out = vec![0.0f32; self.rows * ids.len() * H];
let t0 = mono_ns();
self.pool.compute_group(self.gu, self.down, &group, &mut out).map_err(|e| format!("compute_group: {e:?}"))?;
let wall_us = (mono_ns() - t0) as f64 / 1e3;
Ok(Sample { wall_us, phases: self.pool.take_trace() })
}
}
/// `k` distinct experts of `n`, by a xorshift stream.
fn pick(state: &mut u64, k: usize, n: usize) -> Vec<usize> {
let mut ids: Vec<usize> = Vec::new();
while ids.len() < k {
*state ^= *state << 13;
*state ^= *state >> 7;
*state ^= *state << 17;
let e = (*state % n as u64) as usize;
if !ids.contains(&e) {
ids.push(e);
}
}
ids
}
fn phase_values(samples: &[Sample], mode: u32, f: impl Fn(&PhaseTrace) -> f64) -> Vec<f64> {
samples.iter().flat_map(|s| s.phases.iter().filter(|p| p.mode == mode).map(&f)).collect()
}
fn spread(v: &[f64]) -> String {
format!("{:6.1} {:6.1} {:6.1}", median_of(v), percentile_of(v, 0.75), percentile_of(v, 0.9))
}
fn task_p50(p: &PhaseTrace) -> f64 {
let t: Vec<f64> = p.task_ns.iter().map(|&n| f64::from(n) / 1e3).collect();
median_of(&t)
}
fn report(regime: &str, k: usize, samples: &[Sample]) {
let wall: Vec<f64> = samples.iter().map(|s| s.wall_us).collect();
println!("pool-window {regime} k={k} n={} wall_us p50/p75/p90 {}", samples.len(), spread(&wall));
if samples.iter().all(|s| s.phases.is_empty()) {
return;
}
for (mode, name) in [(5, "m5 gate/up"), (6, "m6 down")] {
let w = phase_values(samples, mode, |p| p.wall_ns as f64 / 1e3);
let task = phase_values(samples, mode, task_p50);
println!(" {name}: wall_us p50/p75/p90 {} | task_us p50 {:.1}", spread(&w), median_of(&task));
}
}
fn run_k(r: &mut Runner, bank: &Bank, a: &WindowArgs, k: usize) -> Result<(), String> {
let hot_ids: Vec<usize> = (0..k).collect();
let mut state = a.seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1;
for (regime, cold) in [("HOT ", false), ("COLD", true)] {
let mut samples = Vec::new();
for i in 0..WARM_UP + a.windows {
let ids = if cold { pick(&mut state, k, a.bank) } else { hot_ids.clone() };
let s = r.window(bank, &ids)?;
if i >= WARM_UP {
samples.push(s);
}
}
report(regime, k, &samples);
}
Ok(())
}
/// `kernel_ab pool-window ...`
pub(super) fn cmd_pool_window(args: &[String]) -> Result<ExitCode, String> {
let a = parse_window_args(args)?;
let (_, _, cases, _) = read_manifest(&a.dir).map_err(|e| e.to_string())?;
let entry = cases.iter().find(|c| c.id == a.case).ok_or_else(|| format!("case {} is not in the manifest", a.case))?;
let case = read_case_in(&a.dir, entry).map_err(|e| e.to_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);
let bank = Bank::new(&case, a.bank);
let pool = DirectCpuPool::new(a.workers).map_err(|e| format!("DirectCpuPool::new: {e:?}"))?;
println!("pool-window case={} workers={} bank={} experts ({} MiB)", a.case, pool.workers(), a.bank, {
a.bank * (bank.sizes.0 + bank.sizes.1 + bank.sizes.2) >> 20
});
let tokens = case.input();
let mut runner = Runner { pool, gu, down, tokens: &tokens, rows: case.header.rows };
for &k in &a.ks {
run_k(&mut runner, &bank, &a, k)?;
}
Ok(ExitCode::SUCCESS)
}
@@ -40,6 +40,11 @@
//! statistics: no class, no interval, no A/A verdict (those are S0.10b,
//! STRA-313).
//!
//! kernel_ab pool-window --run-dir D --case ID [--workers 15] [--bank-experts 2048] [--ks 1,2,3,4] [--windows 400]
//! the real pool on a large replicated expert bank: HOT windows (same
//! experts, cache-resident) against COLD windows (random experts of the
//! bank); `cmd_pool_window.rs`
//!
//! cargo run --release -p leleka-native-cpu-expert --example kernel_ab -- compare D
//! cargo test -p leleka-native-cpu-expert --example kernel_ab
@@ -62,7 +67,11 @@ thread_local! { static BUFFERS: Cell<usize> = const { Cell::new(0) }; }
/// `time` and `alternate` take flags only (the command line of `kab time`).
fn flag_command(cmd: &str, rest: &[String]) -> ExitCode {
let result = if cmd == "time" { cmd_time(rest) } else { cmd_alternate(rest) };
let result = match cmd {
"time" => cmd_time(rest),
"pool-window" => cmd_pool_window(rest),
_ => cmd_alternate(rest),
};
result.unwrap_or_else(|e| {
eprintln!("kernel_ab {cmd}: {e}");
ExitCode::from(1)
@@ -86,7 +95,7 @@ fn verify_command(dir: &Path) -> Result<ExitCode, String> {
fn main() -> ExitCode {
let args: Vec<String> = std::env::args().skip(1).collect();
// the older commands take the directory first
if let Some(cmd @ ("time" | "alternate")) = args.first().map(String::as_str) {
if let Some(cmd @ ("time" | "alternate" | "pool-window")) = args.first().map(String::as_str) {
return flag_command(cmd, &args[1..]);
}
let (Some(cmd), Some(dir)) = (args.first(), args.get(1)) else { return usage() };
@@ -155,6 +164,9 @@ use run_regime::{f32_bits_sha, run_regime};
mod cmd_time;
#[allow(unused_imports)]
use cmd_time::cmd_time;
mod cmd_pool_window;
#[allow(unused_imports)]
use cmd_pool_window::cmd_pool_window;
mod regime_schedule;
#[allow(unused_imports)]
use regime_schedule::{
+6
View File
@@ -35,3 +35,9 @@ The pool always has 48 tasks (3 x 16 threads: 15 workers + host), whatever the e
- Finer tasks at the end of a phase (guided / halving chunk: 3 -> 5-6 tasks per thread, claim cost about 50 ns each): expected tail 17 -> about 9 us at two experts, 6-12 us per window; non-lossy (same arithmetic, same outputs), numerical identity by tensor compare.
- Gate/up kernel (58 us per expert against down 20 us for half the bytes): compare with the vanilla C++ kernel per task (Rust vs C++ were within 6 % in the earlier kernel bench), look at the activation quantisation shared by the 48 tasks and at prefetching the next task's rows.
- Fewer CPU experts per window (more VRAM slots, higher PCIe share) moves the cost out of this linear regime; the quota=no + PCIe 0.65 default is exactly this lever (about 10 % fewer non-resident experts).
## Follow-up (orchestrator, 2026-11-12): kernel micro-benchmarks, no GPU
1. The vanilla `STRATA_POOL_TRACE` log (`host-vanilla-tier-experts-per-layer-pool-trace`, 153 MB) has NO timestamps (`pool trace: layer L run n`), so a per-expert time of the Original cannot be read from it; it gives counts only. Instead: the Original's C++ kernel is timed by `kab time` (resident against streamed) and our Rust twin by `kernel_ab time`; the Original pool is structurally the same as ours (`pool.cpp phase_tasks` = 3 tasks per thread; the Rust pool is its port), so the window time of the Original is the same function of the expert count unless the kernel or the memory differ. Existing C++ record (`/data/leleka-e2e/runs/kernel-ab-317/t-18-20-r1.json`, case IQ3_XXS/IQ4_NL, one row, one thread, pinned, 2.176 MB per expert): RESIDENT 211.6 us, STREAMED (67 MB over a 32 MB LLC) 217.7 us (+3 %): the one-thread kernel is arithmetic-bound (about 10 GB/s per thread, memory adds 3 %). The pool needs about 990 us of thread time per expert (16 threads x (3 x 15.3 us gate/up + 3 x 5.3 us down)): 4-5 times the one-thread kernel. Candidate causes: cold bank (TLB, DRAM latency of the first touch of each 2 MB expert), SMT/clock when 16 threads run, other busy threads. Decided by step 2.
2. `kernel_ab pool-window` (`crates/native-cpu-expert/examples/kernel_ab/cmd_pool_window.rs`, test tooling): the real pool on a 4.4 GiB role-major bank of one verified case, HOT windows (same experts) against COLD windows (random experts), k = 1..4, workers 15 / 7 / 3. Stub `scripts/e2e/codex/prefill/kernel/cpu-expert-kernel-resident-vs-streamed-and-pool-window-hot-vs-cold-iq3s.sh` (CPU only, queued behind the KAR e2e; also runs `kab time` and `kernel_ab time` on case 21-20 = IQ3_S + IQ4_NL). Reading: HOT about the same as COLD means compute/pool; COLD much above HOT means the memory system.
3. Finer tasks need no code: `LELEKA_POOL_TASKS_PER_THREAD` (1..16, default 3) already exists and changes only the row-to-task split ("every row is computed by the same code whatever task holds it, so the output does not depend on it"). The same stub measures 6 and 1 in the pool bench; the identity (tensor compare of the pool output across the knob, then the 2057/1036 identity jobs) and the section delta in a group A/B follow if the bench shows a gain.
@@ -0,0 +1,26 @@
#!/usr/bin/env bash
# Stage 6b step 2 (CPU only, no GPU, no model): is the CPU expert time memory-bound or arithmetic-bound, and where does the pool lose against one thread?
# A. one thread, pinned, the Original's C++ kernel (`kab time`) and our Rust twin (`kernel_ab time`) on the IQ3_S gate/up + IQ4_NL down case 21-20 (rows 1 and 3): RESIDENT (cache) against STREAMED (over the LLC) ns per expert.
# B. the real pool (`kernel_ab pool-window`, cmd_pool_window.rs) on a 4.4 GiB role-major bank of that expert: HOT windows (same k experts, cache-resident) against COLD windows (random experts), k = 1..4, workers 15 / 7 / 3, and 15 workers with LELEKA_POOL_TASKS_PER_THREAD=6 (finer tasks).
# Run it only when no engine runs (it needs all cores). Inputs: the C++ run directory (frozen) and the two tools below.
set -u
T=/data/leleka-e2e/prefill-latency/tools
OUT=/data/leleka-e2e/prefill-latency/runs/cpu-expert-kernel-resident-vs-streamed-and-pool-window-hot-vs-cold-iq3s
D=/data/leleka-e2e/runs/kernel-ab/final
KAB=/data/leleka-e2e/build/kernel-ab-317/kab
RB=$T/kernel_ab-pool-window
mkdir -p "$OUT"
( cd "$T" && sha256sum -c --ignore-missing SHA256SUMS ) >"$OUT/tools-check.txt" 2>&1 || { echo "tool digest mismatch" >&2; exit 1; }
sha256sum "$KAB" "$RB" >"$OUT/tools.sha256"
lscpu >"$OUT/lscpu.txt"; cat /sys/kernel/mm/transparent_hugepage/enabled >"$OUT/thp.txt"; free -m >"$OUT/free.txt"
for c in 21-20-r1 21-20-r3; do
"$KAB" time --run-dir "$D" --case "$c" --slices 50 --pin 9 --out "$OUT/kab-cpp-$c.json" >"$OUT/kab-cpp-$c.log" 2>&1
"$RB" time --run-dir "$D" --case "$c" --slices 50 --pin 9 --out "$OUT/kab-rust-$c.json" >"$OUT/kab-rust-$c.log" 2>&1
done
export LELEKA_POOL_TIMING=layers
for w in 15 7 3; do
"$RB" pool-window --run-dir "$D" --case 21-20-r1 --workers "$w" --ks 1,2,3,4 --windows 400 >"$OUT/pool-window-w$w.txt" 2>&1
done
LELEKA_POOL_TASKS_PER_THREAD=6 "$RB" pool-window --run-dir "$D" --case 21-20-r1 --workers 15 --ks 1,2,3,4 --windows 400 >"$OUT/pool-window-w15-tpt6.txt" 2>&1
LELEKA_POOL_TASKS_PER_THREAD=1 "$RB" pool-window --run-dir "$D" --case 21-20-r1 --workers 15 --ks 1,2,3,4 --windows 400 >"$OUT/pool-window-w15-tpt1.txt" 2>&1
echo done >"$OUT/DONE"