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>
This commit is contained in:
Pavlo Ratushnyi
2026-10-15 12:22:13 +02:00
co-authored by Claude Sonnet 5.5
parent b5d9a569b2
commit 8d96e9c44c
18 changed files with 861 additions and 234 deletions
Generated
+1
View File
@@ -1355,6 +1355,7 @@ version = "0.1.0"
dependencies = [ dependencies = [
"leleka-cpu-worker", "leleka-cpu-worker",
"leleka-gptoss-npu", "leleka-gptoss-npu",
"sysinfo",
] ]
[[package]] [[package]]
+10
View File
@@ -108,6 +108,7 @@ type AttnScores =
fn(&[f32], usize, &[u16], usize, usize, f32, &mut [f32]) -> Result<(), KernelError>; fn(&[f32], usize, &[u16], usize, usize, f32, &mut [f32]) -> Result<(), KernelError>;
type AttnSum = fn(&[f32], usize, usize, &[u16], usize, &mut [f32]) -> Result<(), KernelError>; type AttnSum = fn(&[f32], usize, usize, &[u16], usize, &mut [f32]) -> Result<(), KernelError>;
type ToHalf = fn(&[f32], &mut [u16]) -> Result<(), KernelError>; type ToHalf = fn(&[f32], &mut [u16]) -> Result<(), KernelError>;
type FromHalf = fn(&[u16], &mut [f32]) -> Result<(), KernelError>;
type RowsDot = fn(&[f32], &[f32], usize, usize, &mut [f32]) -> Result<(), KernelError>; type RowsDot = fn(&[f32], &[f32], usize, usize, &mut [f32]) -> Result<(), KernelError>;
type Swiglu = fn(&[f32], &[f32], f32, f32, &mut [f32]) -> Result<(), KernelError>; type Swiglu = fn(&[f32], &[f32], f32, f32, &mut [f32]) -> Result<(), KernelError>;
type ExpSum = fn(&mut [f32], f32) -> Result<f32, KernelError>; type ExpSum = fn(&mut [f32], f32) -> Result<f32, KernelError>;
@@ -128,6 +129,7 @@ pub struct Dispatch {
attn_weighted_sum: AttnSum, attn_weighted_sum: AttnSum,
exp_shift_sum: ExpSum, exp_shift_sum: ExpSum,
f32_to_f16: ToHalf, f32_to_f16: ToHalf,
f16_to_f32: FromHalf,
rows_dot: RowsDot, rows_dot: RowsDot,
swiglu_oai: Swiglu, swiglu_oai: Swiglu,
} }
@@ -163,6 +165,7 @@ impl Dispatch {
attn_scores: leleka_cpu_sys::attn_scores_f16_scalar, attn_scores: leleka_cpu_sys::attn_scores_f16_scalar,
attn_weighted_sum: leleka_cpu_sys::attn_weighted_sum_f16_scalar, attn_weighted_sum: leleka_cpu_sys::attn_weighted_sum_f16_scalar,
f32_to_f16: leleka_cpu_sys::f32_to_f16_slice_scalar, f32_to_f16: leleka_cpu_sys::f32_to_f16_slice_scalar,
f16_to_f32: leleka_cpu_sys::f16_to_f32_slice_scalar,
rows_dot: |q, rows, stride, n, out| { rows_dot: |q, rows, stride, n, out| {
leleka_cpu_sys::attn_scores_scalar(q, 1, rows, stride, n, 1.0, out) leleka_cpu_sys::attn_scores_scalar(q, 1, rows, stride, n, 1.0, out)
}, },
@@ -183,6 +186,7 @@ impl Dispatch {
attn_scores: leleka_cpu_sys::attn_scores_f16_avx2, attn_scores: leleka_cpu_sys::attn_scores_f16_avx2,
attn_weighted_sum: leleka_cpu_sys::attn_weighted_sum_f16_avx2, attn_weighted_sum: leleka_cpu_sys::attn_weighted_sum_f16_avx2,
f32_to_f16: leleka_cpu_sys::f32_to_f16_slice_avx2, f32_to_f16: leleka_cpu_sys::f32_to_f16_slice_avx2,
f16_to_f32: leleka_cpu_sys::f16_to_f32_slice_avx2,
rows_dot: |q, rows, stride, n, out| { rows_dot: |q, rows, stride, n, out| {
leleka_cpu_sys::attn_scores_avx2(q, 1, rows, stride, n, 1.0, out) leleka_cpu_sys::attn_scores_avx2(q, 1, rows, stride, n, 1.0, out)
}, },
@@ -205,6 +209,7 @@ impl Dispatch {
attn_scores: leleka_cpu_sys::attn_scores_f16_avx2, attn_scores: leleka_cpu_sys::attn_scores_f16_avx2,
attn_weighted_sum: leleka_cpu_sys::attn_weighted_sum_f16_avx2, attn_weighted_sum: leleka_cpu_sys::attn_weighted_sum_f16_avx2,
f32_to_f16: leleka_cpu_sys::f32_to_f16_slice_avx2, f32_to_f16: leleka_cpu_sys::f32_to_f16_slice_avx2,
f16_to_f32: leleka_cpu_sys::f16_to_f32_slice_avx2,
rows_dot: |q, rows, stride, n, out| { rows_dot: |q, rows, stride, n, out| {
leleka_cpu_sys::attn_scores_avx2(q, 1, rows, stride, n, 1.0, out) leleka_cpu_sys::attn_scores_avx2(q, 1, rows, stride, n, 1.0, out)
}, },
@@ -339,6 +344,11 @@ impl Dispatch {
(self.f32_to_f16)(src, dst) (self.f32_to_f16)(src, dst)
} }
/// Half bit patterns to floats (exact), `dst.len() == src.len()`.
pub fn f16_to_f32(&self, src: &[u16], dst: &mut [f32]) -> Result<(), KernelError> {
(self.f16_to_f32)(src, dst)
}
/// Replaces each `x[i]` by `exp(x[i] - max)` and returns their sum (softmax numerators). /// Replaces each `x[i]` by `exp(x[i] - max)` and returns their sum (softmax numerators).
pub fn exp_shift_sum(&self, x: &mut [f32], max: f32) -> Result<f32, KernelError> { pub fn exp_shift_sum(&self, x: &mut [f32], max: f32) -> Result<f32, KernelError> {
(self.exp_shift_sum)(x, max) (self.exp_shift_sum)(x, max)
+18
View File
@@ -593,6 +593,24 @@ pub fn f32_to_f16_slice_avx2(src: &[f32], dst: &mut [u16]) -> Result<(), KernelE
} }
with_avx2!(simd::x86::f32_to_f16_slice_avx2(src, dst)) with_avx2!(simd::x86::f32_to_f16_slice_avx2(src, dst))
} }
/// IEEE half bit patterns to floats (portable). The slices must be equally long.
pub fn f16_to_f32_slice_scalar(src: &[u16], dst: &mut [f32]) -> Result<(), KernelError> {
if src.len() != dst.len() {
return Err(KernelError::LengthMismatch);
}
simd::f16_to_f32_slice_scalar(src, dst);
Ok(())
}
/// F16C level of [`f16_to_f32_slice_scalar`]; bit-identical to it.
#[cfg(target_arch = "x86_64")]
pub fn f16_to_f32_slice_avx2(src: &[u16], dst: &mut [f32]) -> Result<(), KernelError> {
if src.len() != dst.len() {
return Err(KernelError::LengthMismatch);
}
with_avx2!(simd::x86::f16_to_f32_slice_avx2(src, dst))
}
/// Replaces each `x[i]` by `exp(x[i] - max)` and returns their sum (portable). /// Replaces each `x[i]` by `exp(x[i] - max)` and returns their sum (portable).
pub fn exp_shift_sum_scalar(x: &mut [f32], max: f32) -> Result<f32, KernelError> { pub fn exp_shift_sum_scalar(x: &mut [f32], max: f32) -> Result<f32, KernelError> {
Ok(simd::exp_shift_sum_scalar(x, max)) Ok(simd::exp_shift_sum_scalar(x, max))
+22
View File
@@ -276,6 +276,13 @@ pub fn swiglu_oai_scalar(gate: &[f32], up: &[f32], alpha: f32, limit: f32, out:
} }
} }
/// Converts IEEE half bit patterns to floats, `dst.len() == src.len()`.
pub fn f16_to_f32_slice_scalar(src: &[u16], dst: &mut [f32]) {
for (d, s) in dst.iter_mut().zip(src) {
*d = f16_to_f32(*s);
}
}
/// Converts floats to IEEE half bit patterns (round to nearest even), `dst.len() == src.len()`. /// Converts floats to IEEE half bit patterns (round to nearest even), `dst.len() == src.len()`.
pub fn f32_to_f16_slice_scalar(src: &[f32], dst: &mut [u16]) { pub fn f32_to_f16_slice_scalar(src: &[f32], dst: &mut [u16]) {
for (d, s) in dst.iter_mut().zip(src) { for (d, s) in dst.iter_mut().zip(src) {
@@ -1485,6 +1492,21 @@ pub mod x86 {
} }
} }
/// Converts half bit patterns to floats with F16C; `dst.len() == src.len()`.
#[target_feature(enable = "avx2,f16c")]
pub unsafe fn f16_to_f32_slice_avx2(src: &[u16], dst: &mut [f32]) {
let mut i = 0;
while i + 8 <= src.len() {
let h = _mm_loadu_si128(src.as_ptr().add(i) as *const __m128i);
_mm256_storeu_ps(dst.as_mut_ptr().add(i), _mm256_cvtph_ps(h));
i += 8;
}
while i < src.len() {
dst[i] = super::f16_to_f32(src[i]);
i += 1;
}
}
#[target_feature(enable = "avx2,fma")] #[target_feature(enable = "avx2,fma")]
pub unsafe fn swiglu_oai_avx2( pub unsafe fn swiglu_oai_avx2(
gate: &[f32], gate: &[f32],
+26
View File
@@ -371,3 +371,29 @@ fn the_expert_activation_matches_an_f64_reference_including_extremes() {
Err(sys::KernelError::LengthMismatch) Err(sys::KernelError::LengthMismatch)
); );
} }
#[test]
fn the_vector_half_to_float_conversion_is_exact_for_every_bit_pattern() {
if !sys::avx2_available() {
return;
}
// every half, padded so the vector body and the scalar tail both run
let all: Vec<u16> = (0..=u16::MAX).collect();
for len in [65_536usize, 65_531, 7, 8, 9, 0] {
let src = &all[..len];
let (mut a, mut b) = (vec![0f32; len], vec![0f32; len]);
sys::f16_to_f32_slice_scalar(src, &mut a).unwrap();
sys::f16_to_f32_slice_avx2(src, &mut b).unwrap();
for (i, (x, y)) in a.iter().zip(&b).enumerate() {
// NaN payloads are not part of the contract
assert!(
x.to_bits() == y.to_bits() || (x.is_nan() && y.is_nan()),
"half {i:#06x}: {x} vs {y}"
);
}
}
assert_eq!(
sys::f16_to_f32_slice_avx2(&[0u16; 3], &mut [0f32; 2]),
Err(sys::KernelError::LengthMismatch)
);
}
@@ -99,6 +99,7 @@ fn main() {
openvino_root: args[1].clone().into(), openvino_root: args[1].clone().into(),
device: args[3].clone(), device: args[3].clone(),
model: path.to_path_buf(), model: path.to_path_buf(),
cache_dir: None,
}; };
let mut accel = NpuPrefill::start(&config, batch).expect("start the NPU service"); let mut accel = NpuPrefill::start(&config, batch).expect("start the NPU service");
println!("# paired prefill A/B (warm)"); println!("# paired prefill A/B (warm)");
@@ -54,6 +54,7 @@ fn main() {
openvino_root: args[1].clone().into(), openvino_root: args[1].clone().into(),
device: args[3].clone(), device: args[3].clone(),
model: path.to_path_buf(), model: path.to_path_buf(),
cache_dir: None,
}; };
let mut accel = NpuPrefill::start(&config, batch).expect("start the NPU service"); let mut accel = NpuPrefill::start(&config, batch).expect("start the NPU service");
let hidden = accel let hidden = accel
@@ -69,6 +69,7 @@ fn main() {
openvino_root: PathBuf::from(&a[1]), openvino_root: PathBuf::from(&a[1]),
device: a[3].clone(), device: a[3].clone(),
model: path.to_path_buf(), model: path.to_path_buf(),
cache_dir: None,
}; };
let mut accel = NpuPrefill::start(&config, batch).expect("start the NPU service"); let mut accel = NpuPrefill::start(&config, batch).expect("start the NPU service");
if let Ok(shadow_device) = std::env::var("LELEKA_SHADOW_DEVICE") { if let Ok(shadow_device) = std::env::var("LELEKA_SHADOW_DEVICE") {
@@ -90,6 +90,7 @@ fn main() {
openvino_root: PathBuf::from(&a[1]), openvino_root: PathBuf::from(&a[1]),
device: device.to_owned(), device: device.to_owned(),
model: path.to_path_buf(), model: path.to_path_buf(),
cache_dir: None,
}; };
let mut client = Client::start(&config, 64).unwrap(); let mut client = Client::start(&config, 64).unwrap();
client.put(client.layout.input_a, &halves).unwrap(); client.put(client.layout.input_a, &halves).unwrap();
+131 -11
View File
@@ -16,6 +16,8 @@ pub struct ServiceConfig {
/// `NPU` normally; `CPU` or `GPU` to test without one. /// `NPU` normally; `CPU` or `GPU` to test without one.
pub device: String, pub device: String,
pub model: PathBuf, pub model: PathBuf,
/// Where the service keeps compiled graphs (default: a folder under the temporary directory).
pub cache_dir: Option<PathBuf>,
} }
/// A byte range of the shared region. /// A byte range of the shared region.
@@ -25,32 +27,67 @@ pub struct Region {
pub bytes: usize, pub bytes: usize,
} }
/// The regions the prefill uses, each big enough for `max_rows` rows of the widest matrix (4096 columns). /// The regions the prefill uses: those of the attention path are big enough for `max_rows` rows of the widest
/// matrix (4096 columns); the five of the expert path hold one row per (token, expert) entry.
#[derive(Clone, Copy, Debug)] #[derive(Clone, Copy, Debug)]
pub struct Layout { pub struct Layout {
pub input_a: Region, pub input_a: Region,
pub input_b: Region, pub input_b: Region,
pub out: [Region; 4], pub out: [Region; 4],
/// Gathered activations, gate and up results, the activated values, down results (`max_entries` rows each).
pub expert: [Region; 5],
pub total: usize, pub total: usize,
} }
impl Layout { impl Layout {
pub fn new(max_rows: usize) -> Self { pub fn new(max_rows: usize, max_entries: usize) -> Self {
// room after the widest result for the per-column scale shifts (one byte per column) // room after the widest result for the per-column scale shifts (one byte per column) and the gaps
// between consecutive products of a batch
let bytes = max_rows * 4096 * 2 + 4096; let bytes = max_rows * 4096 * 2 + 4096;
// the expert path is 2880 columns wide in gpt-oss; 3072 is the most it is given room for
let entry_bytes = max_entries * 3072 * 2 + 64 * 1024;
let at = |i: usize| Region { let at = |i: usize| Region {
offset: i * bytes, offset: i * bytes,
bytes, bytes,
}; };
let expert_at = |i: usize| Region {
offset: 6 * bytes + i * entry_bytes,
bytes: entry_bytes,
};
Self { Self {
input_a: at(0), input_a: at(0),
input_b: at(1), input_b: at(1),
out: [at(2), at(3), at(4), at(5)], out: [at(2), at(3), at(4), at(5)],
total: 6 * bytes, expert: [
expert_at(0),
expert_at(1),
expert_at(2),
expert_at(3),
expert_at(4),
],
total: 6 * bytes + 5 * entry_bytes,
} }
} }
} }
/// One product of a batch: `rows` rows from the byte offset `input` times the tensor, `cols` result columns
/// written at the byte offset `out`.
#[derive(Clone, Debug)]
pub struct Spec {
pub name: String,
pub expert: Option<usize>,
pub rows: usize,
pub cols: usize,
pub input: usize,
pub out: usize,
}
/// Bytes a product's result occupies, including the room for its column shifts, so that consecutive products
/// of a batch can be laid out one after the other.
pub fn out_stride(rows: usize, cols: usize) -> usize {
(rows * cols * 2 + cols).next_multiple_of(64)
}
pub struct Client { pub struct Client {
child: Child, child: Child,
stdin: ChildStdin, stdin: ChildStdin,
@@ -63,7 +100,7 @@ pub struct Client {
impl Client { impl Client {
pub fn start(config: &ServiceConfig, max_rows: usize) -> Result<Self, String> { pub fn start(config: &ServiceConfig, max_rows: usize) -> Result<Self, String> {
let layout = Layout::new(max_rows); let layout = Layout::new(max_rows, max_rows * 4);
let path = let path =
std::env::temp_dir().join(format!("leleka-npu-{}-{}.shm", std::process::id(), nanos())); std::env::temp_dir().join(format!("leleka-npu-{}-{}.shm", std::process::id(), nanos()));
let shm = Shared::create(&path, layout.total) let shm = Shared::create(&path, layout.total)
@@ -97,6 +134,13 @@ impl Client {
.arg("--shm") .arg("--shm")
.arg(&path) .arg(&path)
.args(["--device", &config.device]) .args(["--device", &config.device])
.arg("--cache-dir")
.arg(
config
.cache_dir
.clone()
.unwrap_or_else(|| std::env::temp_dir().join("leleka-npu-cache")),
)
.stdin(Stdio::piped()) .stdin(Stdio::piped())
.stdout(Stdio::piped()) .stdout(Stdio::piped())
.stderr(Stdio::inherit()) .stderr(Stdio::inherit())
@@ -177,6 +221,72 @@ impl Client {
.collect()) .collect())
} }
/// Write half floats (as bits) at a byte offset of the shared region.
pub fn put_at(&self, offset: usize, halves: &[u16]) -> Result<(), String> {
let bytes: Vec<u8> = halves.iter().flat_map(|h| h.to_le_bytes()).collect();
self.shm.write(offset, &bytes).map_err(|e| e.to_string())
}
/// Read `count` half floats (as bits) from a byte offset of the shared region.
pub fn get_at(&self, offset: usize, count: usize) -> Result<Vec<u16>, String> {
let mut bytes = vec![0u8; count * 2];
self.shm
.read(offset, &mut bytes)
.map_err(|e| e.to_string())?;
Ok(bytes
.as_chunks::<2>()
.0
.iter()
.map(|b| u16::from_le_bytes(*b))
.collect())
}
/// Run several products in one round trip, so the service knows each one's successor and prepares its
/// weights while the device runs the current one. Returns, per product, the column shifts when the
/// service had to boost the weight's scales (see [`Client::product`]).
pub fn products(&mut self, specs: &[Spec]) -> Result<Vec<Option<Vec<u8>>>, String> {
let mut text = format!("BATCH {}\n", specs.len());
for s in specs {
let e = s.expert.map_or("-".to_owned(), |e| e.to_string());
text.push_str(&format!(
"MM {} {e} {} {} {}\n",
s.name, s.rows, s.input, s.out
));
}
self.stdin
.write_all(text.as_bytes())
.and_then(|()| self.stdin.flush())
.map_err(|e| format!("the NPU service is gone: {e}"))?;
let mut shifts = Vec::with_capacity(specs.len());
let mut failure = None;
for s in specs {
let mut answer = String::new();
match self.stdout.read_line(&mut answer) {
Ok(0) | Err(_) => return Err("the NPU service closed its output".into()),
Ok(_) => {}
}
let mut fields = answer.split_whitespace();
if fields.next() != Some("OK") {
failure.get_or_insert_with(|| format!("{}: {}", s.name, answer.trim_end()));
shifts.push(None);
continue;
}
if fields.nth(2) != Some("1") {
shifts.push(None);
continue;
}
let mut bytes = vec![0u8; s.cols];
self.shm
.read(s.out + s.rows * s.cols * 2, &mut bytes)
.map_err(|e| e.to_string())?;
shifts.push(Some(bytes));
}
match failure {
Some(f) => Err(f),
None => Ok(shifts),
}
}
/// `out = input . W^T` for the tensor `name` (one `expert` of a stacked tensor; `cols` is the width of the /// `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 /// 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. /// (divide column `c` of the result by `2^shifts[c]`), `None` otherwise.
@@ -229,16 +339,25 @@ mod tests {
use super::*; use super::*;
#[test] #[test]
fn regions_do_not_overlap_and_fit_the_widest_matrix() { fn regions_do_not_overlap_and_fit_their_widest_use() {
let l = Layout::new(1024); let l = Layout::new(1024, 4096);
let all = [l.input_a, l.input_b, l.out[0], l.out[1], l.out[2], l.out[3]]; let mut all = vec![l.input_a, l.input_b, l.out[0], l.out[1], l.out[2], l.out[3]];
all.extend(l.expert);
for (i, a) in all.iter().enumerate() { for (i, a) in all.iter().enumerate() {
assert_eq!(a.bytes, 1024 * 4096 * 2 + 4096);
for b in &all[i + 1..] { for b in &all[i + 1..] {
assert!(a.offset + a.bytes <= b.offset); assert!(a.offset + a.bytes <= b.offset, "{a:?} overlaps {b:?}");
} }
} }
assert_eq!(l.total, 6 * (1024 * 4096 * 2 + 4096)); assert!(all.iter().all(|r| r.offset + r.bytes <= l.total));
assert!(l.out.iter().all(|r| r.bytes >= 1024 * 4096 * 2 + 4096));
// the gate and up results of a whole batch (4 entries per token, 2880 columns) fit one expert region
assert!(l.expert[1].bytes >= out_stride(4096, 2880));
}
#[test]
fn strides_leave_room_for_the_column_shifts() {
assert!(out_stride(3, 100) >= 3 * 100 * 2 + 100);
assert_eq!(out_stride(3, 100) % 64, 0);
} }
#[test] #[test]
@@ -248,6 +367,7 @@ mod tests {
openvino_root: PathBuf::from("nowhere"), openvino_root: PathBuf::from("nowhere"),
device: "CPU".into(), device: "CPU".into(),
model: PathBuf::from("none.gguf"), model: PathBuf::from("none.gguf"),
cache_dir: None,
}; };
assert!(Client::start(&config, 32).is_err()); assert!(Client::start(&config, 32).is_err());
} }
+252 -92
View File
@@ -14,16 +14,16 @@ pub mod client;
mod half; mod half;
mod par; mod par;
use client::{Client, Layout, Region, ServiceConfig}; use client::{Client, Layout, Region, ServiceConfig, Spec};
use leleka_cpu_kernels::Dispatch; use leleka_cpu_kernels::Dispatch;
use leleka_gptoss::{ use leleka_gptoss::{
LayerView, Model, ModelError, PrefillAccelerator, SWIGLU_ALPHA, SWIGLU_LIMIT, State, ops, LayerView, Model, ModelError, PrefillAccelerator, SWIGLU_ALPHA, SWIGLU_LIMIT, State, ops,
}; };
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
/// Rows per batch of prompt tokens (the largest bucket of the service). /// Rows per batch of prompt tokens unless changed (the service has graphs for up to 4096 rows).
pub const DEFAULT_BATCH: usize = 512; pub const DEFAULT_BATCH: usize = 2048;
const MAX_ROWS: usize = 1024; const MAX_ROWS: usize = 4096;
/// Where the time of the last prefill went. /// Where the time of the last prefill went.
#[derive(Clone, Debug, Default)] #[derive(Clone, Debug, Default)]
@@ -34,35 +34,63 @@ pub struct Timings {
pub attention: Duration, pub attention: Duration,
/// The rest of the CPU work (norms, RoPE, router, activation, conversions). /// The rest of the CPU work (norms, RoPE, router, activation, conversions).
pub other: Duration, pub other: Duration,
/// `other` by step: norm and upload, projections to caches, attention upload, residual and router,
/// residual add, expert gather, expert activation, expert combine.
pub parts: [Duration; 8],
pub total: Duration, pub total: Duration,
} }
impl Timings { impl Timings {
fn part(&mut self, i: usize, d: Duration) {
self.other += d;
self.parts[i] += d;
}
pub fn report(&self) -> String { pub fn report(&self) -> String {
let s = |d: Duration| d.as_secs_f64(); let s = |d: Duration| d.as_secs_f64();
format!( format!(
"{} tokens in {:.2} s: npu {:.2} | cpu attention {:.2} | cpu other {:.2}", "{} tokens in {:.2} s: npu {:.2} | cpu attention {:.2} | cpu other {:.2} (norm+upload {:.2}, qkv to caches {:.2}, attention upload {:.2}, residual+router {:.2}, residual add {:.2}, expert gather {:.2}, expert activation {:.2}, expert combine {:.2})",
self.tokens, self.tokens,
s(self.total), s(self.total),
s(self.npu), s(self.npu),
s(self.attention), s(self.attention),
s(self.other) s(self.other),
s(self.parts[0]),
s(self.parts[1]),
s(self.parts[2]),
s(self.parts[3]),
s(self.parts[4]),
s(self.parts[5]),
s(self.parts[6]),
s(self.parts[7])
) )
} }
} }
/// Reports the memory that can be used without paging (the OS's "available" figure).
pub type MemoryProbe = Box<dyn Fn() -> Option<u64> + Send>;
pub struct NpuPrefill { pub struct NpuPrefill {
client: Client, client: Client,
batch: usize, batch: usize,
timings: Timings, timings: Timings,
/// A second service on another device whose results every product is compared with (debugging). /// A second service on another device whose results every product is compared with (debugging).
shadow: Option<Client>, shadow: Option<Client>,
memory_probe: Option<MemoryProbe>,
/// Round the activations through the CPU decoder's Q8_0 quantisation before the device sees them. /// Round the activations through the CPU decoder's Q8_0 quantisation before the device sees them.
quantize_activations: bool, quantize_activations: bool,
dispatch: Dispatch,
/// Scale shifts reported for the last product written to a region (by offset), applied when it is read. /// 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>>, shifts: std::collections::HashMap<usize, Vec<u8>>,
} }
/// A run of consecutive entries that all go to one expert (at most `MAX_ROWS` of them).
struct Chunk {
ex: usize,
start: usize,
rows: usize,
}
fn fail(e: impl std::fmt::Display) -> ModelError { fn fail(e: impl std::fmt::Display) -> ModelError {
ModelError::Invalid(format!("NPU prefill: {e}")) ModelError::Invalid(format!("NPU prefill: {e}"))
} }
@@ -71,13 +99,15 @@ impl NpuPrefill {
/// Start the service process and wait until its device is ready. /// Start the service process and wait until its device is ready.
pub fn start(config: &ServiceConfig, batch: usize) -> Result<Self, String> { pub fn start(config: &ServiceConfig, batch: usize) -> Result<Self, String> {
let batch = batch.clamp(1, MAX_ROWS); let batch = batch.clamp(1, MAX_ROWS);
let client = Client::start(config, MAX_ROWS)?; let client = Client::start(config, batch)?;
Ok(Self { Ok(Self {
client, client,
batch, batch,
timings: Timings::default(), timings: Timings::default(),
shadow: None, shadow: None,
memory_probe: None,
quantize_activations: false, quantize_activations: false,
dispatch: Dispatch::best(),
shifts: std::collections::HashMap::new(), shifts: std::collections::HashMap::new(),
}) })
} }
@@ -85,7 +115,7 @@ impl NpuPrefill {
/// Compare every product with the same product on a second service (another device) and report the /// Compare every product with the same product on a second service (another device) and report the
/// ones that differ (debugging). /// ones that differ (debugging).
pub fn with_shadow(mut self, config: &ServiceConfig) -> Result<Self, String> { pub fn with_shadow(mut self, config: &ServiceConfig) -> Result<Self, String> {
self.shadow = Some(Client::start(config, MAX_ROWS)?); self.shadow = Some(Client::start(config, self.batch)?);
Ok(self) Ok(self)
} }
@@ -97,6 +127,28 @@ impl NpuPrefill {
self self
} }
/// Admit an NPU prefill only while `probe` reports enough free memory for it (see
/// [`NpuPrefill::estimate_bytes`]); otherwise the request is left to the CPU path.
pub fn with_memory_probe(mut self, probe: MemoryProbe) -> Self {
self.memory_probe = Some(probe);
self
}
/// A conservative estimate of the memory a prefill of `tokens` tokens adds (the model's pages are shared
/// with the service and already counted): the shared region, the expert-path float arrays of one batch (gate,
/// up, activation, down, gathered inputs), the hidden states and caches of the whole prompt, the service's
/// slots, and 512 MiB of headroom.
pub fn estimate_bytes(&self, model: &Model, tokens: usize) -> u64 {
let c = &model.config;
let batch = self.batch.min(tokens);
let entries = batch * c.n_expert_used;
let arrays = 5 * entries * c.n_ff.max(c.n_embd) * 4;
let hidden = tokens * c.n_embd * 4;
let caches = 2 * tokens * c.kv_width() * 2;
let slots = 256 << 20;
(self.client.layout.total + arrays + hidden + caches + slots + (512 << 20)) as u64
}
pub fn device_name(&self) -> &str { pub fn device_name(&self) -> &str {
self.client.device_name() self.client.device_name()
} }
@@ -121,10 +173,13 @@ impl NpuPrefill {
/// `rows` half floats from `region` as floats. /// `rows` half floats from `region` as floats.
fn fetch(&self, region: Region, rows: usize, width: usize) -> Result<Vec<f32>, ModelError> { 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 halves = self.client.get(region, rows * width).map_err(fail)?;
let dispatch = self.dispatch;
let mut out = vec![0.0f32; rows * width]; let mut out = vec![0.0f32; rows * width];
par::for_chunks(&mut out, width * 16, |i, chunk| { par::for_chunks(&mut out, width * 16, |i, chunk| {
let start = i * width * 16; let start = i * width * 16;
half::to_f32(&halves[start..start + chunk.len()], chunk); dispatch
.f16_to_f32(&halves[start..start + chunk.len()], chunk)
.expect("equal lengths");
}); });
if let Some(shifts) = self.shifts.get(&region.offset) { if let Some(shifts) = self.shifts.get(&region.offset) {
scale_columns(&mut out, width, shifts); scale_columns(&mut out, width, shifts);
@@ -224,13 +279,19 @@ impl NpuPrefill {
capacity: state.capacity(), capacity: state.capacity(),
}); });
} }
for width in [e, qw, ff] { for (width, limit) in [(e, 3072), (ff, 3072), (qw, 4096)] {
if width % 32 != 0 || width > 4096 { if width % 32 != 0 || width > limit {
return Err(ModelError::Unsupported(format!( return Err(ModelError::Unsupported(format!(
"the NPU prefill handles layer widths up to 4096 in blocks of 32, not {width}" "the NPU prefill handles layer widths in blocks of 32 up to {limit} here, not {width}"
))); )));
} }
} }
if c.n_expert_used * self.batch > 4 * self.batch {
return Err(ModelError::Unsupported(format!(
"the shared region has room for 4 experts per token, the model uses {}",
c.n_expert_used
)));
}
let layout: Layout = self.client.layout; let layout: Layout = self.client.layout;
let dispatch = *model.dispatch(); let dispatch = *model.dispatch();
let group = c.n_head / c.n_head_kv; let group = c.n_head / c.n_head_kv;
@@ -273,7 +334,7 @@ impl NpuPrefill {
) )
}); });
self.put_floats(&dispatch, layout.input_a, &h)?; self.put_floats(&dispatch, layout.input_a, &h)?;
self.timings.other += t0.elapsed(); self.timings.part(0, t0.elapsed());
self.product( self.product(
&name("attn_q"), &name("attn_q"),
None, None,
@@ -333,7 +394,7 @@ impl NpuPrefill {
.expect("equal lengths"); .expect("equal lengths");
}); });
} }
self.timings.other += t1.elapsed(); self.timings.part(1, t1.elapsed());
// --- attention over the cache --- // --- attention over the cache ---
let t2 = Instant::now(); let t2 = Instant::now();
@@ -385,7 +446,7 @@ impl NpuPrefill {
// --- output projection and residual --- // --- output projection and residual ---
let t3 = Instant::now(); let t3 = Instant::now();
self.put_floats(&dispatch, layout.input_a, &attn)?; self.put_floats(&dispatch, layout.input_a, &attn)?;
self.timings.other += t3.elapsed(); self.timings.part(2, t3.elapsed());
self.product( self.product(
&name("attn_output"), &name("attn_output"),
None, None,
@@ -439,22 +500,17 @@ impl NpuPrefill {
per_expert[*ex].push((t, *weight)); per_expert[*ex].push((t, *weight));
} }
} }
self.timings.other += t4.elapsed(); self.timings.part(3, t4.elapsed());
// --- experts --- // --- experts ---
let mut moe = vec![0.0f32; m * e]; let moe = self.experts(&dispatch, &view, l, &per_expert, &h2f, m, (e, ff))?;
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(); let t5 = Instant::now();
par::for_chunks(&mut xs[b0 * e..(b0 + m) * e], e, |t, row| { 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]) { for (x, d) in row.iter_mut().zip(&moe[t * e..(t + 1) * e]) {
*x += d; *x += d;
} }
}); });
self.timings.other += t5.elapsed(); self.timings.part(4, t5.elapsed());
} }
state.store_kv(l, pos0, &kc[pos0 * kw..], &vc[pos0 * kw..]); state.store_kv(l, pos0, &kc[pos0 * kw..], &vc[pos0 * kw..]);
@@ -471,62 +527,103 @@ impl NpuPrefill {
})) }))
} }
/// One expert over up to `MAX_ROWS` of the batch's tokens: gate and up, the activation, down, and the /// All experts of one batch at once. The entries (token, expert pairs) are sorted by expert and gathered into
/// weighted add into `moe`. /// one array in the shared region; the gate and up products of every expert go to the service as one batch,
/// the activation runs on all cores, then the down products go as another batch. Because the service sees the
/// whole list it prepares each product's weights while the device runs the one before it. Returns the
/// weighted expert outputs per token (`m * e`).
#[allow(clippy::too_many_arguments)] // the pieces of one layer step, passed explicitly #[allow(clippy::too_many_arguments)] // the pieces of one layer step, passed explicitly
fn expert( fn experts(
&mut self, &mut self,
dispatch: &Dispatch, dispatch: &Dispatch,
view: &LayerView<'_>, view: &LayerView<'_>,
name: &dyn Fn(&str) -> String, layer: usize,
ex: usize, per_expert: &[Vec<(usize, f32)>],
rows: &[(usize, f32)],
h2f: &[u16], h2f: &[u16],
e: usize, m: usize,
ff: usize, (e, ff): (usize, usize),
moe: &mut [f32], ) -> Result<Vec<f32>, ModelError> {
) -> Result<(), ModelError> {
let layout = self.client.layout; let layout = self.client.layout;
let t0 = Instant::now(); let t0 = Instant::now();
let r = rows.len(); let name = |part: &str| format!("blk.{layer}.{part}.weight");
let mut gathered = vec![0u16; r * e]; let mut chunks: Vec<Chunk> = Vec::new();
for (i, (t, _)) in rows.iter().enumerate() { let mut entry_token: Vec<usize> = Vec::new();
gathered[i * e..(i + 1) * e].copy_from_slice(&h2f[t * e..(t + 1) * e]); let mut entry_expert: Vec<usize> = Vec::new();
} let mut token_entries: Vec<Vec<(usize, f32)>> = vec![Vec::new(); m];
self.client.put(layout.input_a, &gathered).map_err(fail)?; for (ex, list) in per_expert.iter().enumerate() {
self.timings.other += t0.elapsed(); for rows in list.chunks(MAX_ROWS) {
self.product( chunks.push(Chunk {
&name("ffn_gate_exps"), ex,
Some(ex), start: entry_token.len(),
r, rows: rows.len(),
(e, ff), });
layout.input_a, for (t, w) in rows {
layout.out[0], token_entries[*t].push((entry_token.len(), *w));
)?; entry_token.push(*t);
self.product( entry_expert.push(ex);
&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;
} }
} }
let total = entry_token.len();
let mut gathered = vec![0u16; total * e];
par::for_chunks(&mut gathered, e, |i, row| {
let t = entry_token[i];
row.copy_from_slice(&h2f[t * e..(t + 1) * e]);
});
self.client
.put_at(layout.expert[0].offset, &gathered)
.map_err(fail)?;
// result offsets: one product after the other inside each region
let offsets = |region: usize, cols: usize| -> Vec<usize> {
let mut at = layout.expert[region].offset;
chunks
.iter()
.map(|c| {
let here = at;
at += client::out_stride(c.rows, cols);
here
})
.collect()
};
let (gate_at, up_at, down_at) = (offsets(1, ff), offsets(2, ff), offsets(4, e));
let mut specs = Vec::with_capacity(chunks.len() * 2);
for (c, ch) in chunks.iter().enumerate() {
let input = layout.expert[0].offset + ch.start * e * 2;
for (part, out) in [("ffn_gate_exps", gate_at[c]), ("ffn_up_exps", up_at[c])] {
specs.push(Spec {
name: name(part),
expert: Some(ch.ex),
rows: ch.rows,
cols: ff,
input,
out,
});
}
}
self.timings.part(5, t0.elapsed());
let t1 = Instant::now();
let shifts = self.client.products(&specs).map_err(fail)?;
self.timings.npu += t1.elapsed();
let t2 = Instant::now();
let gate_shifts: Vec<_> = shifts.iter().step_by(2).collect();
let up_shifts: Vec<_> = shifts.iter().skip(1).step_by(2).collect();
let mut gate = self.read_results(&chunks, &gate_at, ff, &gate_shifts)?;
let mut up = self.read_results(&chunks, &up_at, ff, &up_shifts)?;
par::for_chunks(&mut gate, ff, |i, row| {
let b = &view.gate_b[entry_expert[i] * ff..(entry_expert[i] + 1) * ff];
for (x, b) in row.iter_mut().zip(b) {
*x += b;
}
});
par::for_chunks(&mut up, ff, |i, row| {
let b = &view.up_b[entry_expert[i] * ff..(entry_expert[i] + 1) * ff];
for (x, b) in row.iter_mut().zip(b) {
*x += b;
}
});
let mut act = vec![0.0f32; total * ff];
let rows_per = 16;
par::for_chunks(&mut act, ff * rows_per, |i, out| { par::for_chunks(&mut act, ff * rows_per, |i, out| {
let first = i * rows_per; let first = i * rows_per;
let count = out.len() / ff; let count = out.len() / ff;
@@ -540,30 +637,74 @@ impl NpuPrefill {
) )
.expect("activation kernel"); .expect("activation kernel");
}); });
self.put_floats(dispatch, layout.input_b, &act)?; let halves = halves_of(dispatch, &act, self.quantize_activations);
self.timings.other += t1.elapsed(); self.client
self.product( .put_at(layout.expert[3].offset, &halves)
&name("ffn_down_exps"), .map_err(fail)?;
Some(ex), let down_specs: Vec<Spec> = chunks
r, .iter()
(ff, e), .enumerate()
layout.input_b, .map(|(c, ch)| Spec {
layout.out[3], name: name("ffn_down_exps"),
)?; expert: Some(ch.ex),
let t2 = Instant::now(); rows: ch.rows,
let down = self.fetch(layout.out[3], r, e)?; cols: e,
let down_b = &view.down_b[ex * e..(ex + 1) * e]; input: layout.expert[3].offset + ch.start * ff * 2,
for (i, (t, weight)) in rows.iter().enumerate() { out: down_at[c],
for ((m, d), b) in moe[t * e..(t + 1) * e] })
.iter_mut() .collect();
.zip(&down[i * e..(i + 1) * e]) self.timings.part(6, t2.elapsed());
.zip(down_b) let t3 = Instant::now();
{ let down_shifts = self.client.products(&down_specs).map_err(fail)?;
*m += weight * (d + b); self.timings.npu += t3.elapsed();
let t4 = Instant::now();
let down_refs: Vec<_> = down_shifts.iter().collect();
let down = self.read_results(&chunks, &down_at, e, &down_refs)?;
let mut moe = vec![0.0f32; m * e];
par::for_chunks(&mut moe, e, |t, row| {
for (idx, weight) in &token_entries[t] {
let ex = entry_expert[*idx];
let d = &down[idx * e..(idx + 1) * e];
let bias = &view.down_b[ex * e..(ex + 1) * e];
for ((m, d), b) in row.iter_mut().zip(d).zip(bias) {
*m += weight * (d + b);
}
}
});
self.timings.part(7, t4.elapsed());
Ok(moe)
}
/// The results of a batch laid out chunk after chunk at `offsets`, as one `[entries][width]` array of floats
/// with the scale shifts (if any) divided out.
fn read_results(
&self,
chunks: &[Chunk],
offsets: &[usize],
width: usize,
shifts: &[&Option<Vec<u8>>],
) -> Result<Vec<f32>, ModelError> {
let dispatch = self.dispatch;
let total: usize = chunks.iter().map(|c| c.rows).sum();
let mut out = vec![0.0f32; total * width];
for (c, ch) in chunks.iter().enumerate() {
let halves = self
.client
.get_at(offsets[c], ch.rows * width)
.map_err(fail)?;
let dst = &mut out[ch.start * width..(ch.start + ch.rows) * width];
let block = width * 16;
par::for_chunks(dst, block, |i, chunk| {
dispatch
.f16_to_f32(&halves[i * block..i * block + chunk.len()], chunk)
.expect("equal lengths");
});
if let Some(s) = shifts[c] {
scale_columns(dst, width, s);
} }
} }
self.timings.other += t2.elapsed(); Ok(out)
Ok(())
} }
} }
@@ -578,6 +719,25 @@ impl PrefillAccelerator for NpuPrefill {
) -> Result<Option<Vec<f32>>, ModelError> { ) -> Result<Option<Vec<f32>>, ModelError> {
self.run(model, state, tokens, pos0, progress, false) self.run(model, state, tokens, pos0, progress, false)
} }
fn admit(&mut self, model: &Model, tokens: usize) -> bool {
let Some(probe) = self.memory_probe.as_ref() else {
return true;
};
let Some(available) = probe() else {
return true;
};
let needed = self.estimate_bytes(model, tokens);
let admitted = available >= needed;
if !admitted {
eprintln!(
"leleka-gptoss-npu: NPU prefill of {tokens} tokens needs about {} MiB and {} MiB are available; using the CPU for this prompt",
needed >> 20,
available >> 20
);
}
admitted
}
} }
/// Divide column `c` of the `width`-wide rows in `values` by `2^shifts[c]`. /// Divide column `c` of the `width`-wide rows in `values` by `2^shifts[c]`.
+246 -118
View File
@@ -13,7 +13,7 @@ use std::sync::Arc;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
/// Row counts the compiled graphs are specialised for; a product is padded up to the next one. /// 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]; pub const BUCKETS: [usize; 8] = [32, 64, 128, 256, 512, 1024, 2048, 4096];
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct Options { pub struct Options {
@@ -24,6 +24,8 @@ pub struct Options {
pub model: PathBuf, pub model: PathBuf,
/// The region file shared with the client; the service maps it. /// The region file shared with the client; the service maps it.
pub shm: PathBuf, pub shm: PathBuf,
/// Where OpenVINO keeps compiled graphs between runs, if anywhere.
pub cache_dir: Option<PathBuf>,
} }
/// One product to run: `y = x . W^T` for the tensor `name` (and one expert of a stacked tensor). /// One product to run: `y = x . W^T` for the tensor `name` (and one expert of a stacked tensor).
@@ -116,13 +118,24 @@ struct Slot {
shifts: Vec<u8>, shifts: Vec<u8>,
} }
/// OpenVINO objects: the compiled graphs and the request slots built on them. /// Two slots per graph shape: while the device runs the product in one, the next product's weights are
/// expanded into the other.
struct Pair {
slots: [Slot; 2],
/// The slot a weight that is not loaded anywhere is expanded into.
next: usize,
}
type Key = (usize, usize, usize);
/// OpenVINO objects: the compiled graphs and the slot pairs built on them.
struct Runtime { struct Runtime {
ov: Arc<OpenVino>, ov: Arc<OpenVino>,
core: Core, core: Core,
device: String, device: String,
graphs: HashMap<(usize, usize, usize), Compiled>, graphs: HashMap<Key, Compiled>,
slots: HashMap<(usize, usize, usize), Slot>, index: HashMap<Key, usize>,
pairs: Vec<Pair>,
} }
fn ov_error(e: leleka_openvino::Error) -> String { fn ov_error(e: leleka_openvino::Error) -> String {
@@ -130,42 +143,77 @@ fn ov_error(e: leleka_openvino::Error) -> String {
} }
impl Runtime { impl Runtime {
fn slot(&mut self, k: usize, n: usize, bucket: usize) -> Result<&mut Slot, String> { fn make_slot(&self, key: Key) -> Result<Slot, String> {
let key = (k, n, bucket); let (k, n, bucket) = key;
if !self.slots.contains_key(&key) { let g = k / GROUP;
if !self.graphs.contains_key(&key) { let mut request = self.graphs[&key].request().map_err(ov_error)?;
let (xml, bin) = graph::matmul_ir(bucket, k, n); let x =
let compiled = self Tensor::new(&self.ov, Element::F16, &[bucket as i64, k as i64]).map_err(ov_error)?;
.core let w = Tensor::new(&self.ov, Element::I8, &[n as i64, g as i64, GROUP as i64])
.compile(&self.device, &xml, &bin) .map_err(ov_error)?;
.map_err(ov_error)?; let s = Tensor::new(&self.ov, Element::F16, &[n as i64, g as i64, 1]).map_err(ov_error)?;
self.graphs.insert(key, compiled); request.set_input(0, &x).map_err(ov_error)?;
} request.set_input(1, &w).map_err(ov_error)?;
let g = k / GROUP; request.set_input(2, &s).map_err(ov_error)?;
let mut request = self.graphs[&key].request().map_err(ov_error)?; Ok(Slot {
let x = Tensor::new(&self.ov, Element::F16, &[bucket as i64, k as i64]) request,
.map_err(ov_error)?; x,
let w = Tensor::new(&self.ov, Element::I8, &[n as i64, g as i64, GROUP as i64]) w,
.map_err(ov_error)?; s,
let s = loaded: None,
Tensor::new(&self.ov, Element::F16, &[n as i64, g as i64, 1]).map_err(ov_error)?; shifts: Vec::new(),
request.set_input(0, &x).map_err(ov_error)?; })
request.set_input(1, &w).map_err(ov_error)?;
request.set_input(2, &s).map_err(ov_error)?;
self.slots.insert(
key,
Slot {
request,
x,
w,
s,
loaded: None,
shifts: Vec::new(),
},
);
}
Ok(self.slots.get_mut(&key).expect("inserted above"))
} }
/// The index of the slot pair for a shape, compiling the graph on first use.
fn pair(&mut self, key: Key) -> Result<usize, String> {
if let Some(i) = self.index.get(&key) {
return Ok(*i);
}
if !self.graphs.contains_key(&key) {
let (xml, bin) = graph::matmul_ir(key.2, key.0, key.1);
let compiled = self
.core
.compile(&self.device, &xml, &bin)
.map_err(ov_error)?;
self.graphs.insert(key, compiled);
}
let pair = Pair {
slots: [self.make_slot(key)?, self.make_slot(key)?],
next: 0,
};
self.pairs.push(pair);
self.index.insert(key, self.pairs.len() - 1);
Ok(self.pairs.len() - 1)
}
}
/// Two distinct elements of a slice, mutably.
fn two_mut<T>(items: &mut [T], i: usize, j: usize) -> (&mut T, &mut T) {
assert_ne!(i, j);
if i < j {
let (a, b) = items.split_at_mut(j);
(&mut a[i], &mut b[0])
} else {
let (a, b) = items.split_at_mut(i);
(&mut b[0], &mut a[j])
}
}
/// Expand `matrix` into the slot's weight and scale tensors and record what it holds.
fn load(slot: &mut Slot, matrix: &Matrix<'_>, id: (String, Option<usize>)) -> Result<(), String> {
expand::expand_parallel(
matrix.format,
matrix.bytes,
slot.w.bytes_mut().map_err(ov_error)?,
slot.s.bytes_mut().map_err(ov_error)?,
);
slot.shifts = expand::normalize_scales(slot.s.bytes_mut().map_err(ov_error)?, matrix.n);
if slot.shifts.iter().all(|s| *s == 0) {
slot.shifts.clear();
}
slot.loaded = Some(id);
Ok(())
} }
pub struct Engine { pub struct Engine {
@@ -181,10 +229,42 @@ fn io_error(what: &str, e: impl std::fmt::Display) -> String {
format!("{what}: {e}") format!("{what}: {e}")
} }
/// What a product needs resolved before it can run.
struct Plan<'a> {
bucket: usize,
matrix: Matrix<'a>,
key: Key,
id: (String, Option<usize>),
}
fn plan<'a>(weights: &'a Weights, p: &Product) -> Result<Plan<'a>, String> {
if p.rows == 0 {
return Err("a product needs at least one row".into());
}
let bucket = Engine::bucket_for(p.rows).ok_or_else(|| {
format!(
"{} rows exceed the largest bucket {}",
p.rows,
BUCKETS[BUCKETS.len() - 1]
)
})?;
let matrix = weights.matrix(&p.name, p.expert)?;
let key = (matrix.k, matrix.n, bucket);
Ok(Plan {
bucket,
matrix,
key,
id: (p.name.clone(), p.expert),
})
}
impl Engine { impl Engine {
pub fn new(options: &Options) -> Result<Self, String> { pub fn new(options: &Options) -> Result<Self, String> {
let ov = OpenVino::load(&options.openvino_dll).map_err(ov_error)?; let ov = OpenVino::load(&options.openvino_dll).map_err(ov_error)?;
let core = Core::new(&ov).map_err(ov_error)?; let mut core = Core::new(&ov).map_err(ov_error)?;
if let Some(dir) = &options.cache_dir {
core = core.with_cache_dir(dir).map_err(ov_error)?;
}
let devices = core.devices().map_err(ov_error)?; let devices = core.devices().map_err(ov_error)?;
if !devices.contains(&options.device) { if !devices.contains(&options.device) {
return Err(format!( return Err(format!(
@@ -211,7 +291,8 @@ impl Engine {
core, core,
device: options.device.clone(), device: options.device.clone(),
graphs: HashMap::new(), graphs: HashMap::new(),
slots: HashMap::new(), index: HashMap::new(),
pairs: Vec::new(),
}, },
weights: Weights { gguf, map }, weights: Weights { gguf, map },
shm, shm,
@@ -230,81 +311,136 @@ impl Engine {
BUCKETS.iter().copied().find(|b| *b >= rows) BUCKETS.iter().copied().find(|b| *b >= rows)
} }
/// Run one product. Activations are read from and the result written to the shared region as /// Run one product (see [`Engine::run_batch`]).
/// little-endian half floats: `rows * k` in, `rows * n` out.
pub fn run(&mut self, p: &Product) -> Result<Done, String> { pub fn run(&mut self, p: &Product) -> Result<Done, String> {
self.run_batch(std::slice::from_ref(p))
.pop()
.expect("one result per product")
}
/// Run products one after another. Activations are read from and the result written to the shared region
/// as little-endian half floats: `rows * k` in, `rows * n` out (plus the scale shifts, if any, after it).
/// Knowing the next product, the weights it needs are expanded on a second thread while the device runs
/// the current one.
pub fn run_batch(&mut self, list: &[Product]) -> Vec<Result<Done, String>> {
(0..list.len()).map(|i| self.run_at(list, i)).collect()
}
fn run_at(&mut self, list: &[Product], i: usize) -> Result<Done, String> {
let started = Instant::now(); let started = Instant::now();
let mut lap = Instant::now(); let Self {
let mut tick = |total: &mut Duration| { runtime,
*total += lap.elapsed(); weights,
lap = Instant::now(); shm,
}; scratch,
if p.rows == 0 { profile,
return Err("a product needs at least one row".into()); ..
} } = self;
let bucket = Self::bucket_for(p.rows).ok_or_else(|| { let p = &list[i];
format!( let cur = plan(weights, p)?;
"{} rows exceed the largest bucket {}", let (n, k) = (cur.matrix.n, cur.matrix.k);
p.rows,
BUCKETS[BUCKETS.len() - 1]
)
})?;
let matrix = self.weights.matrix(&p.name, p.expert)?;
let (n, k) = (matrix.n, matrix.k);
let (in_bytes, out_bytes) = (p.rows * k * 2, p.rows * n * 2); let (in_bytes, out_bytes) = (p.rows * k * 2, p.rows * n * 2);
let mut buffer = std::mem::take(&mut self.scratch); let mut buffer = std::mem::take(scratch);
buffer.resize(in_bytes.max(out_bytes), 0); buffer.resize(in_bytes.max(out_bytes), 0);
self.shm let lap = Instant::now();
.read(p.in_offset, &mut buffer[..in_bytes]) shm.read(p.in_offset, &mut buffer[..in_bytes])
.map_err(|e| io_error("reading the activations", e))?; .map_err(|e| io_error("reading the activations", e))?;
tick(&mut self.profile.read_in); profile.read_in += lap.elapsed();
let slot = self.runtime.slot(k, n, bucket)?; // pairs for this product and the next one (compiling graphs the first time)
tick(&mut self.profile.compile); let lap = Instant::now();
let id = (p.name.clone(), p.expert); let ci = runtime.pair(cur.key)?;
if slot.loaded.as_ref() != Some(&id) { let next = list.get(i + 1).and_then(|np| plan(weights, np).ok());
expand::expand_parallel( let ni = match &next {
matrix.format, Some(nx) => runtime.pair(nx.key).ok(),
matrix.bytes, None => None,
slot.w.bytes_mut().map_err(ov_error)?, };
slot.s.bytes_mut().map_err(ov_error)?, profile.compile += lap.elapsed();
);
tick(&mut self.profile.expand); // the slot for this product, expanding synchronously if nobody prefetched it
slot.shifts = expand::normalize_scales(slot.s.bytes_mut().map_err(ov_error)?, n); let lap = Instant::now();
if slot.shifts.iter().all(|s| *s == 0) { let idx = {
slot.shifts.clear(); let pair = &mut runtime.pairs[ci];
let found = (0..2).find(|s| pair.slots[*s].loaded.as_ref() == Some(&cur.id));
let idx = match found {
Some(s) => s,
None => {
let s = pair.next;
load(&mut pair.slots[s], &cur.matrix, cur.id.clone())?;
s
}
};
pair.next = 1 - idx;
idx
};
profile.expand += lap.elapsed();
// borrow the current slot and, if there is a next product to prepare, its target slot
let (slot, target): (&mut Slot, Option<(&mut Slot, &Plan<'_>)>) = match (ni, &next) {
(Some(ni), Some(nx)) if ni == ci => {
let [a, b] = &mut runtime.pairs[ci].slots;
let (cur_slot, other) = if idx == 0 { (a, b) } else { (b, a) };
let wanted = other.loaded.as_ref() != Some(&nx.id);
(cur_slot, wanted.then_some((other, nx)))
} }
slot.loaded = Some(id); (Some(ni), Some(nx)) => {
tick(&mut self.profile.normalize); let (a, b) = two_mut(&mut runtime.pairs, ci, ni);
} let hit = (0..2).find(|s| b.slots[*s].loaded.as_ref() == Some(&nx.id));
slot.x.write(0, &buffer[..in_bytes]).map_err(ov_error)?; let target = if hit.is_some() {
slot.x.bytes_mut().map_err(ov_error)?[in_bytes..].fill(0); None
tick(&mut self.profile.x_write); } else {
slot.request.infer().map_err(ov_error)?; let t = b.next;
tick(&mut self.profile.infer); b.next = 1 - t;
slot.request Some((&mut b.slots[t], nx))
.output(0) };
.map_err(ov_error)? (&mut a.slots[idx], target)
.read(0, &mut buffer[..out_bytes]) }
.map_err(ov_error)?; _ => (&mut runtime.pairs[ci].slots[idx], None),
tick(&mut self.profile.out_read); };
self.shm
.write(p.out_offset, &buffer[..out_bytes]) let lap = Instant::now();
.map_err(|e| io_error("writing the result", e))?; let outcome: Result<Done, String> = std::thread::scope(|scope| {
let shifted = !slot.shifts.is_empty(); let prefetch = target.map(|(tgt, nx)| {
if shifted { scope.spawn(move || {
self.shm // a failed prefetch leaves the slot unloaded; the product then loads it itself and
.write(p.out_offset + out_bytes, &slot.shifts) // reports the error
.map_err(|e| io_error("writing the scale shifts", e))?; let _ = load(tgt, &nx.matrix, nx.id.clone());
} })
self.scratch = buffer; });
tick(&mut self.profile.shm_write); let result = (|| {
self.profile.calls += 1; slot.x.write(0, &buffer[..in_bytes]).map_err(ov_error)?;
Ok(Done { slot.x.bytes_mut().map_err(ov_error)?[in_bytes..].fill(0);
micros: started.elapsed().as_micros() as u64, slot.request.infer().map_err(ov_error)?;
bucket, slot.request
shifted, .output(0)
.map_err(ov_error)?
.read(0, &mut buffer[..out_bytes])
.map_err(ov_error)?;
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 {
shm.write(p.out_offset + out_bytes, &slot.shifts)
.map_err(|e| io_error("writing the scale shifts", e))?;
}
Ok(Done {
micros: 0,
bucket: cur.bucket,
shifted,
})
})();
if let Some(handle) = prefetch {
let _ = handle.join();
}
result
});
profile.infer += lap.elapsed();
*scratch = buffer;
profile.calls += 1;
outcome.map(|mut done| {
done.micros = started.elapsed().as_micros() as u64;
done
}) })
} }
@@ -313,30 +449,22 @@ impl Engine {
let p = &self.profile; let p = &self.profile;
let ms = |d: Duration| d.as_secs_f64() * 1e3; let ms = |d: Duration| d.as_secs_f64() * 1e3;
format!( 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}", "{} products: read activations {:.0} ms | slots/compile {:.0} | expand weights (not prefetched) {:.0} | run on the device incl. prefetch {:.0}",
p.calls, p.calls,
ms(p.read_in), ms(p.read_in),
ms(p.compile), ms(p.compile),
ms(p.expand), ms(p.expand),
ms(p.normalize),
ms(p.x_write),
ms(p.infer), ms(p.infer),
ms(p.out_read),
ms(p.shm_write)
) )
} }
} }
/// Time spent in each phase of `Engine::run`, summed over products. /// Time spent in each phase of `Engine::run_batch`, summed over products.
#[derive(Default)] #[derive(Default)]
struct Profile { struct Profile {
calls: u64, calls: u64,
read_in: Duration, read_in: Duration,
compile: Duration, compile: Duration,
expand: Duration, expand: Duration,
normalize: Duration,
x_write: Duration,
infer: Duration, infer: Duration,
out_read: Duration,
shm_write: Duration,
} }
+37 -3
View File
@@ -11,7 +11,7 @@ use std::process::ExitCode;
fn parse_args() -> Result<Options, String> { fn parse_args() -> Result<Options, String> {
let mut args = std::env::args().skip(1); let mut args = std::env::args().skip(1);
let (mut dll, mut model, mut shm) = (None, None, None); let (mut dll, mut model, mut shm, mut cache_dir) = (None, None, None, None);
let mut device = "NPU".to_owned(); let mut device = "NPU".to_owned();
while let Some(arg) = args.next() { while let Some(arg) = args.next() {
let mut value = |name: &str| args.next().ok_or_else(|| format!("{name} needs a value")); let mut value = |name: &str| args.next().ok_or_else(|| format!("{name} needs a value"));
@@ -19,6 +19,7 @@ fn parse_args() -> Result<Options, String> {
"--openvino" => dll = Some(PathBuf::from(value("--openvino")?)), "--openvino" => dll = Some(PathBuf::from(value("--openvino")?)),
"--model" => model = Some(PathBuf::from(value("--model")?)), "--model" => model = Some(PathBuf::from(value("--model")?)),
"--shm" => shm = Some(PathBuf::from(value("--shm")?)), "--shm" => shm = Some(PathBuf::from(value("--shm")?)),
"--cache-dir" => cache_dir = Some(PathBuf::from(value("--cache-dir")?)),
"--device" => device = value("--device")?, "--device" => device = value("--device")?,
other => return Err(format!("unknown argument {other}")), other => return Err(format!("unknown argument {other}")),
} }
@@ -28,6 +29,7 @@ fn parse_args() -> Result<Options, String> {
device, device,
model: model.ok_or("--model is required")?, model: model.ok_or("--model is required")?,
shm: shm.ok_or("--shm is required")?, shm: shm.ok_or("--shm is required")?,
cache_dir,
}) })
} }
@@ -57,11 +59,43 @@ fn main() -> ExitCode {
if reply(&mut out, &protocol::ready_line(engine.device_name())).is_err() { if reply(&mut out, &protocol::ready_line(engine.device_name())).is_err() {
return ExitCode::FAILURE; return ExitCode::FAILURE;
} }
for line in std::io::stdin().lock().lines() { let stdin = std::io::stdin();
let Ok(line) = line else { break }; let mut lines = stdin.lock().lines();
while let Some(Ok(line)) = lines.next() {
let answer = match protocol::parse(&line) { let answer = match protocol::parse(&line) {
Ok(Command::Quit) => break, Ok(Command::Quit) => break,
Ok(Command::Ping) => "PONG".to_owned(), Ok(Command::Ping) => "PONG".to_owned(),
Ok(Command::Batch(count)) => {
// read all the products first so each one's successor is known
let mut products = Vec::with_capacity(count);
let mut bad = None;
for _ in 0..count {
let Some(Ok(next)) = lines.next() else {
bad = Some("the input ended inside a batch".to_owned());
break;
};
match protocol::parse(&next) {
Ok(Command::Product(p)) => products.push(p),
_ => bad = Some(format!("not a product inside a batch: {next}")),
}
}
let results = match &bad {
Some(m) => vec![Err(m.clone()); count],
None => engine.run_batch(&products),
};
let mut broken = false;
for result in results {
let line = match result {
Ok(done) => protocol::ok_line(done),
Err(m) => protocol::err_line(&m),
};
broken |= reply(&mut out, &line).is_err();
}
if broken {
break;
}
continue;
}
Ok(Command::Product(p)) => match engine.run(&p) { Ok(Command::Product(p)) => match engine.run(&p) {
Ok(done) => protocol::ok_line(done), Ok(done) => protocol::ok_line(done),
Err(m) => protocol::err_line(&m), Err(m) => protocol::err_line(&m),
+12 -1
View File
@@ -1,6 +1,7 @@
//! The line protocol between the client and the service (docs/npu-service.md). //! 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`. //! Client to service: `PING`, `MM <tensor> <expert|-> <rows> <in_offset> <out_offset>`, `BATCH <n>` followed by
//! `n` `MM` lines, `QUIT`.
//! Service to client: `READY <device name>` once at start, then `PONG`, `OK <micros> <bucket> <shifted>` 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. //! per line. Offsets are byte offsets into the shared region; activations and results are half floats.
@@ -11,6 +12,9 @@ pub enum Command {
Ping, Ping,
Product(Product), Product(Product),
Quit, Quit,
/// `BATCH <n>`: the next `n` lines are `MM` commands, run in order with the weights of each prepared
/// while the previous one runs; one reply line per product follows.
Batch(usize),
} }
pub fn parse(line: &str) -> Result<Command, String> { pub fn parse(line: &str) -> Result<Command, String> {
@@ -18,6 +22,11 @@ pub fn parse(line: &str) -> Result<Command, String> {
match fields.next() { match fields.next() {
Some("PING") => Ok(Command::Ping), Some("PING") => Ok(Command::Ping),
Some("QUIT") => Ok(Command::Quit), Some("QUIT") => Ok(Command::Quit),
Some("BATCH") => fields
.next()
.and_then(|n| n.parse().ok())
.map(Command::Batch)
.ok_or_else(|| "BATCH needs a count".to_owned()),
Some("MM") => { Some("MM") => {
let name = fields.next().ok_or("MM needs a tensor name")?.to_owned(); let name = fields.next().ok_or("MM needs a tensor name")?.to_owned();
let expert = match fields.next().ok_or("MM needs an expert or -")? { let expert = match fields.next().ok_or("MM needs an expert or -")? {
@@ -91,6 +100,8 @@ mod tests {
fn other_commands_and_errors() { fn other_commands_and_errors() {
assert_eq!(parse("PING").unwrap(), Command::Ping); assert_eq!(parse("PING").unwrap(), Command::Ping);
assert_eq!(parse("QUIT").unwrap(), Command::Quit); assert_eq!(parse("QUIT").unwrap(), Command::Quit);
assert_eq!(parse("BATCH 12").unwrap(), Command::Batch(12));
assert!(parse("BATCH x").is_err());
assert!(parse("MM x - 1 2").is_err()); assert!(parse("MM x - 1 2").is_err());
assert!(parse("MM x e 1 2 3").is_err()); assert!(parse("MM x e 1 2 3").is_err());
assert!(parse("NOPE").is_err()); assert!(parse("NOPE").is_err());
+1
View File
@@ -13,6 +13,7 @@ path = "src/main.rs"
[dependencies] [dependencies]
leleka-cpu-worker = { path = "../cpu-worker" } leleka-cpu-worker = { path = "../cpu-worker" }
leleka-gptoss-npu = { path = "../gptoss-npu" } leleka-gptoss-npu = { path = "../gptoss-npu" }
sysinfo = { version = "0.39.6", default-features = false, features = ["system"] }
[lints] [lints]
workspace = true workspace = true
+12 -1
View File
@@ -143,6 +143,7 @@ fn main() -> ExitCode {
openvino_root, openvino_root,
device: args.device.clone(), device: args.device.clone(),
model: args.model.clone(), model: args.model.clone(),
cache_dir: None,
}; };
match NpuPrefill::start(&config, args.batch) { match NpuPrefill::start(&config, args.batch) {
Ok(npu) => { Ok(npu) => {
@@ -152,7 +153,10 @@ fn main() -> ExitCode {
args.min_tokens, args.min_tokens,
args.batch args.batch
); );
engine.set_accelerator(Box::new(npu), args.min_tokens); engine.set_accelerator(
Box::new(npu.with_memory_probe(Box::new(available_memory))),
args.min_tokens,
);
} }
Err(e) => eprintln!("leleka-npu-worker: {e}; serving from the CPU only"), Err(e) => eprintln!("leleka-npu-worker: {e}; serving from the CPU only"),
} }
@@ -173,3 +177,10 @@ fn main() -> ExitCode {
} }
} }
} }
/// Memory the OS can hand out without paging (free plus reclaimable cache), in bytes.
fn available_memory() -> Option<u64> {
let mut system = sysinfo::System::new();
system.refresh_memory();
Some(system.available_memory()).filter(|bytes| *bytes > 0)
}
+28 -3
View File
@@ -284,6 +284,7 @@ impl OpenVino {
pub struct Core { pub struct Core {
ov: Arc<OpenVino>, ov: Arc<OpenVino>,
raw: *mut c_void, raw: *mut c_void,
cache_dir: Option<CString>,
} }
// SAFETY: the core is used from one thread at a time (no Sync), and moving it between threads is allowed by // SAFETY: the core is used from one thread at a time (no Sync), and moving it between threads is allowed by
@@ -298,9 +299,19 @@ impl Core {
Ok(Self { Ok(Self {
ov: ov.clone(), ov: ov.clone(),
raw, raw,
cache_dir: None,
}) })
} }
/// Keep compiled blobs in `dir` (OpenVINO's `CACHE_DIR` property): compiling the same model again, in this
/// or a later process, imports the blob instead of compiling.
pub fn with_cache_dir(mut self, dir: &std::path::Path) -> Result<Self, Error> {
std::fs::create_dir_all(dir)
.map_err(|e| Error::Invalid(format!("{}: {e}", dir.display())))?;
self.cache_dir = Some(cstring(&dir.to_string_lossy())?);
Ok(self)
}
/// Names of the devices OpenVINO can use, such as `CPU`, `GPU`, `NPU`. /// Names of the devices OpenVINO can use, such as `CPU`, `GPU`, `NPU`.
pub fn devices(&self) -> Result<Vec<String>, Error> { pub fn devices(&self) -> Result<Vec<String>, Error> {
let mut raw = RawDevices { let mut raw = RawDevices {
@@ -366,9 +377,23 @@ impl Core {
)?; )?;
let d = cstring(device)?; let d = cstring(device)?;
let mut compiled = std::ptr::null_mut(); let mut compiled = std::ptr::null_mut();
// SAFETY: valid core, model and device name; zero optional properties (the variadic tail is empty). let key = cstring("CACHE_DIR")?;
let status = // SAFETY: valid core, model and device name; the variadic tail is empty or one (key, value) pair of
unsafe { (self.ov.fns.compile)(self.raw, model, d.as_ptr(), 0usize, &mut compiled) }; // NUL-terminated strings that live through the call, announced by the count of 2 (the C API counts the arguments, not the pairs).
let status = unsafe {
match &self.cache_dir {
Some(dir) => (self.ov.fns.compile)(
self.raw,
model,
d.as_ptr(),
2usize,
&mut compiled,
key.as_ptr(),
dir.as_ptr(),
),
None => (self.ov.fns.compile)(self.raw, model, d.as_ptr(), 0usize, &mut compiled),
}
};
// SAFETY: the model was created above and is not needed once compiled (or if compiling failed). // SAFETY: the model was created above and is not needed once compiled (or if compiling failed).
unsafe { (self.ov.fns.model_free)(model) }; unsafe { (self.ov.fns.model_free)(model) };
self.ov.check(status, "ov_core_compile_model")?; self.ov.check(status, "ov_core_compile_model")?;
+61 -5
View File
@@ -99,7 +99,11 @@ fn model(m: usize, k: usize, n: usize, int8: bool, param: bool) -> (String, Vec<
let v = ((rng.next() % 2001) as f32 - 1000.0) * 1e-5; let v = ((rng.next() % 2001) as f32 - 1000.0) * 1e-5;
bin.extend_from_slice(&f32_to_f16(v).to_le_bytes()); bin.extend_from_slice(&f32_to_f16(v).to_le_bytes());
} }
write!(xml, "<layer id=\"1\" name=\"w\" type=\"Const\" version=\"opset1\"><data element_type=\"f16\" shape=\"{n},{k}\" offset=\"0\" size=\"{size}\"/><output><port id=\"0\" precision=\"FP16\">{}</port></output></layer>", dims(n, k)).unwrap(); if param {
write!(xml, "<layer id=\"1\" name=\"w\" type=\"Parameter\" version=\"opset1\"><data shape=\"{n},{k}\" element_type=\"f16\"/><output><port id=\"0\" precision=\"FP16\" names=\"w\">{}</port></output></layer>", dims(n, k)).unwrap();
} else {
write!(xml, "<layer id=\"1\" name=\"w\" type=\"Const\" version=\"opset1\"><data element_type=\"f16\" shape=\"{n},{k}\" offset=\"0\" size=\"{size}\"/><output><port id=\"0\" precision=\"FP16\">{}</port></output></layer>", dims(n, k)).unwrap();
}
weight_out = (1, 0); weight_out = (1, 0);
} }
write!(xml, "<layer id=\"5\" name=\"mm\" type=\"MatMul\" version=\"opset1\"><data transpose_a=\"false\" transpose_b=\"true\"/><input><port id=\"0\" precision=\"FP16\">{}</port><port id=\"1\" precision=\"FP16\">{}</port></input><output><port id=\"2\" precision=\"FP16\" names=\"y\">{}</port></output></layer>", dims(m, k), dims(n, k), dims(m, n)).unwrap(); write!(xml, "<layer id=\"5\" name=\"mm\" type=\"MatMul\" version=\"opset1\"><data transpose_a=\"false\" transpose_b=\"true\"/><input><port id=\"0\" precision=\"FP16\">{}</port><port id=\"1\" precision=\"FP16\">{}</port></input><output><port id=\"2\" precision=\"FP16\" names=\"y\">{}</port></output></layer>", dims(m, k), dims(n, k), dims(m, n)).unwrap();
@@ -158,7 +162,8 @@ fn main() {
let work = std::path::PathBuf::from(&a[2]); let work = std::path::PathBuf::from(&a[2]);
let device = CString::new(a[3].as_str()).unwrap(); let device = CString::new(a[3].as_str()).unwrap();
let int8 = a[4] == "i8" || a[4] == "i8p"; let int8 = a[4] == "i8" || a[4] == "i8p";
let param = a[4] == "i8p"; let f16p = a[4] == "f16p";
let param = a[4] == "i8p" || f16p;
let mx = a[4] == "mx"; let mx = a[4] == "mx";
let group = a[4] == "i8g" || mx; let group = a[4] == "i8g" || mx;
let (k, n): (usize, usize) = (a[5].parse().unwrap(), a[6].parse().unwrap()); let (k, n): (usize, usize) = (a[5].parse().unwrap(), a[6].parse().unwrap());
@@ -218,6 +223,11 @@ fn main() {
unsafe extern "C" fn(*mut c_void) -> i32 unsafe extern "C" fn(*mut c_void) -> i32
); );
let free_str = sym!(lib, "ov_free", unsafe extern "C" fn(*const c_char)); let free_str = sym!(lib, "ov_free", unsafe extern "C" fn(*const c_char));
let get_output = sym!(
lib,
"ov_infer_request_get_output_tensor_by_index",
unsafe extern "C" fn(*const c_void, usize, *mut *mut c_void) -> i32
);
unsafe { unsafe {
let mut core = std::ptr::null_mut(); let mut core = std::ptr::null_mut();
@@ -267,6 +277,12 @@ fn main() {
*v = f32_to_f16(((rng.next() % 2001) as f32 - 1000.0) * 1e-3); *v = f32_to_f16(((rng.next() % 2001) as f32 - 1000.0) * 1e-3);
} }
check(set_input(req, 0, tensor), "set_input", err); check(set_input(req, 0, tensor), "set_input", err);
let mut last_w: *mut c_void = std::ptr::null_mut();
let mut last_s: *mut c_void = std::ptr::null_mut();
let last_x: *mut c_void = data;
let qmax: i32 = std::env::var("SPIKE_QMAX").ok().and_then(|s| s.parse().ok()).unwrap_or(127);
let wide = std::env::var_os("SPIKE_WIDE_SCALES").is_some();
let tiny = std::env::var_os("SPIKE_TINY_SCALES").is_some();
if group { if group {
let g = k / 32; let g = k / 32;
let make = |elem: u32, dims: &[i64]| { let make = |elem: u32, dims: &[i64]| {
@@ -282,8 +298,9 @@ fn main() {
let wbytes = if mx { n * k / 2 } else { n * k }; let wbytes = if mx { n * k / 2 } else { n * k };
let ws = std::slice::from_raw_parts_mut(wd as *mut u8, wbytes); let ws = std::slice::from_raw_parts_mut(wd as *mut u8, wbytes);
for v in ws.iter_mut() { for v in ws.iter_mut() {
*v = rng.next() as u8; *v = if mx { rng.next() as u8 } else { (((rng.next() % (2 * qmax as u64 + 1)) as i32) - qmax) as i8 as u8 };
} }
last_w = wd;
check(set_input(req, 1, wt), "set_input w", err); check(set_input(req, 1, wt), "set_input w", err);
let (st, sd) = make(if mx { 25 } else { 3 }, &[n as i64, g as i64, 1]); let (st, sd) = make(if mx { 25 } else { 3 }, &[n as i64, g as i64, 1]);
if mx { if mx {
@@ -294,9 +311,10 @@ fn main() {
} else { } else {
let ss = std::slice::from_raw_parts_mut(sd as *mut u16, n * g); let ss = std::slice::from_raw_parts_mut(sd as *mut u16, n * g);
for v in ss.iter_mut() { for v in ss.iter_mut() {
*v = f32_to_f16(0.0005); *v = if tiny { 1 + (rng.next() % 1000) as u16 } else if wide { f32_to_f16(2f32.powi(-14 + (rng.next() % 7) as i32) * (1.0 + (rng.next() % 100) as f32 / 100.0)) } else { f32_to_f16(0.0005) };
} }
} }
last_s = sd;
check(set_input(req, 2, st), "set_input s", err); check(set_input(req, 2, st), "set_input s", err);
} }
if param { if param {
@@ -304,7 +322,7 @@ fn main() {
let mut wshape = Shape { rank: 0, dims: std::ptr::null_mut() }; let mut wshape = Shape { rank: 0, dims: std::ptr::null_mut() };
check(shape_create(2, wdims.as_ptr(), &mut wshape), "shape_create", err); check(shape_create(2, wdims.as_ptr(), &mut wshape), "shape_create", err);
let mut wt = std::ptr::null_mut(); let mut wt = std::ptr::null_mut();
check(tensor_create(7, wshape, &mut wt), "tensor_create i8", err); check(tensor_create(if f16p { 3 } else { 7 }, wshape, &mut wt), "tensor_create w", err);
let mut wd = std::ptr::null_mut(); let mut wd = std::ptr::null_mut();
check(tensor_data(wt, &mut wd), "tensor_data", err); check(tensor_data(wt, &mut wd), "tensor_data", err);
let ws = std::slice::from_raw_parts_mut(wd as *mut u8, n * k); let ws = std::slice::from_raw_parts_mut(wd as *mut u8, n * k);
@@ -316,6 +334,44 @@ fn main() {
let t = Instant::now(); let t = Instant::now();
check(infer(req), "first infer", err); check(infer(req), "first infer", err);
let first = t.elapsed().as_secs_f64() * 1e3; let first = t.elapsed().as_secs_f64() * 1e3;
if group && !mx && std::env::var_os("SPIKE_ACCURACY").is_some() {
// reference in f64 from the very bytes handed to the device
let g = k / 32;
let qmax: i32 = std::env::var("SPIKE_QMAX").ok().and_then(|s| s.parse().ok()).unwrap_or(127);
let _ = qmax;
let mut out_t = std::ptr::null_mut();
check(get_output(req, 0, &mut out_t), "get_output", err);
let mut od = std::ptr::null_mut();
check(tensor_data(out_t, &mut od), "tensor_data", err);
let y = std::slice::from_raw_parts(od as *const u16, m * n);
let h2f = |b: u16| {
let e = i32::from((b >> 10) & 31);
let man = f64::from(b & 1023);
let s = if b & 0x8000 != 0 { -1.0 } else { 1.0 };
s * if e == 0 { man * 2f64.powi(-24) } else { (1.0 + man / 1024.0) * 2f64.powi(e - 15) }
};
let wsl = std::slice::from_raw_parts(last_w as *const u8, n * k);
let ssl = std::slice::from_raw_parts(last_s as *const u16, n * g);
let xsl = std::slice::from_raw_parts(last_x as *const u16, m * k);
let (mut num, mut den) = (0f64, 0f64);
for r in 0..m.min(8) {
for c in 0..n {
let mut acc = 0f64;
for gi in 0..g {
let sc = h2f(ssl[c * g + gi]);
let mut part = 0f64;
for j in 0..32 {
part += h2f(xsl[r * k + gi * 32 + j]) * f64::from(wsl[(c * g + gi) * 32 + j] as i8);
}
acc += sc * part;
}
let got = h2f(y[r * n + c]);
num += (got - acc) * (got - acc);
den += acc * acc;
}
}
println!(" accuracy: relative rms error {:.2e} (first {} rows)", (num / den).sqrt(), m.min(8));
}
let t = Instant::now(); let t = Instant::now();
for _ in 0..iters { for _ in 0..iters {
check(infer(req), "infer", err); check(infer(req), "infer", err);