Files
leleka/crates/gptoss-npu/examples/numerics_probe.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

125 lines
4.7 KiB
Rust

//! How accurate is a device's half-precision matmul on real activations? Computes the layer-0 normalised
//! hidden states of a few tokens, multiplies them by the layer-0 value projection (Q8_0) in f64 as the reference
//! and through the NPU service on the given devices, and prints the relative rms errors.
//!
//! Run: `cargo run --release -p leleka-gptoss-npu --example numerics_probe -- <model.gguf> <openvino root> <service exe> <device,device...>`
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 std::fs::File;
use std::io::BufReader;
use std::path::{Path, PathBuf};
fn f16_to_f64(bits: u16) -> f64 {
let sign = if bits & 0x8000 != 0 { -1.0 } else { 1.0 };
let exp = i32::from((bits >> 10) & 31);
let man = f64::from(bits & 1023);
sign * if exp == 0 {
man * 2f64.powi(-24)
} else {
(1.0 + man / 1024.0) * 2f64.powi(exp - 15)
}
}
fn main() {
let a: Vec<String> = std::env::args().skip(1).collect();
if a.len() < 4 {
eprintln!("usage: numerics_probe <model.gguf> <openvino root> <service exe> <device,...>");
std::process::exit(2);
}
let path = Path::new(&a[0]);
let size = std::fs::metadata(path).unwrap().len();
let gguf = Gguf::read(BufReader::new(File::open(path).unwrap()), size).unwrap();
let model = Model::load(
std::sync::Arc::new(Mapping::open(path).unwrap()),
&gguf,
Dispatch::from_env().unwrap(),
4,
)
.unwrap();
let c = &model.config;
let e = c.n_embd;
let tokens: Vec<u32> = (0..32).map(|i| 1000 + i * 1237).collect();
let view = model.layer_view(0);
let mut h = vec![0.0f32; tokens.len() * e];
for (t, row) in h.chunks_exact_mut(e).enumerate() {
let mut x = vec![0.0f32; e];
model.embed(tokens[t], &mut x).unwrap();
ops::rms_norm(&x, view.attn_norm, c.rms_eps, row);
}
let max = h.iter().fold(0.0f32, |m, v| m.max(v.abs()));
let rms =
(h.iter().map(|v| f64::from(*v) * f64::from(*v)).sum::<f64>() / h.len() as f64).sqrt();
println!("layer-0 normalised activations: max |h| {max:.2}, rms {rms:.3}");
// f16 inputs, as the device receives them
let dispatch = Dispatch::from_env().unwrap();
let mut halves = vec![0u16; h.len()];
dispatch.f32_to_f16(&h, &mut halves).unwrap();
// reference: the value projection in f64 (rows of Q8_0 blocks)
let w = &view.wv;
let (n, k) = (w.rows, w.cols);
let row_bytes = k / 32 * 34;
let mut reference = vec![0f64; tokens.len() * n];
for r in 0..n {
let mut row = vec![0f64; k];
for (b, block) in w.data[r * row_bytes..(r + 1) * row_bytes]
.as_chunks::<34>()
.0
.iter()
.enumerate()
{
let scale = f16_to_f64(u16::from_le_bytes([block[0], block[1]]));
for (j, q) in block[2..].iter().enumerate() {
row[b * 32 + j] = scale * f64::from(*q as i8);
}
}
for t in 0..tokens.len() {
reference[t * n + r] = (0..k).map(|i| f16_to_f64(halves[t * k + i]) * row[i]).sum();
}
}
let den: f64 = reference.iter().map(|v| v * v).sum();
for device in a[3].split(',') {
let config = ServiceConfig {
service: PathBuf::from(&a[2]),
openvino_root: PathBuf::from(&a[1]),
device: device.to_owned(),
model: path.to_path_buf(),
cache_dir: None,
};
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 shifts = client
.product("blk.0.attn_v.weight", None, tokens.len(), n, input, out)
.unwrap();
let y = client.get(out, tokens.len() * n).unwrap();
let mut num = 0f64;
let mut per_token = Vec::new();
for t in 0..tokens.len() {
let (mut tn, mut td) = (0f64, 0f64);
for r in 0..n {
let shift = shifts.as_ref().map_or(0, |s| i32::from(s[r]));
let d = f16_to_f64(y[t * n + r]) / 2f64.powi(shift) - reference[t * n + r];
tn += d * d;
td += reference[t * n + r] * reference[t * n + r];
}
num += tn;
per_token.push((tn / td).sqrt());
}
per_token.sort_by(|x, y| x.total_cmp(y));
println!(
"{device} ({}): relative rms error {:.2e}; per token median {:.2e}, worst {:.2e}",
client.device_name(),
(num / den).sqrt(),
per_token[per_token.len() / 2],
per_token[per_token.len() - 1]
);
}
}