feat: add the NPU-assisted prefill client, the NPU worker and the scale-shift fix (STRA-207)

- gptoss-npu: a prefill accelerator that sends the matrix products to the NPU service and keeps norms, RoPE,
  attention, router, activation and combine on the CPU; debugging shadow device; examples for comparison, the
  quality dump, a numerics probe and a paired A/B
- npu-worker: separate executable with the CPU worker's protocol, CPU-only fallback, --openvino-root/--npu-*
- the NPU flushes half-precision subnormals to zero, which erased every Q8_0 block with scale < 2^-14
  (error 11% on attn_output); the service now boosts such rows' scales by a power of two and reports the
  per-column shifts the client divides out (relative rms error back to 3e-4 on all shapes)
- Smoke-GptOssStack.ps1 takes -Worker leleka-npu-worker -OpenVinoRoot; passes through the control plane

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-15 11:37:22 +02:00
co-authored by Claude Sonnet 5.5
parent 204ec34fbd
commit b5d9a569b2
20 changed files with 2258 additions and 22 deletions
Generated
+19
View File
@@ -1300,6 +1300,17 @@ dependencies = [
"leleka-igpu",
]
[[package]]
name = "leleka-gptoss-npu"
version = "0.1.0"
dependencies = [
"leleka-cpu-kernels",
"leleka-cpu-sys",
"leleka-gguf",
"leleka-gptoss",
"leleka-shm",
]
[[package]]
name = "leleka-harmony"
version = "0.1.0"
@@ -1338,6 +1349,14 @@ dependencies = [
"leleka-shm",
]
[[package]]
name = "leleka-npu-worker"
version = "0.1.0"
dependencies = [
"leleka-cpu-worker",
"leleka-gptoss-npu",
]
[[package]]
name = "leleka-openvino"
version = "0.1.0"
+2 -2
View File
@@ -1,7 +1,7 @@
[workspace]
resolver = "3"
members = ["crates/backend-api", "crates/cpu-kernels", "crates/cpu-sys", "crates/cpu-worker", "crates/gguf", "crates/gptoss", "crates/gptoss-igpu", "crates/harmony", "crates/igpu", "crates/igpu-worker", "crates/shm", "crates/openvino", "crates/npu-service", "crates/tokenizer", "control-plane", "desktop-core"]
default-members = ["crates/backend-api", "crates/cpu-kernels", "crates/cpu-sys", "crates/cpu-worker", "crates/gguf", "crates/gptoss", "crates/gptoss-igpu", "crates/harmony", "crates/igpu", "crates/igpu-worker", "crates/shm", "crates/openvino", "crates/npu-service", "crates/tokenizer", "control-plane", "desktop-core"]
members = ["crates/backend-api", "crates/cpu-kernels", "crates/cpu-sys", "crates/cpu-worker", "crates/gguf", "crates/gptoss", "crates/gptoss-igpu", "crates/harmony", "crates/igpu", "crates/igpu-worker", "crates/shm", "crates/openvino", "crates/npu-service", "crates/gptoss-npu", "crates/npu-worker", "crates/tokenizer", "control-plane", "desktop-core"]
default-members = ["crates/backend-api", "crates/cpu-kernels", "crates/cpu-sys", "crates/cpu-worker", "crates/gguf", "crates/gptoss", "crates/gptoss-igpu", "crates/harmony", "crates/igpu", "crates/igpu-worker", "crates/shm", "crates/openvino", "crates/npu-service", "crates/gptoss-npu", "crates/npu-worker", "crates/tokenizer", "control-plane", "desktop-core"]
[workspace.package]
edition = "2024"
+3 -2
View File
@@ -15,7 +15,8 @@ param(
[int] $Port = 8081,
[int] $Context = 8192,
[int] $Threads = 10,
[ValidateSet('leleka-cpu-worker', 'leleka-igpu-worker')] [string] $Worker = 'leleka-cpu-worker',
[ValidateSet('leleka-cpu-worker', 'leleka-igpu-worker', 'leleka-npu-worker')] [string] $Worker = 'leleka-cpu-worker',
[string] $OpenVinoRoot = '',
[int] $GpuMinTokens = 256
)
$ErrorActionPreference = 'Stop'
@@ -27,7 +28,7 @@ $config = @{
bind = "127.0.0.1:$Port"; model = 'gpt-oss-20b'
engine = @{
executable = (Join-Path $bin "$Worker.exe")
args = @('--model', $Model, '--ctx', "$Context", '--threads', "$Threads") + $(if ($Worker -eq 'leleka-igpu-worker') { @('--gpu-min-tokens', "$GpuMinTokens") } else { @() })
args = @('--model', $Model, '--ctx', "$Context", '--threads', "$Threads") + $(if ($Worker -eq 'leleka-igpu-worker') { @('--gpu-min-tokens', "$GpuMinTokens") } elseif ($Worker -eq 'leleka-npu-worker') { @('--npu-min-tokens', "$GpuMinTokens", '--openvino-root', $OpenVinoRoot) } else { @() })
gptoss_gguf = $Model; startup_timeout_s = 300; generation_timeout_s = 600
}
} | ConvertTo-Json -Depth 5
+19
View File
@@ -0,0 +1,19 @@
[package]
name = "leleka-gptoss-npu"
version = "0.1.0"
description = "NPU-assisted prefill for the Leleka gpt-oss decoder: the matrix products run in the NPU service process, everything else on the CPU, and the KV cache goes to the CPU decoder (experimental)"
edition.workspace = true
license.workspace = true
rust-version.workspace = true
[dependencies]
leleka-cpu-kernels = { path = "../cpu-kernels" }
leleka-gptoss = { path = "../gptoss" }
leleka-shm = { path = "../shm" }
[dev-dependencies]
leleka-cpu-sys = { path = "../cpu-sys" }
leleka-gguf = { path = "../gguf" }
[lints]
workspace = true
@@ -0,0 +1,204 @@
//! 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(),
};
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)
);
}
}
@@ -0,0 +1,89 @@
//! Teacher-forced log-probabilities with the prompt prefilled through the NPU service: the same output format
//! as `dump_logprobs` of the CPU decoder, so `compare_logprobs` can compare it with llama.cpp's reference.
//! Every position's hidden state comes from the NPU prefill; the output projection runs on the CPU.
//!
//! Run: `cargo run --release -p leleka-gptoss-npu --example dump_logprobs_npu -- <model.gguf> <openvino root> <service exe> <device> <ids.txt> <out.jsonl> [top_n] [batch]`
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, BufWriter, Write};
use std::path::Path;
fn main() {
let args: Vec<String> = std::env::args().skip(1).collect();
if args.len() < 6 {
eprintln!(
"usage: dump_logprobs_npu <model.gguf> <openvino root> <service exe> <device> <ids.txt> <out.jsonl> [top_n] [batch]"
);
std::process::exit(2);
}
let ids: Vec<u32> = std::fs::read_to_string(&args[4])
.expect("ids file")
.trim()
.split(',')
.map(|s| s.trim().parse().expect("token id"))
.collect();
let top_n: usize = args.get(6).and_then(|s| s.parse().ok()).unwrap_or(20);
let batch: usize = args
.get(7)
.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 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 e = model.config.n_embd;
let mut state = State::new(&model.config, ids.len() + 1);
let config = ServiceConfig {
service: args[2].clone().into(),
openvino_root: args[1].clone().into(),
device: args[3].clone(),
model: path.to_path_buf(),
};
let mut accel = NpuPrefill::start(&config, batch).expect("start the NPU service");
let hidden = accel
.prefill_all_hidden(&model, &mut state, &ids, 0)
.expect("gpu prefill");
eprintln!("{}", accel.timings().report());
let mut out = BufWriter::new(File::create(&args[5]).expect("output file"));
for pos in 0..ids.len() {
model
.next_from_hidden(&mut state, &hidden[pos * e..(pos + 1) * e])
.expect("output projection");
let logits = &state.logits;
let max = logits.iter().copied().fold(f32::NEG_INFINITY, f32::max);
let z: f64 = logits.iter().map(|l| f64::from(l - max).exp()).sum();
let mut order: Vec<usize> = (0..logits.len()).collect();
order.sort_by(|a, b| logits[*b].total_cmp(&logits[*a]).then(a.cmp(b)));
let top: Vec<String> = order
.iter()
.take(top_n)
.map(|i| format!("[{},{:.6}]", i, f64::from(logits[*i] - max) - z.ln()))
.collect();
let next = ids
.get(pos + 1)
.map_or("null".to_owned(), |n| n.to_string());
writeln!(
out,
"{{\"pos\":{pos},\"next\":{next},\"top\":[{}]}}",
top.join(",")
)
.expect("write");
}
eprintln!("wrote {} positions", ids.len());
}
+181
View File
@@ -0,0 +1,181 @@
//! 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(),
};
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)
);
}
}
@@ -0,0 +1,123 @@
//! 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(),
};
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]
);
}
}
+254
View File
@@ -0,0 +1,254 @@
//! The client side of the NPU service protocol: starts the service process, owns the shared region, and runs
//! one matrix product at a time (`MM`). It loads nothing from OpenVINO; it only talks to the process that does.
use leleka_shm::Shared;
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio};
/// Where the service and its OpenVINO files are.
#[derive(Clone, Debug)]
pub struct ServiceConfig {
/// The `leleka-npu-service` executable.
pub service: PathBuf,
/// The unpacked OpenVINO archive (the folder that holds `runtime`).
pub openvino_root: PathBuf,
/// `NPU` normally; `CPU` or `GPU` to test without one.
pub device: String,
pub model: PathBuf,
}
/// A byte range of the shared region.
#[derive(Clone, Copy, Debug)]
pub struct Region {
pub offset: usize,
pub bytes: usize,
}
/// The regions the prefill uses, each big enough for `max_rows` rows of the widest matrix (4096 columns).
#[derive(Clone, Copy, Debug)]
pub struct Layout {
pub input_a: Region,
pub input_b: Region,
pub out: [Region; 4],
pub total: usize,
}
impl Layout {
pub fn new(max_rows: usize) -> Self {
// room after the widest result for the per-column scale shifts (one byte per column)
let bytes = max_rows * 4096 * 2 + 4096;
let at = |i: usize| Region {
offset: i * bytes,
bytes,
};
Self {
input_a: at(0),
input_b: at(1),
out: [at(2), at(3), at(4), at(5)],
total: 6 * bytes,
}
}
}
pub struct Client {
child: Child,
stdin: ChildStdin,
stdout: BufReader<ChildStdout>,
shm: Shared,
path: PathBuf,
device_name: String,
pub layout: Layout,
}
impl Client {
pub fn start(config: &ServiceConfig, max_rows: usize) -> Result<Self, String> {
let layout = Layout::new(max_rows);
let path =
std::env::temp_dir().join(format!("leleka-npu-{}-{}.shm", std::process::id(), nanos()));
let shm = Shared::create(&path, layout.total)
.map_err(|e| format!("cannot create the shared region: {e}"))?;
let bin = config
.openvino_root
.join("runtime")
.join("bin")
.join("intel64")
.join("Release");
let tbb = config
.openvino_root
.join("runtime")
.join("3rdparty")
.join("tbb")
.join("bin");
let search = std::env::join_paths([bin.clone(), tbb].into_iter().chain(
std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default()),
))
.map_err(|e| e.to_string())?;
let spawned = Command::new(&config.service)
.env("PATH", search)
.arg("--openvino")
.arg(bin.join(if cfg!(windows) {
"openvino_c.dll"
} else {
"libopenvino_c.so"
}))
.arg("--model")
.arg(&config.model)
.arg("--shm")
.arg(&path)
.args(["--device", &config.device])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.spawn();
let mut child = match spawned {
Ok(c) => c,
Err(e) => {
let _ = std::fs::remove_file(&path);
return Err(format!("cannot start {}: {e}", config.service.display()));
}
};
let stdin = child.stdin.take().ok_or("no stdin")?;
let mut stdout = BufReader::new(child.stdout.take().ok_or("no stdout")?);
let mut line = String::new();
let ready = stdout.read_line(&mut line);
match (ready, line.strip_prefix("READY ")) {
(Ok(n), Some(name)) if n > 0 => {
let device_name = name.trim().to_owned();
Ok(Self {
child,
stdin,
stdout,
shm,
path,
device_name,
layout,
})
}
_ => {
let _ = child.kill();
let _ = child.wait();
let _ = std::fs::remove_file(&path);
Err(format!(
"the NPU service did not become ready (said {line:?})"
))
}
}
}
pub fn device_name(&self) -> &str {
&self.device_name
}
pub fn region_path(&self) -> &Path {
&self.path
}
fn ask(&mut self, line: &str) -> Result<String, String> {
writeln!(self.stdin, "{line}")
.and_then(|()| self.stdin.flush())
.map_err(|e| format!("the NPU service is gone: {e}"))?;
let mut answer = String::new();
match self.stdout.read_line(&mut answer) {
Ok(0) | Err(_) => Err("the NPU service closed its output".into()),
Ok(_) => Ok(answer.trim_end().to_owned()),
}
}
/// Write half floats (as bits) into `region` at element 0.
pub fn put(&self, region: Region, halves: &[u16]) -> Result<(), String> {
let bytes: Vec<u8> = halves.iter().flat_map(|h| h.to_le_bytes()).collect();
self.shm
.write(region.offset, &bytes)
.map_err(|e| e.to_string())
}
/// Read `count` half floats (as bits) from `region`.
pub fn get(&self, region: Region, count: usize) -> Result<Vec<u16>, String> {
let mut bytes = vec![0u8; count * 2];
self.shm
.read(region.offset, &mut bytes)
.map_err(|e| e.to_string())?;
Ok(bytes
.as_chunks::<2>()
.0
.iter()
.map(|b| u16::from_le_bytes(*b))
.collect())
}
/// `out = input . W^T` for the tensor `name` (one `expert` of a stacked tensor; `cols` is the width of the
/// result). Returns the per-column scale shifts when the service had to boost the weight's scales
/// (divide column `c` of the result by `2^shifts[c]`), `None` otherwise.
pub fn product(
&mut self,
name: &str,
expert: Option<usize>,
rows: usize,
cols: usize,
input: Region,
out: Region,
) -> Result<Option<Vec<u8>>, String> {
let e = expert.map_or("-".to_owned(), |e| e.to_string());
let answer = self.ask(&format!(
"MM {name} {e} {rows} {} {}",
input.offset, out.offset
))?;
let mut fields = answer.split_whitespace();
if fields.next() != Some("OK") {
return Err(format!("{name}: {answer}"));
}
if fields.nth(2) != Some("1") {
return Ok(None);
}
let mut shifts = vec![0u8; cols];
self.shm
.read(out.offset + rows * cols * 2, &mut shifts)
.map_err(|e| e.to_string())?;
Ok(Some(shifts))
}
}
impl Drop for Client {
fn drop(&mut self) {
let _ = writeln!(self.stdin, "QUIT");
let _ = self.stdin.flush();
let _ = self.child.wait();
let _ = std::fs::remove_file(&self.path);
}
}
fn nanos() -> u128 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_nanos())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn regions_do_not_overlap_and_fit_the_widest_matrix() {
let l = Layout::new(1024);
let all = [l.input_a, l.input_b, l.out[0], l.out[1], l.out[2], l.out[3]];
for (i, a) in all.iter().enumerate() {
assert_eq!(a.bytes, 1024 * 4096 * 2 + 4096);
for b in &all[i + 1..] {
assert!(a.offset + a.bytes <= b.offset);
}
}
assert_eq!(l.total, 6 * (1024 * 4096 * 2 + 4096));
}
#[test]
fn a_missing_service_is_an_error() {
let config = ServiceConfig {
service: PathBuf::from("definitely-not-a-service.exe"),
openvino_root: PathBuf::from("nowhere"),
device: "CPU".into(),
model: PathBuf::from("none.gguf"),
};
assert!(Client::start(&config, 32).is_err());
}
}
+45
View File
@@ -0,0 +1,45 @@
//! Half-precision bits to f32.
use std::sync::OnceLock;
fn table() -> &'static [f32] {
static TABLE: OnceLock<Vec<f32>> = OnceLock::new();
TABLE.get_or_init(|| (0..=u16::MAX).map(to_f32_slow).collect())
}
fn to_f32_slow(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 => {
if man == 0.0 {
sign * f32::INFINITY
} else {
f32::NAN
}
}
_ => sign * (1.0 + man / 1024.0) * 2f32.powi(exp - 15),
}
}
/// Convert `src` half bits into `dst` floats.
pub fn to_f32(src: &[u16], dst: &mut [f32]) {
let t = table();
for (d, s) in dst.iter_mut().zip(src) {
*d = t[usize::from(*s)];
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn known_values() {
let mut out = [0.0f32; 5];
to_f32(&[0x3C00, 0xC000, 0x7BFF, 0x0001, 0x0000], &mut out);
assert_eq!(out, [1.0, -2.0, 65504.0, 2f32.powi(-24), 0.0]);
}
}
+637
View File
@@ -0,0 +1,637 @@
//! NPU-assisted prefill of the gpt-oss decoder (experimental).
//!
//! The prompt goes through all layers layer after layer, as in the GPU prefill, but here the matrix products
//! (attention projections and the experts) are sent to the NPU service process (`leleka-npu-service`, the NPU
//! runtime) through a shared region, and everything else runs on the CPU in this process: normalisation, RoPE,
//! attention over a half-precision cache, the router, the expert activation, the weighted combine. The layer's
//! keys and values land in the CPU decoder's cache, which then decodes as usual.
//!
//! Numerics differ from the CPU decoder on purpose: the NPU multiplies half-precision activations (no 8-bit
//! activation quantisation) by the exactly expanded weights and accumulates in float, so results agree to
//! half-precision accuracy rather than bit for bit. This path is *experimental* until its quality gate passes.
pub mod client;
mod half;
mod par;
use client::{Client, Layout, Region, ServiceConfig};
use leleka_cpu_kernels::Dispatch;
use leleka_gptoss::{
LayerView, Model, ModelError, PrefillAccelerator, SWIGLU_ALPHA, SWIGLU_LIMIT, State, ops,
};
use std::time::{Duration, Instant};
/// Rows per batch of prompt tokens (the largest bucket of the service).
pub const DEFAULT_BATCH: usize = 512;
const MAX_ROWS: usize = 1024;
/// Where the time of the last prefill went.
#[derive(Clone, Debug, Default)]
pub struct Timings {
pub tokens: usize,
/// Waiting for the service (includes its weight expansion and the copies through the shared region).
pub npu: Duration,
pub attention: Duration,
/// The rest of the CPU work (norms, RoPE, router, activation, conversions).
pub other: Duration,
pub total: Duration,
}
impl Timings {
pub fn report(&self) -> String {
let s = |d: Duration| d.as_secs_f64();
format!(
"{} tokens in {:.2} s: npu {:.2} | cpu attention {:.2} | cpu other {:.2}",
self.tokens,
s(self.total),
s(self.npu),
s(self.attention),
s(self.other)
)
}
}
pub struct NpuPrefill {
client: Client,
batch: usize,
timings: Timings,
/// A second service on another device whose results every product is compared with (debugging).
shadow: Option<Client>,
/// Round the activations through the CPU decoder's Q8_0 quantisation before the device sees them.
quantize_activations: bool,
/// Scale shifts reported for the last product written to a region (by offset), applied when it is read.
shifts: std::collections::HashMap<usize, Vec<u8>>,
}
fn fail(e: impl std::fmt::Display) -> ModelError {
ModelError::Invalid(format!("NPU prefill: {e}"))
}
impl NpuPrefill {
/// Start the service process and wait until its device is ready.
pub fn start(config: &ServiceConfig, batch: usize) -> Result<Self, String> {
let batch = batch.clamp(1, MAX_ROWS);
let client = Client::start(config, MAX_ROWS)?;
Ok(Self {
client,
batch,
timings: Timings::default(),
shadow: None,
quantize_activations: false,
shifts: std::collections::HashMap::new(),
})
}
/// Compare every product with the same product on a second service (another device) and report the
/// ones that differ (debugging).
pub fn with_shadow(mut self, config: &ServiceConfig) -> Result<Self, String> {
self.shadow = Some(Client::start(config, MAX_ROWS)?);
Ok(self)
}
/// Round the activations through the CPU decoder's Q8_0 quantisation before the device sees them (the
/// default feeds it the exact half-precision values: closer to the mathematical result, a little further
/// from what the CPU decoder and llama.cpp compute).
pub fn q8_activations(mut self) -> Self {
self.quantize_activations = true;
self
}
pub fn device_name(&self) -> &str {
self.client.device_name()
}
pub fn timings(&self) -> &Timings {
&self.timings
}
/// As the [`PrefillAccelerator`] implementation, but returns the hidden state of every token.
pub fn prefill_all_hidden(
&mut self,
model: &Model,
state: &mut State,
tokens: &[u32],
pos0: usize,
) -> Result<Vec<f32>, ModelError> {
Ok(self
.run(model, state, tokens, pos0, &mut |_| true, true)?
.expect("not cancelled"))
}
/// `rows` half floats from `region` as floats.
fn fetch(&self, region: Region, rows: usize, width: usize) -> Result<Vec<f32>, ModelError> {
let halves = self.client.get(region, rows * width).map_err(fail)?;
let mut out = vec![0.0f32; rows * width];
par::for_chunks(&mut out, width * 16, |i, chunk| {
let start = i * width * 16;
half::to_f32(&halves[start..start + chunk.len()], chunk);
});
if let Some(shifts) = self.shifts.get(&region.offset) {
scale_columns(&mut out, width, shifts);
}
Ok(out)
}
fn put_floats(
&self,
dispatch: &Dispatch,
region: Region,
values: &[f32],
) -> Result<(), ModelError> {
let halves = halves_of(dispatch, values, self.quantize_activations);
self.client.put(region, &halves).map_err(fail)
}
fn product(
&mut self,
name: &str,
expert: Option<usize>,
rows: usize,
(k, n): (usize, usize),
input: Region,
out: Region,
) -> Result<(), ModelError> {
let started = Instant::now();
let shifts = self
.client
.product(name, expert, rows, n, input, out)
.map_err(fail)?;
match shifts {
Some(s) => {
self.shifts.insert(out.offset, s);
}
None => {
self.shifts.remove(&out.offset);
}
}
self.timings.npu += started.elapsed();
if let Some(mut shadow) = self.shadow.take() {
// debugging aid: the same product on a second device, compared
let x = self.client.get(input, rows * k).map_err(fail)?;
let ours = self.fetch(out, rows, n)?;
let sl = shadow.layout;
shadow.put(sl.input_a, &x).map_err(fail)?;
let their_shifts = shadow
.product(name, expert, rows, n, sl.input_a, sl.out[0])
.map_err(fail)?;
let halves = shadow.get(sl.out[0], rows * n).map_err(fail)?;
let mut theirs = vec![0.0f32; rows * n];
half::to_f32(&halves, &mut theirs);
if let Some(s) = their_shifts {
scale_columns(&mut theirs, n, &s);
}
let (mut num, mut den, mut bad) = (0f64, 0f64, 0usize);
for (a, b) in ours.iter().zip(&theirs) {
bad += usize::from(!a.is_finite());
let d = f64::from(*a) - f64::from(*b);
num += d * d;
den += f64::from(*b) * f64::from(*b);
}
let mut inputs = vec![0.0f32; x.len()];
half::to_f32(&x, &mut inputs);
let worst_in = inputs.iter().fold(0.0f32, |m, v| m.max(v.abs()));
let rel = (num / den.max(1e-30)).sqrt();
if rel > 5e-3 || bad > 0 {
eprintln!(
"shadow: {name} expert {expert:?} rows {rows}: relative rms {rel:.2e}, {bad} non-finite, max |input| {worst_in:.1}"
);
}
self.shadow = Some(shadow);
}
Ok(())
}
fn run(
&mut self,
model: &Model,
state: &mut State,
tokens: &[u32],
pos0: usize,
progress: &mut dyn FnMut(f64) -> bool,
all_hidden: bool,
) -> Result<Option<Vec<f32>>, ModelError> {
let started = Instant::now();
self.timings = Timings {
tokens: tokens.len(),
..Timings::default()
};
let c = &model.config;
let (e, hd, qw, kw, ff) = (c.n_embd, c.head_dim, c.q_width(), c.kv_width(), c.n_ff);
let n = tokens.len();
if n == 0 || pos0 + n > state.capacity() {
return Err(ModelError::ContextFull {
position: pos0 + n,
capacity: state.capacity(),
});
}
for width in [e, qw, ff] {
if width % 32 != 0 || width > 4096 {
return Err(ModelError::Unsupported(format!(
"the NPU prefill handles layer widths up to 4096 in blocks of 32, not {width}"
)));
}
}
let layout: Layout = self.client.layout;
let dispatch = *model.dispatch();
let group = c.n_head / c.n_head_kv;
let scale = 1.0 / (hd as f32).sqrt();
let half_hd = hd / 2;
let mut xs = vec![0.0f32; n * e];
for (t, row) in xs.chunks_exact_mut(e).enumerate() {
model.embed(tokens[t], row)?;
}
let mut rotations = vec![(0.0f32, 0.0f32); n * half_hd];
par::for_chunks(&mut rotations, half_hd, |t, r| {
c.yarn.rotation((pos0 + t) as u32, hd, r)
});
for l in 0..c.blocks {
let view = model.layer_view(l);
let name = |part: &str| format!("blk.{l}.{part}.weight");
let window = if c.is_sliding(l) { c.sliding_window } else { 0 };
let positions = pos0 + n;
let mut kc = vec![0u16; positions * kw];
let mut vc = vec![0u16; positions * kw];
if pos0 > 0 {
let (k, v) = state.kv_rows(l, 0, pos0);
kc[..pos0 * kw].copy_from_slice(&k);
vc[..pos0 * kw].copy_from_slice(&v);
}
for b0 in (0..n).step_by(self.batch) {
let m = self.batch.min(n - b0);
let t0 = Instant::now();
// --- attention: norm, projections ---
let mut h = vec![0.0f32; m * e];
par::for_chunks(&mut h, e, |t, row| {
ops::rms_norm(
&xs[(b0 + t) * e..(b0 + t + 1) * e],
view.attn_norm,
c.rms_eps,
row,
)
});
self.put_floats(&dispatch, layout.input_a, &h)?;
self.timings.other += t0.elapsed();
self.product(
&name("attn_q"),
None,
m,
(e, qw),
layout.input_a,
layout.out[0],
)?;
self.product(
&name("attn_k"),
None,
m,
(e, kw),
layout.input_a,
layout.out[1],
)?;
self.product(
&name("attn_v"),
None,
m,
(e, kw),
layout.input_a,
layout.out[2],
)?;
let t1 = Instant::now();
let mut q = self.fetch(layout.out[0], m, qw)?;
let mut k = self.fetch(layout.out[1], m, kw)?;
let mut v = self.fetch(layout.out[2], m, kw)?;
for (data, width, bias) in [
(&mut q, qw, view.bq),
(&mut k, kw, view.bk),
(&mut v, kw, view.bv),
] {
par::for_chunks(data, width, |_, row| {
for (x, b) in row.iter_mut().zip(bias) {
*x += b;
}
});
}
par::for_chunks(&mut q, qw, |t, row| {
let rot = &rotations[(b0 + t) * half_hd..(b0 + t + 1) * half_hd];
for head in row.chunks_exact_mut(hd) {
ops::rope_neox(head, rot);
}
});
par::for_chunks(&mut k, kw, |t, row| {
let rot = &rotations[(b0 + t) * half_hd..(b0 + t + 1) * half_hd];
for head in row.chunks_exact_mut(hd) {
ops::rope_neox(head, rot);
}
});
let at = (pos0 + b0) * kw;
for (cache, values) in [(&mut kc, &k), (&mut vc, &v)] {
par::for_chunks(&mut cache[at..at + m * kw], kw, |t, out| {
dispatch
.f32_to_f16(&values[t * kw..(t + 1) * kw], out)
.expect("equal lengths");
});
}
self.timings.other += t1.elapsed();
// --- attention over the cache ---
let t2 = Instant::now();
let parts = par::dynamic(
m * c.n_head_kv,
|| (Vec::<f32>::new(), Vec::<(usize, usize, Vec<f32>)>::new()),
|item, (scores, done)| {
let (t, kvh) = (item / c.n_head_kv, item % c.n_head_kv);
let pos = pos0 + b0 + t;
let first = if window != 0 {
(pos + 1).saturating_sub(window)
} else {
0
};
let attended = pos + 1 - first;
scores.resize(group * attended, 0.0);
let mut out = vec![0.0f32; group * hd];
let start = first * kw + kvh * hd;
let qs = t * qw + kvh * group * hd;
ops::attend_group_with_sink(
ops::Group {
queries: &q[qs..qs + group * hd],
sinks: &view.sinks[kvh * group..(kvh + 1) * group],
scale,
},
ops::KvRows {
keys: &kc[start..],
values: &vc[start..],
stride: kw,
},
attended,
&dispatch,
scores,
&mut out,
)
.expect("attention kernel");
done.push((t, kvh, out));
},
);
let mut attn = vec![0.0f32; m * qw];
for (_, done) in parts {
for (t, kvh, out) in done {
attn[t * qw + kvh * group * hd..t * qw + (kvh + 1) * group * hd]
.copy_from_slice(&out);
}
}
self.timings.attention += t2.elapsed();
// --- output projection and residual ---
let t3 = Instant::now();
self.put_floats(&dispatch, layout.input_a, &attn)?;
self.timings.other += t3.elapsed();
self.product(
&name("attn_output"),
None,
m,
(qw, e),
layout.input_a,
layout.out[3],
)?;
let t4 = Instant::now();
let proj = self.fetch(layout.out[3], m, e)?;
par::for_chunks(&mut xs[b0 * e..(b0 + m) * e], e, |t, row| {
for ((x, p), b) in row.iter_mut().zip(&proj[t * e..(t + 1) * e]).zip(view.bo) {
*x += p + b;
}
});
// --- router ---
let mut h2 = vec![0.0f32; m * e];
par::for_chunks(&mut h2, e, |t, row| {
ops::rms_norm(
&xs[(b0 + t) * e..(b0 + t + 1) * e],
view.post_norm,
c.rms_eps,
row,
)
});
let mut chosen: Vec<Vec<(usize, f32)>> = vec![Vec::new(); m];
par::for_chunks(&mut chosen, 8, |i, part| {
for (j, slot) in part.iter_mut().enumerate() {
let t = i * 8 + j;
let mut logits = vec![0.0f32; c.n_expert];
dispatch
.rows_dot(
&h2[t * e..(t + 1) * e],
view.router_w,
e,
c.n_expert,
&mut logits,
)
.expect("router kernel");
for (l, b) in logits.iter_mut().zip(view.router_b) {
*l += b;
}
*slot = ops::route_top_k(&logits, c.n_expert_used);
}
});
let h2f = halves_of(&dispatch, &h2, self.quantize_activations);
let mut per_expert: Vec<Vec<(usize, f32)>> = vec![Vec::new(); c.n_expert];
for (t, picks) in chosen.iter().enumerate() {
for (ex, weight) in picks {
per_expert[*ex].push((t, *weight));
}
}
self.timings.other += t4.elapsed();
// --- experts ---
let mut moe = vec![0.0f32; m * e];
for (ex, list) in per_expert.iter().enumerate() {
for rows in list.chunks(MAX_ROWS) {
self.expert(&dispatch, &view, &name, ex, rows, &h2f, e, ff, &mut moe)?;
}
}
let t5 = Instant::now();
par::for_chunks(&mut xs[b0 * e..(b0 + m) * e], e, |t, row| {
for (x, d) in row.iter_mut().zip(&moe[t * e..(t + 1) * e]) {
*x += d;
}
});
self.timings.other += t5.elapsed();
}
state.store_kv(l, pos0, &kc[pos0 * kw..], &vc[pos0 * kw..]);
if !progress((l + 1) as f64 / c.blocks as f64) {
self.timings.total = started.elapsed();
return Ok(None);
}
}
self.timings.total = started.elapsed();
Ok(Some(if all_hidden {
xs
} else {
xs[(n - 1) * e..].to_vec()
}))
}
/// One expert over up to `MAX_ROWS` of the batch's tokens: gate and up, the activation, down, and the
/// weighted add into `moe`.
#[allow(clippy::too_many_arguments)] // the pieces of one layer step, passed explicitly
fn expert(
&mut self,
dispatch: &Dispatch,
view: &LayerView<'_>,
name: &dyn Fn(&str) -> String,
ex: usize,
rows: &[(usize, f32)],
h2f: &[u16],
e: usize,
ff: usize,
moe: &mut [f32],
) -> Result<(), ModelError> {
let layout = self.client.layout;
let t0 = Instant::now();
let r = rows.len();
let mut gathered = vec![0u16; r * e];
for (i, (t, _)) in rows.iter().enumerate() {
gathered[i * e..(i + 1) * e].copy_from_slice(&h2f[t * e..(t + 1) * e]);
}
self.client.put(layout.input_a, &gathered).map_err(fail)?;
self.timings.other += t0.elapsed();
self.product(
&name("ffn_gate_exps"),
Some(ex),
r,
(e, ff),
layout.input_a,
layout.out[0],
)?;
self.product(
&name("ffn_up_exps"),
Some(ex),
r,
(e, ff),
layout.input_a,
layout.out[1],
)?;
let t1 = Instant::now();
let mut gate = self.fetch(layout.out[0], r, ff)?;
let mut up = self.fetch(layout.out[1], r, ff)?;
let (gate_b, up_b) = (
&view.gate_b[ex * ff..(ex + 1) * ff],
&view.up_b[ex * ff..(ex + 1) * ff],
);
let mut act = vec![0.0f32; r * ff];
let rows_per = 16;
// the bias adds, then the activation over blocks of rows on all cores
for (g, u) in gate.chunks_exact_mut(ff).zip(up.chunks_exact_mut(ff)) {
for ((x, b), (y, c)) in g.iter_mut().zip(gate_b).zip(u.iter_mut().zip(up_b)) {
*x += b;
*y += c;
}
}
par::for_chunks(&mut act, ff * rows_per, |i, out| {
let first = i * rows_per;
let count = out.len() / ff;
dispatch
.swiglu_oai(
&gate[first * ff..(first + count) * ff],
&up[first * ff..(first + count) * ff],
SWIGLU_ALPHA,
SWIGLU_LIMIT,
out,
)
.expect("activation kernel");
});
self.put_floats(dispatch, layout.input_b, &act)?;
self.timings.other += t1.elapsed();
self.product(
&name("ffn_down_exps"),
Some(ex),
r,
(ff, e),
layout.input_b,
layout.out[3],
)?;
let t2 = Instant::now();
let down = self.fetch(layout.out[3], r, e)?;
let down_b = &view.down_b[ex * e..(ex + 1) * e];
for (i, (t, weight)) in rows.iter().enumerate() {
for ((m, d), b) in moe[t * e..(t + 1) * e]
.iter_mut()
.zip(&down[i * e..(i + 1) * e])
.zip(down_b)
{
*m += weight * (d + b);
}
}
self.timings.other += t2.elapsed();
Ok(())
}
}
impl PrefillAccelerator for NpuPrefill {
fn prefill(
&mut self,
model: &Model,
state: &mut State,
tokens: &[u32],
pos0: usize,
progress: &mut dyn FnMut(f64) -> bool,
) -> Result<Option<Vec<f32>>, ModelError> {
self.run(model, state, tokens, pos0, progress, false)
}
}
/// Divide column `c` of the `width`-wide rows in `values` by `2^shifts[c]`.
fn scale_columns(values: &mut [f32], width: usize, shifts: &[u8]) {
let factors: Vec<f32> = shifts.iter().map(|s| 2f32.powi(-i32::from(*s))).collect();
par::for_chunks(values, width * 16, |_, chunk| {
for row in chunk.chunks_exact_mut(width) {
for (v, f) in row.iter_mut().zip(&factors) {
*v *= f;
}
}
});
}
/// Half-precision activations for the device. With `q8` the values first go through the CPU decoder's own 8-bit
/// activation quantisation (Q8_0 blocks, scale rounded to half) and back, so the product sees the same rounded
/// activations the CPU decoder and llama.cpp compute with and the paths differ only by the device's arithmetic.
fn halves_of(dispatch: &Dispatch, values: &[f32], q8: bool) -> Vec<u16> {
let mut halves = vec![0u16; values.len()];
let chunk = 4096; // a multiple of the 32-value block
par::for_chunks(&mut halves, chunk, |i, out| {
let src = &values[i * chunk..i * chunk + out.len()];
if !q8 {
dispatch.f32_to_f16(src, out).expect("equal lengths");
return;
}
let mut blocks = vec![0u8; src.len() / 32 * 34];
dispatch.quantize_q8_0(src, &mut blocks).expect("quantize");
let mut back = vec![0.0f32; src.len()];
for (block, row) in blocks
.as_chunks::<34>()
.0
.iter()
.zip(back.as_chunks_mut::<32>().0.iter_mut())
{
let mut scale = [0.0f32];
half::to_f32(&[u16::from_le_bytes([block[0], block[1]])], &mut scale);
for (v, q) in row.iter_mut().zip(&block[2..]) {
*v = f32::from(*q as i8) * scale[0];
}
}
dispatch.f32_to_f16(&back, out).expect("equal lengths");
});
halves
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn shifted_columns_are_divided_by_powers_of_two() {
let mut v = vec![8.0f32, 8.0, 8.0, 4.0, 4.0, 4.0];
scale_columns(&mut v, 3, &[0, 1, 3]);
assert_eq!(v, vec![8.0, 4.0, 1.0, 4.0, 2.0, 0.5]);
}
}
+89
View File
@@ -0,0 +1,89 @@
//! Small helpers for running a loop body on all cores with scoped threads.
use std::sync::atomic::{AtomicUsize, Ordering};
pub fn threads() -> usize {
std::thread::available_parallelism().map_or(1, |n| n.get())
}
/// Split `data` into chunks of `chunk` elements and run `f(chunk index, chunk)` over them on all cores.
pub fn for_chunks<T: Send>(data: &mut [T], chunk: usize, f: impl Fn(usize, &mut [T]) + Sync) {
let chunk = chunk.max(1);
let count = data.len().div_ceil(chunk);
let workers = threads().min(count).max(1);
if workers == 1 {
for (i, c) in data.chunks_mut(chunk).enumerate() {
f(i, c);
}
return;
}
let per = count.div_ceil(workers);
std::thread::scope(|scope| {
let f = &f;
for (w, part) in data.chunks_mut(per * chunk).enumerate() {
scope.spawn(move || {
for (i, c) in part.chunks_mut(chunk).enumerate() {
f(w * per + i, c);
}
});
}
});
}
/// Run `f(item, worker state)` for `items` work items claimed dynamically by all cores; each worker owns a
/// state made by `init`, and the states come back for the caller to combine.
pub fn dynamic<S: Send>(
items: usize,
init: impl Fn() -> S + Sync,
f: impl Fn(usize, &mut S) + Sync,
) -> Vec<S> {
let next = AtomicUsize::new(0);
let workers = threads().min(items).max(1);
std::thread::scope(|scope| {
let handles: Vec<_> = (0..workers)
.map(|_| {
scope.spawn(|| {
let mut state = init();
loop {
let i = next.fetch_add(1, Ordering::Relaxed);
if i >= items {
break;
}
f(i, &mut state);
}
state
})
})
.collect();
handles
.into_iter()
.map(|h| h.join().expect("worker panicked"))
.collect()
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn chunks_are_visited_once_with_their_index() {
let mut data = vec![0usize; 1000];
for_chunks(&mut data, 7, |i, c| {
for v in c.iter_mut() {
*v += i + 1;
}
});
for (j, v) in data.iter().enumerate() {
assert_eq!(*v, j / 7 + 1);
}
}
#[test]
fn dynamic_items_are_claimed_exactly_once() {
let states = dynamic(500, Vec::new, |i, s: &mut Vec<usize>| s.push(i));
let mut all: Vec<usize> = states.into_iter().flatten().collect();
all.sort_unstable();
assert_eq!(all, (0..500).collect::<Vec<_>>());
}
}
+66 -1
View File
@@ -10,7 +10,7 @@ use std::fs::File;
use std::io::BufReader;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Instant;
use std::time::{Duration, Instant};
/// Row counts the compiled graphs are specialised for; a product is padded up to the next one.
pub const BUCKETS: [usize; 6] = [32, 64, 128, 256, 512, 1024];
@@ -40,6 +40,9 @@ pub struct Product {
pub struct Done {
pub micros: u64,
pub bucket: usize,
/// The weight needed its scales boosted (see `expand::normalize_scales`): the per-column shifts follow
/// the result in the shared region, one byte per column, and the client divides column `c` by `2^shift[c]`.
pub shifted: bool,
}
/// The model file: tensors found by name, bytes borrowed from the mapping.
@@ -109,6 +112,8 @@ struct Slot {
s: Tensor,
/// The weight currently in `w` and `s`, so consecutive products with it skip the expansion.
loaded: Option<(String, Option<usize>)>,
/// Per-row scale shifts of the loaded weight (empty when none was needed).
shifts: Vec<u8>,
}
/// OpenVINO objects: the compiled graphs and the request slots built on them.
@@ -155,6 +160,7 @@ impl Runtime {
w,
s,
loaded: None,
shifts: Vec::new(),
},
);
}
@@ -168,6 +174,7 @@ pub struct Engine {
shm: Shared,
device_name: String,
scratch: Vec<u8>,
profile: Profile,
}
fn io_error(what: &str, e: impl std::fmt::Display) -> String {
@@ -210,6 +217,7 @@ impl Engine {
shm,
device_name,
scratch: Vec::new(),
profile: Profile::default(),
})
}
@@ -226,6 +234,11 @@ impl Engine {
/// little-endian half floats: `rows * k` in, `rows * n` out.
pub fn run(&mut self, p: &Product) -> Result<Done, String> {
let started = Instant::now();
let mut lap = Instant::now();
let mut tick = |total: &mut Duration| {
*total += lap.elapsed();
lap = Instant::now();
};
if p.rows == 0 {
return Err("a product needs at least one row".into());
}
@@ -245,8 +258,10 @@ impl Engine {
self.shm
.read(p.in_offset, &mut buffer[..in_bytes])
.map_err(|e| io_error("reading the activations", e))?;
tick(&mut self.profile.read_in);
let slot = self.runtime.slot(k, n, bucket)?;
tick(&mut self.profile.compile);
let id = (p.name.clone(), p.expert);
if slot.loaded.as_ref() != Some(&id) {
expand::expand_parallel(
@@ -255,23 +270,73 @@ impl Engine {
slot.w.bytes_mut().map_err(ov_error)?,
slot.s.bytes_mut().map_err(ov_error)?,
);
tick(&mut self.profile.expand);
slot.shifts = expand::normalize_scales(slot.s.bytes_mut().map_err(ov_error)?, n);
if slot.shifts.iter().all(|s| *s == 0) {
slot.shifts.clear();
}
slot.loaded = Some(id);
tick(&mut self.profile.normalize);
}
slot.x.write(0, &buffer[..in_bytes]).map_err(ov_error)?;
slot.x.bytes_mut().map_err(ov_error)?[in_bytes..].fill(0);
tick(&mut self.profile.x_write);
slot.request.infer().map_err(ov_error)?;
tick(&mut self.profile.infer);
slot.request
.output(0)
.map_err(ov_error)?
.read(0, &mut buffer[..out_bytes])
.map_err(ov_error)?;
tick(&mut self.profile.out_read);
self.shm
.write(p.out_offset, &buffer[..out_bytes])
.map_err(|e| io_error("writing the result", e))?;
let shifted = !slot.shifts.is_empty();
if shifted {
self.shm
.write(p.out_offset + out_bytes, &slot.shifts)
.map_err(|e| io_error("writing the scale shifts", e))?;
}
self.scratch = buffer;
tick(&mut self.profile.shm_write);
self.profile.calls += 1;
Ok(Done {
micros: started.elapsed().as_micros() as u64,
bucket,
shifted,
})
}
/// Where the time of all products so far went, one line.
pub fn profile_report(&self) -> String {
let p = &self.profile;
let ms = |d: Duration| d.as_secs_f64() * 1e3;
format!(
"{} products: read activations {:.0} ms | slot/compile {:.0} | expand weights {:.0} | scale shifts {:.0} | write activations {:.0} | infer {:.0} | read result {:.0} | write result {:.0}",
p.calls,
ms(p.read_in),
ms(p.compile),
ms(p.expand),
ms(p.normalize),
ms(p.x_write),
ms(p.infer),
ms(p.out_read),
ms(p.shm_write)
)
}
}
/// Time spent in each phase of `Engine::run`, summed over products.
#[derive(Default)]
struct Profile {
calls: u64,
read_in: Duration,
compile: Duration,
expand: Duration,
normalize: Duration,
x_write: Duration,
infer: Duration,
out_read: Duration,
shm_write: Duration,
}
+121
View File
@@ -180,3 +180,124 @@ mod tests {
}
}
}
/// Round `x` to the nearest half float (ties to even) and return its bits; values beyond the half range
/// saturate to the largest finite half.
pub fn f32_to_f16_bits(x: f32) -> u16 {
let bits = x.to_bits();
let sign = ((bits >> 16) & 0x8000) as u16;
let magnitude = bits & 0x7FFF_FFFF;
if magnitude >= 0x4780_0000 {
// 65536 and above (or infinity/NaN): saturate
return sign | 0x7BFF;
}
if magnitude < 0x3300_0000 {
// below 2^-25: rounds to zero
return sign;
}
let exp = (magnitude >> 23) as i32 - 127;
if exp < -14 {
// subnormal half: a multiple of 2^-24
let shift = (-exp - 14 + 13) as u32; // right shift of the 24-bit significand
let significand = (magnitude & 0x7F_FFFF) | 0x80_0000;
let kept = significand >> shift;
let rest = significand & ((1 << shift) - 1);
let half = 1 << (shift - 1);
let rounded = kept + u32::from(rest > half || (rest == half && kept & 1 == 1));
return sign | rounded as u16;
}
let mantissa = magnitude & 0x7F_FFFF;
let kept = mantissa >> 13;
let rest = mantissa & 0x1FFF;
let rounded = kept + u32::from(rest > 0x1000 || (rest == 0x1000 && kept & 1 == 1));
let packed = (((exp + 15) as u32) << 10) + rounded; // a mantissa carry increments the exponent
sign | packed.min(0x7BFF) as u16
}
/// The NPU flushes half-precision subnormals to zero, which would erase every weight block whose scale is
/// below 2^-14 (common in Q8_0 attention weights). For each row whose scales (`s`: little-endian halves, a
/// whole number per row) include a subnormal, multiply all scales of that row by `2^shift` so the smallest
/// becomes normal, and return the shifts (one per row, 0 for untouched rows): the product row has to be scaled
/// back by `2^-shift`.
pub fn normalize_scales(s: &mut [u8], rows: usize) -> Vec<u8> {
let per_row = s.len() / 2 / rows.max(1);
let mut shifts = vec![0u8; rows];
for (row, shift) in s.chunks_exact_mut(per_row * 2).zip(shifts.iter_mut()) {
let smallest = row
.as_chunks::<2>()
.0
.iter()
.map(|b| u16::from_le_bytes(*b))
.filter(|bits| *bits != 0 && (*bits & 0x7FFF) < 0x0400)
.map(|bits| bits & 0x7FFF)
.min();
let Some(smallest) = smallest else { continue };
// value = smallest * 2^-24; want >= 2^-14, i.e. a factor of 2^(10 - floor(log2(smallest)))
let s_exp = 10 - smallest.ilog2();
*shift = s_exp as u8;
for b in row.as_chunks_mut::<2>().0.iter_mut() {
let bits = u16::from_le_bytes(*b);
if bits & 0x7FFF == 0 {
continue;
}
let value = half_bits_to_f32(bits) * (1u32 << s_exp) as f32;
*b = f32_to_f16_bits(value).to_le_bytes();
}
}
shifts
}
fn half_bits_to_f32(bits: u16) -> f32 {
let sign = if bits & 0x8000 != 0 { -1.0f32 } else { 1.0 };
let exp = i32::from((bits >> 10) & 31);
let man = f32::from(bits & 1023);
sign * if exp == 0 {
man * 2f32.powi(-24)
} else {
(1.0 + man / 1024.0) * 2f32.powi(exp - 15)
}
}
#[cfg(test)]
mod scale_tests {
use super::*;
#[test]
fn rounding_to_half_matches_known_values() {
for (x, bits) in [
(1.0f32, 0x3C00u16),
(-2.0, 0xC000),
(65504.0, 0x7BFF),
(1e9, 0x7BFF),
(2f32.powi(-14), 0x0400),
(2f32.powi(-24), 0x0001),
(2f32.powi(-25), 0x0000),
(1.0 + 2f32.powi(-11), 0x3C00), // tie goes to even
(1.0 + 3.0 * 2f32.powi(-11), 0x3C02),
(0.0, 0),
] {
assert_eq!(f32_to_f16_bits(x), bits, "{x}");
}
// every half converts back to itself
for bits in (0u16..0x7C00).chain(0x8000..0xFC00) {
assert_eq!(f32_to_f16_bits(half_bits_to_f32(bits)), bits, "{bits:#06x}");
}
}
#[test]
fn rows_with_subnormal_scales_are_boosted_and_the_shift_recorded() {
// row 0: scales 0x0010 (subnormal), 0x3000 (normal); row 1: all normal; row 2: has a zero scale too
let halves = [0x0010u16, 0x3000, 0x3C00, 0x3800, 0x0000, 0x0200];
let mut s: Vec<u8> = halves.iter().flat_map(|h| h.to_le_bytes()).collect();
let shifts = normalize_scales(&mut s, 3);
let get = |i: usize| u16::from_le_bytes([s[i * 2], s[i * 2 + 1]]);
// 0x0010 = 16 * 2^-24: shift 10 - 4 = 6 -> 2^-14 exactly (0x0400)
assert_eq!(shifts, vec![6, 0, 1]);
assert_eq!(get(0), 0x0400);
assert_eq!(half_bits_to_f32(get(1)), half_bits_to_f32(0x3000) * 64.0);
assert_eq!((get(2), get(3)), (0x3C00, 0x3800), "untouched row");
assert_eq!(get(4), 0, "zero stays zero");
// 0x0200 = 512 * 2^-24: shift 10 - 9 = 1
assert_eq!(get(5), 0x0400);
}
}
+3
View File
@@ -72,5 +72,8 @@ fn main() -> ExitCode {
break;
}
}
if std::env::var_os("LELEKA_NPU_PROFILE").is_some() {
eprintln!("leleka-npu-service: {}", engine.profile_report());
}
ExitCode::SUCCESS
}
+10 -4
View File
@@ -1,7 +1,7 @@
//! The line protocol between the client and the service (docs/npu-service.md).
//!
//! Client to service: `PING`, `MM <tensor> <expert|-> <rows> <in_offset> <out_offset>`, `QUIT`.
//! Service to client: `READY <device name>` once at start, then `PONG`, `OK <micros> <bucket>` or `ERR <message>`
//! Service to client: `READY <device name>` once at start, then `PONG`, `OK <micros> <bucket> <shifted>` or `ERR <message>`
//! per line. Offsets are byte offsets into the shared region; activations and results are half floats.
use crate::engine::{Done, Product};
@@ -51,7 +51,12 @@ pub fn ready_line(device_name: &str) -> String {
}
pub fn ok_line(done: Done) -> String {
format!("OK {} {}", done.micros, done.bucket)
format!(
"OK {} {} {}",
done.micros,
done.bucket,
u8::from(done.shifted)
)
}
pub fn err_line(message: &str) -> String {
@@ -98,9 +103,10 @@ mod tests {
assert_eq!(
ok_line(Done {
micros: 12,
bucket: 64
bucket: 64,
shifted: false
}),
"OK 12 64"
"OK 12 64 0"
);
}
}
+71 -13
View File
@@ -15,7 +15,11 @@ 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) }
sign * if exp == 0 {
man * 2f64.powi(-24)
} else {
(1.0 + man / 1024.0) * 2f64.powi(exp - 15)
}
}
fn f32_to_f16(x: f32) -> u16 {
@@ -41,7 +45,11 @@ fn env() -> Option<Env> {
let model = PathBuf::from(std::env::var("LELEKA_GPTOSS_GGUF").ok()?);
let root = PathBuf::from(std::env::var("LELEKA_OPENVINO_ROOT").ok()?);
let device = std::env::var("LELEKA_OPENVINO_DEVICE").unwrap_or_else(|_| "NPU".into());
Some(Env { model, root, device })
Some(Env {
model,
root,
device,
})
}
struct Service {
@@ -58,9 +66,9 @@ impl Service {
let shm = Shared::create(&path, 64 << 20).unwrap();
let bin = env.root.join("runtime/bin/intel64/Release");
let tbb = env.root.join("runtime/3rdparty/tbb/bin");
let search = std::env::join_paths(
[bin.clone(), tbb].into_iter().chain(std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default())),
)
let search = std::env::join_paths([bin.clone(), tbb].into_iter().chain(
std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default()),
))
.unwrap();
let mut child = Command::new(env!("CARGO_BIN_EXE_leleka-npu-service"))
.env("PATH", search)
@@ -82,7 +90,13 @@ impl Service {
stdout.read_line(&mut line).unwrap();
assert!(line.starts_with("READY"), "{line:?}");
eprintln!("service: {}", line.trim_end());
Self { child, stdin, stdout, shm, path }
Self {
child,
stdin,
stdout,
shm,
path,
}
}
fn ask(&mut self, line: &str) -> String {
@@ -126,7 +140,11 @@ fn reference_rows(env: &Env, name: &str, first: usize, n: usize) -> (Vec<f64>, u
match t.tensor_type {
TensorType::Q8_0 => {
let scale = f16_to_f64(u16::from_le_bytes([all[at], all[at + 1]]));
out.extend(all[at + 2..at + 34].iter().map(|q| scale * f64::from(*q as i8)));
out.extend(
all[at + 2..at + 34]
.iter()
.map(|q| scale * f64::from(*q as i8)),
);
}
_ => {
const HALVES: [f64; 8] = [0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0];
@@ -145,11 +163,23 @@ fn reference_rows(env: &Env, name: &str, first: usize, n: usize) -> (Vec<f64>, u
(out, k)
}
fn compare(env: &Env, svc: &mut Service, name: &str, expert: Option<usize>, rows: usize, seed: u64) {
fn compare(
env: &Env,
svc: &mut Service,
name: &str,
expert: Option<usize>,
rows: usize,
seed: u64,
) {
let info_dims = {
let file = std::fs::File::open(&env.model).unwrap();
let size = file.metadata().unwrap().len();
Gguf::read(BufReader::new(file), size).unwrap().tensor(name).unwrap().dims.clone()
Gguf::read(BufReader::new(file), size)
.unwrap()
.tensor(name)
.unwrap()
.dims
.clone()
};
let (n, first) = match expert {
None => (info_dims[1..].iter().product::<u64>() as usize, 0),
@@ -172,18 +202,41 @@ fn compare(env: &Env, svc: &mut Service, name: &str, expert: Option<usize>, rows
assert!(answer.starts_with("OK"), "{name}: {answer}");
let mut out = vec![0u8; rows * n * 2];
svc.shm.read(out_off, &mut out).unwrap();
// the service reports a boost of subnormal scales and appends one shift per column
let shifted = answer.split_whitespace().nth(3) == Some("1");
let mut shifts = vec![0u8; n];
if shifted {
svc.shm.read(out_off + rows * n * 2, &mut shifts).unwrap();
}
let (mut num, mut den, mut worst) = (0f64, 0f64, 0f64);
let mut by_eighth = [(0f64, 0f64); 8];
for r in 0..rows {
for c in 0..n {
let want: f64 = (0..k).map(|i| f16_to_f64(x[r * k + i]) * w[c * k + i]).sum();
let got = f16_to_f64(u16::from_le_bytes([out[(r * n + c) * 2], out[(r * n + c) * 2 + 1]]));
let want: f64 = (0..k)
.map(|i| f16_to_f64(x[r * k + i]) * w[c * k + i])
.sum();
let raw = f16_to_f64(u16::from_le_bytes([
out[(r * n + c) * 2],
out[(r * n + c) * 2 + 1],
]));
let got = raw / 2f64.powi(i32::from(shifts[c]));
num += (got - want) * (got - want);
den += want * want;
worst = worst.max((got - want).abs());
by_eighth[c * 8 / n].0 += (got - want) * (got - want);
by_eighth[c * 8 / n].1 += want * want;
}
}
let rel = (num / den).sqrt();
eprintln!("{name} expert {expert:?} rows {rows}: relative rms error {rel:.2e}, worst abs {worst:.3e}, {answer}");
let shown: Vec<String> = by_eighth
.iter()
.map(|(a, b)| format!("{:.1e}", (a / b.max(1e-30)).sqrt()))
.collect();
eprintln!(
"{name} expert {expert:?} rows {rows}: relative rms error {rel:.2e}, worst abs {worst:.3e}, shifted columns {}, {answer}\n error by eighth of the columns: {}",
shifts.iter().filter(|s| **s > 0).count(),
shown.join(" ")
);
assert!(rel < 5e-3, "{name}: relative rms error {rel}");
}
@@ -197,12 +250,17 @@ fn products_match_the_dequantized_reference() {
assert_eq!(svc.ask("PING"), "PONG");
// Q8_0 attention weights, a row count that is not a bucket
compare(&env, &mut svc, "blk.0.attn_k.weight", None, 37, 1);
compare(&env, &mut svc, "blk.0.attn_q.weight", None, 37, 5);
compare(&env, &mut svc, "blk.0.attn_output.weight", None, 37, 6);
// MXFP4 experts: two different experts, then the first again (reload), another row count
compare(&env, &mut svc, "blk.2.ffn_down_exps.weight", Some(5), 70, 2);
compare(&env, &mut svc, "blk.2.ffn_down_exps.weight", Some(9), 70, 3);
compare(&env, &mut svc, "blk.2.ffn_down_exps.weight", Some(5), 33, 4);
// errors are replies, not crashes
assert!(svc.ask("MM blk.0.nope.weight - 4 0 8").starts_with("ERR"));
assert!(svc.ask("MM blk.0.attn_k.weight - 5000 0 8").starts_with("ERR"));
assert!(
svc.ask("MM blk.0.attn_k.weight - 5000 0 8")
.starts_with("ERR")
);
assert_eq!(svc.ask("PING"), "PONG");
}
+18
View File
@@ -0,0 +1,18 @@
[package]
name = "leleka-npu-worker"
version = "0.1.0"
description = "Leleka inference worker with NPU-assisted prefill: the CPU worker's decoder, with long prompts' matrix products run by the NPU service process (experimental)"
edition.workspace = true
license.workspace = true
rust-version.workspace = true
[[bin]]
name = "leleka-npu-worker"
path = "src/main.rs"
[dependencies]
leleka-cpu-worker = { path = "../cpu-worker" }
leleka-gptoss-npu = { path = "../gptoss-npu" }
[lints]
workspace = true
+175
View File
@@ -0,0 +1,175 @@
//! `leleka-npu-worker --serve --model <gpt-oss.gguf> --openvino-root <dir> [--npu-service <exe>] [--npu-device NPU]
//! [--npu-min-tokens N] [--npu-batch N] [--threads N] [--ctx N] [--no-warm] [--seed N]` (experimental)
//!
//! The CPU worker's decoder and protocol with one addition: prompts that need at least `--npu-min-tokens`
//! tokens computed have their matrix products run by the NPU service process (`leleka-npu-service`, which
//! loads OpenVINO and reads the model itself; this worker loads no OpenVINO code); everything else, and all
//! decoding, stays on the CPU. If the service cannot start the worker says so on standard error and serves from
//! the CPU only; if an NPU prefill fails it is redone on the CPU and the NPU is not used again in that session.
use leleka_cpu_worker::engine::{self, LoadOptions};
use leleka_cpu_worker::serve::serve;
use leleka_gptoss_npu::client::ServiceConfig;
use leleka_gptoss_npu::{DEFAULT_BATCH, NpuPrefill};
use std::io::{self, BufReader};
use std::path::PathBuf;
use std::process::ExitCode;
const DEFAULT_CONTEXT: usize = 32_768;
/// Below this many tokens the CPU is as fast or faster (see docs/npu-service.md).
const DEFAULT_NPU_MIN_TOKENS: usize = 1024;
struct Args {
model: PathBuf,
threads: usize,
context: usize,
warm: bool,
seed: u64,
openvino_root: Option<PathBuf>,
service: Option<PathBuf>,
device: String,
min_tokens: usize,
batch: usize,
}
fn usage() -> &'static str {
"usage: leleka-npu-worker --serve --model <gpt-oss.gguf> --openvino-root <dir> [--npu-service <exe>] [--npu-device NPU] [--npu-min-tokens N] [--npu-batch N] [--threads N] [--ctx N] [--no-warm] [--seed N]"
}
fn parse_args() -> Result<Args, String> {
let mut args = std::env::args().skip(1);
let mut model = None;
let mut threads = std::thread::available_parallelism().map_or(1, |n| n.get());
let mut context = DEFAULT_CONTEXT;
let mut warm = true;
let mut seed = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0x5EED, |d| d.as_nanos() as u64);
let mut openvino_root = std::env::var_os("LELEKA_OPENVINO_ROOT").map(PathBuf::from);
let mut service = None;
let mut device = "NPU".to_owned();
let mut min_tokens = DEFAULT_NPU_MIN_TOKENS;
let mut batch = DEFAULT_BATCH;
let mut serving = false;
let number = |name: &str, value: Option<String>| -> Result<u64, String> {
value
.and_then(|v| v.parse::<u64>().ok())
.ok_or_else(|| format!("{name} needs a number"))
};
while let Some(arg) = args.next() {
match arg.as_str() {
"--serve" => serving = true,
"--model" => model = Some(PathBuf::from(args.next().ok_or("--model needs a path")?)),
"--threads" => threads = number("--threads", args.next())?.max(1) as usize,
"--ctx" => context = number("--ctx", args.next())?.max(16) as usize,
"--no-warm" => warm = false,
"--seed" => seed = number("--seed", args.next())?,
"--openvino-root" => {
openvino_root = Some(PathBuf::from(
args.next().ok_or("--openvino-root needs a path")?,
));
}
"--npu-service" => {
service = Some(PathBuf::from(
args.next().ok_or("--npu-service needs a path")?,
));
}
"--npu-device" => device = args.next().ok_or("--npu-device needs a name")?,
"--npu-min-tokens" => {
min_tokens = number("--npu-min-tokens", args.next())?.max(1) as usize;
}
"--npu-batch" => batch = number("--npu-batch", args.next())?.max(1) as usize,
other => return Err(format!("unknown argument {other}")),
}
}
if !serving {
return Err("only --serve mode exists".into());
}
Ok(Args {
model: model.ok_or("--model is required")?,
threads,
context,
warm,
seed,
openvino_root,
service,
device,
min_tokens,
batch,
})
}
/// The service executable next to this one, unless the caller named another.
fn default_service() -> PathBuf {
let name = if cfg!(windows) {
"leleka-npu-service.exe"
} else {
"leleka-npu-service"
};
std::env::current_exe()
.ok()
.and_then(|exe| exe.parent().map(|dir| dir.join(name)))
.unwrap_or_else(|| PathBuf::from(name))
}
fn main() -> ExitCode {
let args = match parse_args() {
Ok(args) => args,
Err(message) => {
eprintln!("leleka-npu-worker: {message}\n{}", usage());
return ExitCode::from(2);
}
};
let loaded = match engine::load(&LoadOptions {
model: &args.model,
threads: args.threads,
context: args.context,
warm: args.warm,
}) {
Ok(loaded) => loaded,
Err(message) => {
eprintln!("leleka-npu-worker: {message}");
return ExitCode::FAILURE;
}
};
let mut engine = loaded.engine;
match args.openvino_root.clone() {
None => eprintln!(
"leleka-npu-worker: no --openvino-root (or LELEKA_OPENVINO_ROOT); serving from the CPU only"
),
Some(openvino_root) => {
let config = ServiceConfig {
service: args.service.clone().unwrap_or_else(default_service),
openvino_root,
device: args.device.clone(),
model: args.model.clone(),
};
match NpuPrefill::start(&config, args.batch) {
Ok(npu) => {
eprintln!(
"leleka-npu-worker: NPU prefill on {} for prompts of at least {} tokens (batch {})",
npu.device_name(),
args.min_tokens,
args.batch
);
engine.set_accelerator(Box::new(npu), args.min_tokens);
}
Err(e) => eprintln!("leleka-npu-worker: {e}; serving from the CPU only"),
}
}
}
let stdin = BufReader::new(io::stdin());
match serve(
&mut engine,
stdin,
io::stdout(),
&loaded.stop_tokens,
args.seed,
) {
Ok(()) => ExitCode::SUCCESS,
Err(e) => {
eprintln!("leleka-npu-worker: {e}");
ExitCode::FAILURE
}
}
}
+129
View File
@@ -0,0 +1,129 @@
//! End to end with the real gpt-oss-20b file: spawn the NPU-prefill worker (every prompt of at least one
//! token goes through the NPU service), speak the line protocol to it. The continuation after a cached prefix
//! exercises the NPU path continuing from keys and values the CPU decoder produced.
//!
//! Needs `LELEKA_GPTOSS_GGUF` (the model, about 12 GB) and `LELEKA_OPENVINO_ROOT` (the unpacked OpenVINO archive),
//! and `leleka-npu-service` built next to the worker; skipped otherwise. `LELEKA_OPENVINO_DEVICE` defaults to NPU.
use std::io::{BufRead, BufReader, Write};
use std::process::{Child, ChildStdin, Command, Stdio};
const PROMPT: [u32; 5] = [976, 9029, 328, 10128, 382];
/// llama.cpp's first greedy token after "The capital of France is" (later tokens are near-ties that
/// tiny numeric differences flip).
const FIRST_TOKEN: u32 = 12650;
struct Worker {
child: Child,
stdin: ChildStdin,
stdout: BufReader<std::process::ChildStdout>,
}
impl Worker {
fn start(model: &str) -> Self {
let root = std::env::var("LELEKA_OPENVINO_ROOT").expect("LELEKA_OPENVINO_ROOT");
let device = std::env::var("LELEKA_OPENVINO_DEVICE").unwrap_or_else(|_| "NPU".into());
let mut child = Command::new(env!("CARGO_BIN_EXE_leleka-npu-worker"))
.args([
"--serve",
"--model",
model,
"--threads",
"4",
"--ctx",
"512",
"--no-warm",
"--openvino-root",
&root,
"--npu-device",
&device,
"--npu-min-tokens",
"1",
])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.spawn()
.expect("spawn the worker");
let stdin = child.stdin.take().unwrap();
let mut stdout = BufReader::new(child.stdout.take().unwrap());
let mut line = String::new();
stdout.read_line(&mut line).expect("READY line");
assert_eq!(line.trim_end(), "READY 512 stop");
Self {
child,
stdin,
stdout,
}
}
/// Send one GEN line; return the generated tokens and the DONE line.
fn generate(&mut self, max_new: u32, prompt: &[u32]) -> (Vec<u32>, String, usize) {
let ids: Vec<String> = prompt.iter().map(u32::to_string).collect();
writeln!(self.stdin, "GEN {max_new} {}", ids.join(",")).unwrap();
self.stdin.flush().unwrap();
let (mut tokens, mut reused) = (Vec::new(), 0);
loop {
let mut line = String::new();
assert!(
self.stdout.read_line(&mut line).unwrap() > 0,
"worker exited"
);
let line = line.trim_end().to_owned();
if let Some(t) = line.strip_prefix("T ") {
tokens.push(t.parse().unwrap());
} else if let Some(n) = line.strip_prefix("REUSED ") {
reused = n.parse().unwrap();
} else if line.starts_with("DONE ") {
return (tokens, line, reused);
} else {
assert!(line.starts_with("PP "), "unexpected line {line:?}");
}
}
}
}
impl Drop for Worker {
fn drop(&mut self) {
let _ = writeln!(self.stdin, "QUIT");
let _ = self.stdin.flush();
let _ = self.child.wait();
}
}
#[test]
fn the_npu_worker_serves_prompts_and_continues_from_a_cached_prefix() {
let (Ok(model), Ok(_)) = (
std::env::var("LELEKA_GPTOSS_GGUF"),
std::env::var("LELEKA_OPENVINO_ROOT"),
) else {
eprintln!(
"skipped: set LELEKA_GPTOSS_GGUF and LELEKA_OPENVINO_ROOT (and build leleka-npu-service) to run this test"
);
return;
};
let mut worker = Worker::start(&model);
// the whole prompt is prefilled on the GPU (--gpu-min-tokens 1)
let (tokens, done, reused) = worker.generate(16, &PROMPT);
assert_eq!(tokens.len(), 16);
assert_eq!(tokens[0], FIRST_TOKEN);
assert_eq!(reused, 0);
let fields: Vec<&str> = done.split_whitespace().collect();
assert_eq!(&fields[1..3], ["16", "5"], "{done}");
assert_eq!(fields[5], "length");
// the prompt plus the first four generated tokens: the cached prefix is reused and the NPU path computes
// only the last token on top of keys and values it did not produce. The numbers differ slightly from
// the CPU's, so near-tie tokens may differ; the count and the reuse are what is checked.
let mut longer = PROMPT.to_vec();
longer.extend_from_slice(&tokens[..4]);
let (continued, done, reused) = worker.generate(12, &longer);
assert_eq!(reused, longer.len() - 1, "{done}");
assert_eq!(continued.len(), 12);
// a different prompt shares one token and still works after the reuse
let (tokens, _, reused) = worker.generate(3, &[976, 9029]);
assert_eq!(tokens.len(), 3);
assert_eq!(reused, 1);
}