- 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>
183 lines
6.2 KiB
Rust
183 lines
6.2 KiB
Rust
//! Prefill the same prompt on the CPU and with the NPU service and compare what they leave behind (last-token
|
|
//! distribution, KV caches, greedy continuation) and the times.
|
|
//!
|
|
//! Run: `cargo run --release -p leleka-gptoss-npu --example npu_prefill -- <model.gguf> <openvino root> <service exe> <device> <ids|synth:N> [batch] [decode]`
|
|
//! Set `LELEKA_SKIP_CPU=1` to time the NPU path only.
|
|
|
|
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, PathBuf};
|
|
use std::time::Instant;
|
|
|
|
fn log_softmax(logits: &[f32]) -> Vec<f64> {
|
|
let max = logits.iter().copied().fold(f32::NEG_INFINITY, f32::max);
|
|
let z: f64 = logits.iter().map(|l| f64::from(l - max).exp()).sum();
|
|
logits.iter().map(|l| f64::from(l - max) - z.ln()).collect()
|
|
}
|
|
|
|
fn main() {
|
|
let a: Vec<String> = std::env::args().skip(1).collect();
|
|
if a.len() < 5 {
|
|
eprintln!(
|
|
"usage: npu_prefill <model.gguf> <openvino root> <service exe> <device> <ids|synth:N> [batch] [decode]"
|
|
);
|
|
std::process::exit(2);
|
|
}
|
|
let prompt: Vec<u32> = if let Some(n) = a[4].strip_prefix("synth:") {
|
|
let mut s = 0x2545_F491_4F6C_DD1Du64;
|
|
(0..n.parse::<usize>().expect("synth:N"))
|
|
.map(|_| {
|
|
s ^= s << 13;
|
|
s ^= s >> 7;
|
|
s ^= s << 17;
|
|
1000 + (s % 60_000) as u32
|
|
})
|
|
.collect()
|
|
} else {
|
|
a[4].split(',')
|
|
.map(|s| s.trim().parse().expect("token id"))
|
|
.collect()
|
|
};
|
|
let batch: usize = a
|
|
.get(5)
|
|
.and_then(|s| s.parse().ok())
|
|
.unwrap_or(leleka_gptoss_npu::DEFAULT_BATCH);
|
|
let decode: usize = a.get(6).and_then(|s| s.parse().ok()).unwrap_or(8);
|
|
let path = Path::new(&a[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 model = Model::load(
|
|
std::sync::Arc::new(Mapping::open(path).expect("map model")),
|
|
&gguf,
|
|
Dispatch::from_env().expect("kernel level"),
|
|
std::thread::available_parallelism().map_or(1, |n| n.get()),
|
|
)
|
|
.expect("load model");
|
|
let capacity = prompt.len() + decode + 1;
|
|
let config = ServiceConfig {
|
|
service: PathBuf::from(&a[2]),
|
|
openvino_root: PathBuf::from(&a[1]),
|
|
device: a[3].clone(),
|
|
model: path.to_path_buf(),
|
|
cache_dir: None,
|
|
};
|
|
let mut accel = NpuPrefill::start(&config, batch).expect("start the NPU service");
|
|
if let Ok(shadow_device) = std::env::var("LELEKA_SHADOW_DEVICE") {
|
|
let shadow = ServiceConfig {
|
|
device: shadow_device,
|
|
..config.clone()
|
|
};
|
|
accel = accel
|
|
.with_shadow(&shadow)
|
|
.expect("start the shadow service");
|
|
}
|
|
println!("service device: {}, batch {batch}", accel.device_name());
|
|
|
|
let mut npu_state = State::new(&model.config, capacity);
|
|
let t = Instant::now();
|
|
let npu = model
|
|
.prefill_reuse_accelerated(&mut npu_state, &prompt, &mut accel, 1, &mut |_, _| true)
|
|
.expect("npu prefill")
|
|
.expect("not cancelled");
|
|
let s = t.elapsed().as_secs_f64();
|
|
println!(
|
|
"npu prefill: {} tokens in {s:.2} s ({:.1} tok/s), next {}\n {}",
|
|
prompt.len(),
|
|
prompt.len() as f64 / s,
|
|
npu.next,
|
|
accel.timings().report()
|
|
);
|
|
if std::env::var_os("LELEKA_SKIP_CPU").is_some() {
|
|
return;
|
|
}
|
|
|
|
let mut cpu = State::new(&model.config, capacity);
|
|
let t = Instant::now();
|
|
let cpu_reuse = model.prefill_reuse(&mut cpu, &prompt).expect("cpu prefill");
|
|
let s = t.elapsed().as_secs_f64();
|
|
println!(
|
|
"cpu prefill: {} tokens in {s:.2} s ({:.1} tok/s), next {}",
|
|
prompt.len(),
|
|
prompt.len() as f64 / s,
|
|
cpu_reuse.next
|
|
);
|
|
let (lc, ln) = (log_softmax(&cpu.logits), log_softmax(&npu_state.logits));
|
|
let kl: f64 = lc.iter().zip(&ln).map(|(p, q)| p.exp() * (p - q)).sum();
|
|
let gap = cpu
|
|
.logits
|
|
.iter()
|
|
.zip(&npu_state.logits)
|
|
.map(|(x, y)| (x - y).abs())
|
|
.fold(0.0f32, f32::max);
|
|
println!(
|
|
"last token: top-1 {} (cpu {} npu {}), KL(cpu||npu) {kl:.6}, max logit gap {gap:.4}",
|
|
if cpu_reuse.next == npu.next {
|
|
"agree"
|
|
} else {
|
|
"DIFFER"
|
|
},
|
|
cpu_reuse.next,
|
|
npu.next
|
|
);
|
|
layer_report(&model, &cpu, &npu_state, prompt.len());
|
|
let (mut x, mut y) = (cpu_reuse.next, npu.next);
|
|
let (mut sx, mut sy) = (vec![x], vec![y]);
|
|
for i in 0..decode {
|
|
x = model
|
|
.forward(&mut cpu, x, prompt.len() + i)
|
|
.expect("cpu decode");
|
|
y = model
|
|
.forward(&mut npu_state, y, prompt.len() + i)
|
|
.expect("npu-cache decode");
|
|
sx.push(x);
|
|
sy.push(y);
|
|
}
|
|
println!("continuation from cpu cache: {sx:?}\ncontinuation from npu cache: {sy:?}");
|
|
}
|
|
|
|
fn half(bits: u16) -> f32 {
|
|
let sign = if bits & 0x8000 != 0 { -1.0f32 } else { 1.0 };
|
|
let exp = i32::from((bits >> 10) & 0x1F);
|
|
let man = f32::from(bits & 0x3FF);
|
|
match exp {
|
|
0 => sign * man * 2f32.powi(-24),
|
|
31 => f32::NAN,
|
|
_ => sign * (1.0 + man / 1024.0) * 2f32.powi(exp - 15),
|
|
}
|
|
}
|
|
|
|
/// Relative rms difference of two half-precision arrays.
|
|
fn rel_rms(a: &[u16], b: &[u16]) -> f64 {
|
|
let (mut num, mut den) = (0f64, 0f64);
|
|
for (x, y) in a.iter().zip(b) {
|
|
let (fx, fy) = (f64::from(half(*x)), f64::from(half(*y)));
|
|
num += (fx - fy) * (fx - fy);
|
|
den += fx * fx;
|
|
}
|
|
(num / den).sqrt()
|
|
}
|
|
|
|
/// Per-layer cache differences between two states, to find where two prefills first part.
|
|
#[allow(dead_code)]
|
|
fn layer_report(model: &Model, a: &State, b: &State, tokens: usize) {
|
|
for l in 0..model.config.blocks {
|
|
let (ak, av) = a.kv_rows(l, 0, tokens);
|
|
let (bk, bv) = b.kv_rows(l, 0, tokens);
|
|
println!(
|
|
"layer {l:>2}: keys {:.2e} values {:.2e}",
|
|
rel_rms(&ak, &bk),
|
|
rel_rms(&av, &bv)
|
|
);
|
|
}
|
|
}
|