Files
leleka/crates/gptoss-npu/examples/ab_prefill_npu.rs
T
Pavlo RatushnyiandClaude Sonnet 5.5 8d96e9c44c perf: overlap weight expansion with NPU execution, batch products, SIMD half conversion, graph cache (STRA-207)
- service: BATCH n lets it see each product's successor and expand the next weights on a thread
  while the device runs the current one; buckets up to 4096; OpenVINO CACHE_DIR compile cache
- client: batched expert products, layout sized by batch, default batch 2048
- cpu-sys/cpu-kernels: AVX2 F16C f16_to_f32 kernel, exact for every half bit pattern
- npu-worker: memory admission before an NPU prefill (falls back to the CPU when RAM is short)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-15 12:22:13 +02:00

206 lines
7.3 KiB
Rust

//! Paired A/B of the prompt-processing speed: the CPU decoder against the NPU prefill, same prompts, runs
//! alternating in order (CPU first, then GPU first, ...) with a fresh cache each time, in one process so that
//! the page cache and the machine state are shared. Warm only: each path is run once untimed first. Prints
//! every run, the distribution per path and the paired speed-up with a 95% confidence interval.
//!
//! Run: `cargo run --release -p leleka-gptoss-npu --example ab_prefill_npu -- <model.gguf> <openvino root> <service exe> <device> <tokens[,tokens...]> <pairs> [batch]`
//! Set `LELEKA_MODEL_SHA256` to record the model digest in the report.
use leleka_cpu_kernels::Dispatch;
use leleka_cpu_sys::mapping::Mapping;
use leleka_gguf::Gguf;
use leleka_gptoss::{Model, State};
use leleka_gptoss_npu::NpuPrefill;
use leleka_gptoss_npu::client::ServiceConfig;
use std::fs::File;
use std::io::BufReader;
use std::path::Path;
use std::time::Instant;
fn synth(n: usize) -> Vec<u32> {
let mut s = 0x2545_F491_4F6C_DD1Du64;
(0..n)
.map(|_| {
s ^= s << 13;
s ^= s >> 7;
s ^= s << 17;
1000 + (s % 60_000) as u32
})
.collect()
}
/// Two-sided 95% Student t critical values for 1..=30 degrees of freedom.
fn t95(df: usize) -> f64 {
const T: [f64; 30] = [
12.706, 4.303, 3.182, 2.776, 2.571, 2.447, 2.365, 2.306, 2.262, 2.228, 2.201, 2.179, 2.160,
2.145, 2.131, 2.120, 2.110, 2.101, 2.093, 2.086, 2.080, 2.074, 2.069, 2.064, 2.060, 2.056,
2.052, 2.048, 2.045, 2.042,
];
T[df.clamp(1, 30) - 1]
}
fn mean_sd(x: &[f64]) -> (f64, f64) {
let m = x.iter().sum::<f64>() / x.len() as f64;
let var = if x.len() > 1 {
x.iter().map(|v| (v - m) * (v - m)).sum::<f64>() / (x.len() - 1) as f64
} else {
0.0
};
(m, var.sqrt())
}
fn median(x: &[f64]) -> f64 {
let mut v = x.to_vec();
v.sort_by(|a, b| a.total_cmp(b));
let n = v.len();
if n % 2 == 1 {
v[n / 2]
} else {
(v[n / 2 - 1] + v[n / 2]) / 2.0
}
}
fn main() {
let args: Vec<String> = std::env::args().skip(1).collect();
if args.len() < 6 {
eprintln!(
"usage: ab_prefill_npu <model.gguf> <openvino root> <service exe> <device> <tokens[,tokens...]> <pairs> [batch]"
);
std::process::exit(2);
}
let sizes: Vec<usize> = args[4]
.split(',')
.map(|s| s.trim().parse().expect("token count"))
.collect();
let pairs: usize = args[5].parse().expect("pairs");
let batch: usize = args
.get(6)
.and_then(|s| s.parse().ok())
.unwrap_or(leleka_gptoss_npu::DEFAULT_BATCH);
let path = Path::new(&args[0]);
let size = std::fs::metadata(path).expect("model file").len();
let gguf = Gguf::read(
BufReader::with_capacity(1 << 20, File::open(path).expect("open")),
size,
)
.expect("valid GGUF");
let threads = std::thread::available_parallelism().map_or(1, |n| n.get());
let dispatch = Dispatch::from_env().expect("kernel level");
let isa = dispatch.isa();
let model = Model::load(
std::sync::Arc::new(Mapping::open(path).expect("map model")),
&gguf,
dispatch,
threads,
)
.expect("load model");
let config = ServiceConfig {
service: args[2].clone().into(),
openvino_root: args[1].clone().into(),
device: args[3].clone(),
model: path.to_path_buf(),
cache_dir: None,
};
let mut accel = NpuPrefill::start(&config, batch).expect("start the NPU service");
println!("# paired prefill A/B (warm)");
println!(
"model: {} ({} bytes, sha256 {})",
path.file_name().and_then(|n| n.to_str()).unwrap_or("?"),
size,
std::env::var("LELEKA_MODEL_SHA256").unwrap_or_else(|_| "not recorded".into())
);
println!(
"cpu: {threads} threads, kernels {isa}; npu service device: {}, batch {batch}; context capacity = prompt + 1",
accel.device_name()
);
println!(
"date: {} (hardware/driver/power state are not controlled; see docs/npu-service.md)",
std::env::var("LELEKA_AB_DATE").unwrap_or_else(|_| "unrecorded".into())
);
for n in sizes {
let prompt = synth(n);
let run_cpu = |model: &Model| {
let mut state = State::new(&model.config, n + 1);
let t = Instant::now();
let r = model
.prefill_reuse(&mut state, &prompt)
.expect("cpu prefill");
(t.elapsed().as_secs_f64(), r.next)
};
let run_npu = |model: &Model, accel: &mut NpuPrefill| {
let mut state = State::new(&model.config, n + 1);
let t = Instant::now();
let r = model
.prefill_reuse_accelerated(&mut state, &prompt, accel, 1, &mut |_, _| true)
.expect("npu prefill")
.expect("not cancelled");
(t.elapsed().as_secs_f64(), r.next)
};
// warm-up: page the weights in, compile the graphs
let warm_n = n.min(64);
{
let mut state = State::new(&model.config, warm_n + 1);
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 _ = model
.prefill_reuse_accelerated(&mut state, p, &mut accel, 1, &mut |_, _| true)
.expect("warm npu");
}
println!("\n## {n} prompt tokens, {pairs} pairs");
println!(
"{:>4} {:>6} {:>10} {:>10} {:>9} next tokens",
"pair", "first", "cpu s", "npu s", "speed-up"
);
let (mut cpu_s, mut npu_s, mut ratios) = (Vec::new(), Vec::new(), Vec::new());
for i in 0..pairs {
let npu_first = i % 2 == 1;
let ((c, cn), (g, gn)) = if npu_first {
let g = run_npu(&model, &mut accel);
let c = run_cpu(&model);
(c, g)
} else {
let c = run_cpu(&model);
let g = run_npu(&model, &mut accel);
(c, g)
};
println!(
"{:>4} {:>6} {:>10.2} {:>10.2} {:>8.2}x cpu {cn} npu {gn}",
i + 1,
if npu_first { "npu" } else { "cpu" },
c,
g,
c / g
);
cpu_s.push(c);
npu_s.push(g);
ratios.push(c / g);
}
for (name, x) in [("cpu", &cpu_s), ("npu", &npu_s)] {
let (m, sd) = mean_sd(x);
let mut sorted = x.clone();
sorted.sort_by(|a, b| a.total_cmp(b));
println!(
"{name}: mean {m:.2} s (sd {sd:.2}), median {:.2}, min {:.2}, max {:.2} => {:.1} tok/s at the median",
median(x),
sorted[0],
sorted[sorted.len() - 1],
n as f64 / median(x)
);
}
let (m, sd) = mean_sd(&ratios);
let half = if pairs > 1 {
t95(pairs - 1) * sd / (pairs as f64).sqrt()
} else {
f64::NAN
};
println!(
"paired speed-up cpu/npu: mean {m:.2}x, 95% CI [{:.2}, {:.2}], median {:.2}x ({pairs} pairs)",
m - half,
m + half,
median(&ratios)
);
}
}