From 8d96e9c44cdcb6d4882068d824292440696834ea Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Thu, 15 Oct 2026 12:22:13 +0200 Subject: [PATCH] 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 --- Cargo.lock | 1 + crates/cpu-kernels/src/lib.rs | 10 + crates/cpu-sys/src/lib.rs | 18 + crates/cpu-sys/src/simd.rs | 22 ++ crates/cpu-sys/tests/attention.rs | 26 ++ crates/gptoss-npu/examples/ab_prefill_npu.rs | 1 + .../gptoss-npu/examples/dump_logprobs_npu.rs | 1 + crates/gptoss-npu/examples/npu_prefill.rs | 1 + crates/gptoss-npu/examples/numerics_probe.rs | 1 + crates/gptoss-npu/src/client.rs | 142 ++++++- crates/gptoss-npu/src/lib.rs | 344 ++++++++++++----- crates/npu-service/src/engine.rs | 364 ++++++++++++------ crates/npu-service/src/main.rs | 40 +- crates/npu-service/src/protocol.rs | 13 +- crates/npu-worker/Cargo.toml | 1 + crates/npu-worker/src/main.rs | 13 +- crates/openvino/src/lib.rs | 31 +- experiments/npu-spike/src/main.rs | 66 +++- 18 files changed, 861 insertions(+), 234 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7c938972..8d5e678b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1355,6 +1355,7 @@ version = "0.1.0" dependencies = [ "leleka-cpu-worker", "leleka-gptoss-npu", + "sysinfo", ] [[package]] diff --git a/crates/cpu-kernels/src/lib.rs b/crates/cpu-kernels/src/lib.rs index b292ff1d..86000987 100644 --- a/crates/cpu-kernels/src/lib.rs +++ b/crates/cpu-kernels/src/lib.rs @@ -108,6 +108,7 @@ type AttnScores = fn(&[f32], usize, &[u16], usize, usize, f32, &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 FromHalf = fn(&[u16], &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 ExpSum = fn(&mut [f32], f32) -> Result; @@ -128,6 +129,7 @@ pub struct Dispatch { attn_weighted_sum: AttnSum, exp_shift_sum: ExpSum, f32_to_f16: ToHalf, + f16_to_f32: FromHalf, rows_dot: RowsDot, swiglu_oai: Swiglu, } @@ -163,6 +165,7 @@ impl Dispatch { attn_scores: leleka_cpu_sys::attn_scores_f16_scalar, attn_weighted_sum: leleka_cpu_sys::attn_weighted_sum_f16_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| { 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_weighted_sum: leleka_cpu_sys::attn_weighted_sum_f16_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| { 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_weighted_sum: leleka_cpu_sys::attn_weighted_sum_f16_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| { 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) } + /// 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). pub fn exp_shift_sum(&self, x: &mut [f32], max: f32) -> Result { (self.exp_shift_sum)(x, max) diff --git a/crates/cpu-sys/src/lib.rs b/crates/cpu-sys/src/lib.rs index 5ea84027..8c365d07 100644 --- a/crates/cpu-sys/src/lib.rs +++ b/crates/cpu-sys/src/lib.rs @@ -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)) } +/// 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). pub fn exp_shift_sum_scalar(x: &mut [f32], max: f32) -> Result { Ok(simd::exp_shift_sum_scalar(x, max)) diff --git a/crates/cpu-sys/src/simd.rs b/crates/cpu-sys/src/simd.rs index 0e67ebd5..9f2a3135 100644 --- a/crates/cpu-sys/src/simd.rs +++ b/crates/cpu-sys/src/simd.rs @@ -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()`. pub fn f32_to_f16_slice_scalar(src: &[f32], dst: &mut [u16]) { 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")] pub unsafe fn swiglu_oai_avx2( gate: &[f32], diff --git a/crates/cpu-sys/tests/attention.rs b/crates/cpu-sys/tests/attention.rs index e0bb8b8a..630b1f45 100644 --- a/crates/cpu-sys/tests/attention.rs +++ b/crates/cpu-sys/tests/attention.rs @@ -371,3 +371,29 @@ fn the_expert_activation_matches_an_f64_reference_including_extremes() { 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 = (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) + ); +} diff --git a/crates/gptoss-npu/examples/ab_prefill_npu.rs b/crates/gptoss-npu/examples/ab_prefill_npu.rs index 10438e3b..3a235062 100644 --- a/crates/gptoss-npu/examples/ab_prefill_npu.rs +++ b/crates/gptoss-npu/examples/ab_prefill_npu.rs @@ -99,6 +99,7 @@ fn main() { openvino_root: args[1].clone().into(), device: args[3].clone(), model: path.to_path_buf(), + cache_dir: None, }; let mut accel = NpuPrefill::start(&config, batch).expect("start the NPU service"); println!("# paired prefill A/B (warm)"); diff --git a/crates/gptoss-npu/examples/dump_logprobs_npu.rs b/crates/gptoss-npu/examples/dump_logprobs_npu.rs index c8305ea2..1dfa4c4e 100644 --- a/crates/gptoss-npu/examples/dump_logprobs_npu.rs +++ b/crates/gptoss-npu/examples/dump_logprobs_npu.rs @@ -54,6 +54,7 @@ fn main() { openvino_root: args[1].clone().into(), device: args[3].clone(), model: path.to_path_buf(), + cache_dir: None, }; let mut accel = NpuPrefill::start(&config, batch).expect("start the NPU service"); let hidden = accel diff --git a/crates/gptoss-npu/examples/npu_prefill.rs b/crates/gptoss-npu/examples/npu_prefill.rs index ab482470..71c95e45 100644 --- a/crates/gptoss-npu/examples/npu_prefill.rs +++ b/crates/gptoss-npu/examples/npu_prefill.rs @@ -69,6 +69,7 @@ fn main() { openvino_root: PathBuf::from(&a[1]), device: a[3].clone(), model: path.to_path_buf(), + cache_dir: None, }; let mut accel = NpuPrefill::start(&config, batch).expect("start the NPU service"); if let Ok(shadow_device) = std::env::var("LELEKA_SHADOW_DEVICE") { diff --git a/crates/gptoss-npu/examples/numerics_probe.rs b/crates/gptoss-npu/examples/numerics_probe.rs index 5fe022f9..42fcdac2 100644 --- a/crates/gptoss-npu/examples/numerics_probe.rs +++ b/crates/gptoss-npu/examples/numerics_probe.rs @@ -90,6 +90,7 @@ fn main() { openvino_root: PathBuf::from(&a[1]), device: device.to_owned(), model: path.to_path_buf(), + cache_dir: None, }; let mut client = Client::start(&config, 64).unwrap(); client.put(client.layout.input_a, &halves).unwrap(); diff --git a/crates/gptoss-npu/src/client.rs b/crates/gptoss-npu/src/client.rs index 97977c7a..f0d88664 100644 --- a/crates/gptoss-npu/src/client.rs +++ b/crates/gptoss-npu/src/client.rs @@ -16,6 +16,8 @@ pub struct ServiceConfig { /// `NPU` normally; `CPU` or `GPU` to test without one. pub device: String, pub model: PathBuf, + /// Where the service keeps compiled graphs (default: a folder under the temporary directory). + pub cache_dir: Option, } /// A byte range of the shared region. @@ -25,32 +27,67 @@ pub struct Region { 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)] pub struct Layout { pub input_a: Region, pub input_b: Region, 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, } impl Layout { - pub fn new(max_rows: usize) -> Self { - // room after the widest result for the per-column scale shifts (one byte per column) + 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) and the gaps + // between consecutive products of a batch 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 { offset: i * bytes, bytes, }; + let expert_at = |i: usize| Region { + offset: 6 * bytes + i * entry_bytes, + bytes: entry_bytes, + }; Self { input_a: at(0), input_b: at(1), 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, + 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 { child: Child, stdin: ChildStdin, @@ -63,7 +100,7 @@ pub struct Client { impl Client { pub fn start(config: &ServiceConfig, max_rows: usize) -> Result { - let layout = Layout::new(max_rows); + let layout = Layout::new(max_rows, max_rows * 4); let path = std::env::temp_dir().join(format!("leleka-npu-{}-{}.shm", std::process::id(), nanos())); let shm = Shared::create(&path, layout.total) @@ -97,6 +134,13 @@ impl Client { .arg("--shm") .arg(&path) .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()) .stdout(Stdio::piped()) .stderr(Stdio::inherit()) @@ -177,6 +221,72 @@ impl Client { .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 = 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, 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>>, 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 /// 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. @@ -229,16 +339,25 @@ 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]]; + fn regions_do_not_overlap_and_fit_their_widest_use() { + let l = Layout::new(1024, 4096); + 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() { - assert_eq!(a.bytes, 1024 * 4096 * 2 + 4096); 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] @@ -248,6 +367,7 @@ mod tests { openvino_root: PathBuf::from("nowhere"), device: "CPU".into(), model: PathBuf::from("none.gguf"), + cache_dir: None, }; assert!(Client::start(&config, 32).is_err()); } diff --git a/crates/gptoss-npu/src/lib.rs b/crates/gptoss-npu/src/lib.rs index c18af99c..c6a4fa3b 100644 --- a/crates/gptoss-npu/src/lib.rs +++ b/crates/gptoss-npu/src/lib.rs @@ -14,16 +14,16 @@ pub mod client; mod half; mod par; -use client::{Client, Layout, Region, ServiceConfig}; +use client::{Client, Layout, Region, ServiceConfig, Spec}; 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; +/// Rows per batch of prompt tokens unless changed (the service has graphs for up to 4096 rows). +pub const DEFAULT_BATCH: usize = 2048; +const MAX_ROWS: usize = 4096; /// Where the time of the last prefill went. #[derive(Clone, Debug, Default)] @@ -34,35 +34,63 @@ pub struct Timings { pub attention: Duration, /// The rest of the CPU work (norms, RoPE, router, activation, conversions). 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, } impl Timings { + fn part(&mut self, i: usize, d: Duration) { + self.other += d; + self.parts[i] += d; + } + 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}", + "{} 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, s(self.total), s(self.npu), 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 Option + Send>; + 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, + memory_probe: Option, /// Round the activations through the CPU decoder's Q8_0 quantisation before the device sees them. quantize_activations: bool, + dispatch: Dispatch, /// Scale shifts reported for the last product written to a region (by offset), applied when it is read. shifts: std::collections::HashMap>, } +/// 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 { ModelError::Invalid(format!("NPU prefill: {e}")) } @@ -71,13 +99,15 @@ impl NpuPrefill { /// Start the service process and wait until its device is ready. pub fn start(config: &ServiceConfig, batch: usize) -> Result { let batch = batch.clamp(1, MAX_ROWS); - let client = Client::start(config, MAX_ROWS)?; + let client = Client::start(config, batch)?; Ok(Self { client, batch, timings: Timings::default(), shadow: None, + memory_probe: None, quantize_activations: false, + dispatch: Dispatch::best(), 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 /// ones that differ (debugging). pub fn with_shadow(mut self, config: &ServiceConfig) -> Result { - self.shadow = Some(Client::start(config, MAX_ROWS)?); + self.shadow = Some(Client::start(config, self.batch)?); Ok(self) } @@ -97,6 +127,28 @@ impl NpuPrefill { 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 { self.client.device_name() } @@ -121,10 +173,13 @@ impl NpuPrefill { /// `rows` half floats from `region` as floats. fn fetch(&self, region: Region, rows: usize, width: usize) -> Result, ModelError> { let halves = self.client.get(region, rows * width).map_err(fail)?; + let dispatch = self.dispatch; 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); + dispatch + .f16_to_f32(&halves[start..start + chunk.len()], chunk) + .expect("equal lengths"); }); if let Some(shifts) = self.shifts.get(®ion.offset) { scale_columns(&mut out, width, shifts); @@ -224,13 +279,19 @@ impl NpuPrefill { capacity: state.capacity(), }); } - for width in [e, qw, ff] { - if width % 32 != 0 || width > 4096 { + for (width, limit) in [(e, 3072), (ff, 3072), (qw, 4096)] { + if width % 32 != 0 || width > limit { 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 dispatch = *model.dispatch(); let group = c.n_head / c.n_head_kv; @@ -273,7 +334,7 @@ impl NpuPrefill { ) }); self.put_floats(&dispatch, layout.input_a, &h)?; - self.timings.other += t0.elapsed(); + self.timings.part(0, t0.elapsed()); self.product( &name("attn_q"), None, @@ -333,7 +394,7 @@ impl NpuPrefill { .expect("equal lengths"); }); } - self.timings.other += t1.elapsed(); + self.timings.part(1, t1.elapsed()); // --- attention over the cache --- let t2 = Instant::now(); @@ -385,7 +446,7 @@ impl NpuPrefill { // --- output projection and residual --- let t3 = Instant::now(); self.put_floats(&dispatch, layout.input_a, &attn)?; - self.timings.other += t3.elapsed(); + self.timings.part(2, t3.elapsed()); self.product( &name("attn_output"), None, @@ -439,22 +500,17 @@ impl NpuPrefill { per_expert[*ex].push((t, *weight)); } } - self.timings.other += t4.elapsed(); + self.timings.part(3, 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 moe = self.experts(&dispatch, &view, l, &per_expert, &h2f, m, (e, ff))?; 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(); + self.timings.part(4, t5.elapsed()); } 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 - /// weighted add into `moe`. + /// All experts of one batch at once. The entries (token, expert pairs) are sorted by expert and gathered into + /// 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 - fn expert( + fn experts( &mut self, dispatch: &Dispatch, view: &LayerView<'_>, - name: &dyn Fn(&str) -> String, - ex: usize, - rows: &[(usize, f32)], + layer: usize, + per_expert: &[Vec<(usize, f32)>], h2f: &[u16], - e: usize, - ff: usize, - moe: &mut [f32], - ) -> Result<(), ModelError> { + m: usize, + (e, ff): (usize, usize), + ) -> 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; + let name = |part: &str| format!("blk.{layer}.{part}.weight"); + let mut chunks: Vec = Vec::new(); + let mut entry_token: Vec = Vec::new(); + let mut entry_expert: Vec = Vec::new(); + let mut token_entries: Vec> = vec![Vec::new(); m]; + for (ex, list) in per_expert.iter().enumerate() { + for rows in list.chunks(MAX_ROWS) { + chunks.push(Chunk { + ex, + start: entry_token.len(), + rows: rows.len(), + }); + for (t, w) in rows { + token_entries[*t].push((entry_token.len(), *w)); + entry_token.push(*t); + entry_expert.push(ex); + } } } + 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 { + 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| { let first = i * rows_per; let count = out.len() / ff; @@ -540,30 +637,74 @@ impl NpuPrefill { ) .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); + let halves = halves_of(dispatch, &act, self.quantize_activations); + self.client + .put_at(layout.expert[3].offset, &halves) + .map_err(fail)?; + let down_specs: Vec = chunks + .iter() + .enumerate() + .map(|(c, ch)| Spec { + name: name("ffn_down_exps"), + expert: Some(ch.ex), + rows: ch.rows, + cols: e, + input: layout.expert[3].offset + ch.start * ff * 2, + out: down_at[c], + }) + .collect(); + self.timings.part(6, t2.elapsed()); + let t3 = Instant::now(); + let down_shifts = self.client.products(&down_specs).map_err(fail)?; + 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>], + ) -> Result, 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(()) + Ok(out) } } @@ -578,6 +719,25 @@ impl PrefillAccelerator for NpuPrefill { ) -> Result>, ModelError> { 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]`. diff --git a/crates/npu-service/src/engine.rs b/crates/npu-service/src/engine.rs index 43a1e5c7..9d8afd7c 100644 --- a/crates/npu-service/src/engine.rs +++ b/crates/npu-service/src/engine.rs @@ -13,7 +13,7 @@ use std::sync::Arc; 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]; +pub const BUCKETS: [usize; 8] = [32, 64, 128, 256, 512, 1024, 2048, 4096]; #[derive(Clone, Debug)] pub struct Options { @@ -24,6 +24,8 @@ pub struct Options { pub model: PathBuf, /// The region file shared with the client; the service maps it. pub shm: PathBuf, + /// Where OpenVINO keeps compiled graphs between runs, if anywhere. + pub cache_dir: Option, } /// 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, } -/// 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 { ov: Arc, core: Core, device: String, - graphs: HashMap<(usize, usize, usize), Compiled>, - slots: HashMap<(usize, usize, usize), Slot>, + graphs: HashMap, + index: HashMap, + pairs: Vec, } fn ov_error(e: leleka_openvino::Error) -> String { @@ -130,42 +143,77 @@ fn ov_error(e: leleka_openvino::Error) -> String { } impl Runtime { - fn slot(&mut self, k: usize, n: usize, bucket: usize) -> Result<&mut Slot, String> { - let key = (k, n, bucket); - if !self.slots.contains_key(&key) { - if !self.graphs.contains_key(&key) { - let (xml, bin) = graph::matmul_ir(bucket, k, n); - let compiled = self - .core - .compile(&self.device, &xml, &bin) - .map_err(ov_error)?; - self.graphs.insert(key, compiled); - } - let g = k / GROUP; - let mut request = self.graphs[&key].request().map_err(ov_error)?; - let x = Tensor::new(&self.ov, Element::F16, &[bucket as i64, k as i64]) - .map_err(ov_error)?; - let w = Tensor::new(&self.ov, Element::I8, &[n as i64, g as i64, GROUP as i64]) - .map_err(ov_error)?; - let s = - Tensor::new(&self.ov, Element::F16, &[n as i64, g as i64, 1]).map_err(ov_error)?; - 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")) + fn make_slot(&self, key: Key) -> Result { + let (k, n, bucket) = key; + let g = k / GROUP; + let mut request = self.graphs[&key].request().map_err(ov_error)?; + let x = + Tensor::new(&self.ov, Element::F16, &[bucket as i64, k as i64]).map_err(ov_error)?; + let w = Tensor::new(&self.ov, Element::I8, &[n as i64, g as i64, GROUP as i64]) + .map_err(ov_error)?; + let s = Tensor::new(&self.ov, Element::F16, &[n as i64, g as i64, 1]).map_err(ov_error)?; + 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)?; + Ok(Slot { + request, + x, + w, + s, + loaded: None, + shifts: Vec::new(), + }) } + + /// The index of the slot pair for a shape, compiling the graph on first use. + fn pair(&mut self, key: Key) -> Result { + 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(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)) -> 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 { @@ -181,10 +229,42 @@ fn io_error(what: &str, e: impl std::fmt::Display) -> String { 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), +} + +fn plan<'a>(weights: &'a Weights, p: &Product) -> Result, 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 { pub fn new(options: &Options) -> Result { 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)?; if !devices.contains(&options.device) { return Err(format!( @@ -211,7 +291,8 @@ impl Engine { core, device: options.device.clone(), graphs: HashMap::new(), - slots: HashMap::new(), + index: HashMap::new(), + pairs: Vec::new(), }, weights: Weights { gguf, map }, shm, @@ -230,81 +311,136 @@ impl Engine { BUCKETS.iter().copied().find(|b| *b >= rows) } - /// Run one product. Activations are read from and the result written to the shared region as - /// little-endian half floats: `rows * k` in, `rows * n` out. + /// Run one product (see [`Engine::run_batch`]). pub fn run(&mut self, p: &Product) -> Result { + 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> { + (0..list.len()).map(|i| self.run_at(list, i)).collect() + } + + fn run_at(&mut self, list: &[Product], i: usize) -> Result { 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()); - } - let bucket = Self::bucket_for(p.rows).ok_or_else(|| { - format!( - "{} rows exceed the largest bucket {}", - p.rows, - BUCKETS[BUCKETS.len() - 1] - ) - })?; - let matrix = self.weights.matrix(&p.name, p.expert)?; - let (n, k) = (matrix.n, matrix.k); + let Self { + runtime, + weights, + shm, + scratch, + profile, + .. + } = self; + let p = &list[i]; + let cur = plan(weights, p)?; + let (n, k) = (cur.matrix.n, cur.matrix.k); 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); - self.shm - .read(p.in_offset, &mut buffer[..in_bytes]) + let lap = Instant::now(); + shm.read(p.in_offset, &mut buffer[..in_bytes]) .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)?; - tick(&mut self.profile.compile); - let id = (p.name.clone(), p.expert); - if slot.loaded.as_ref() != Some(&id) { - expand::expand_parallel( - matrix.format, - matrix.bytes, - 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(); + // pairs for this product and the next one (compiling graphs the first time) + let lap = Instant::now(); + let ci = runtime.pair(cur.key)?; + let next = list.get(i + 1).and_then(|np| plan(weights, np).ok()); + let ni = match &next { + Some(nx) => runtime.pair(nx.key).ok(), + None => None, + }; + profile.compile += lap.elapsed(); + + // the slot for this product, expanding synchronously if nobody prefetched it + let lap = Instant::now(); + let idx = { + 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); - 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, + (Some(ni), Some(nx)) => { + 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)); + let target = if hit.is_some() { + None + } else { + let t = b.next; + b.next = 1 - t; + Some((&mut b.slots[t], nx)) + }; + (&mut a.slots[idx], target) + } + _ => (&mut runtime.pairs[ci].slots[idx], None), + }; + + let lap = Instant::now(); + let outcome: Result = std::thread::scope(|scope| { + let prefetch = target.map(|(tgt, nx)| { + scope.spawn(move || { + // a failed prefetch leaves the slot unloaded; the product then loads it itself and + // reports the error + let _ = load(tgt, &nx.matrix, nx.id.clone()); + }) + }); + let result = (|| { + slot.x.write(0, &buffer[..in_bytes]).map_err(ov_error)?; + slot.x.bytes_mut().map_err(ov_error)?[in_bytes..].fill(0); + slot.request.infer().map_err(ov_error)?; + slot.request + .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 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}", + "{} products: read activations {:.0} ms | slots/compile {:.0} | expand weights (not prefetched) {:.0} | run on the device incl. prefetch {:.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. +/// Time spent in each phase of `Engine::run_batch`, 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, } diff --git a/crates/npu-service/src/main.rs b/crates/npu-service/src/main.rs index 41775137..b0bc6bff 100644 --- a/crates/npu-service/src/main.rs +++ b/crates/npu-service/src/main.rs @@ -11,7 +11,7 @@ use std::process::ExitCode; fn parse_args() -> Result { 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(); while let Some(arg) = args.next() { let mut value = |name: &str| args.next().ok_or_else(|| format!("{name} needs a value")); @@ -19,6 +19,7 @@ fn parse_args() -> Result { "--openvino" => dll = Some(PathBuf::from(value("--openvino")?)), "--model" => model = Some(PathBuf::from(value("--model")?)), "--shm" => shm = Some(PathBuf::from(value("--shm")?)), + "--cache-dir" => cache_dir = Some(PathBuf::from(value("--cache-dir")?)), "--device" => device = value("--device")?, other => return Err(format!("unknown argument {other}")), } @@ -28,6 +29,7 @@ fn parse_args() -> Result { device, model: model.ok_or("--model 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() { return ExitCode::FAILURE; } - for line in std::io::stdin().lock().lines() { - let Ok(line) = line else { break }; + let stdin = std::io::stdin(); + let mut lines = stdin.lock().lines(); + while let Some(Ok(line)) = lines.next() { let answer = match protocol::parse(&line) { Ok(Command::Quit) => break, 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(done) => protocol::ok_line(done), Err(m) => protocol::err_line(&m), diff --git a/crates/npu-service/src/protocol.rs b/crates/npu-service/src/protocol.rs index 36f0b14b..e1f26ec1 100644 --- a/crates/npu-service/src/protocol.rs +++ b/crates/npu-service/src/protocol.rs @@ -1,6 +1,7 @@ //! The line protocol between the client and the service (docs/npu-service.md). //! -//! Client to service: `PING`, `MM `, `QUIT`. +//! Client to service: `PING`, `MM `, `BATCH ` followed by +//! `n` `MM` lines, `QUIT`. //! Service to client: `READY ` once at start, then `PONG`, `OK ` or `ERR ` //! per line. Offsets are byte offsets into the shared region; activations and results are half floats. @@ -11,6 +12,9 @@ pub enum Command { Ping, Product(Product), Quit, + /// `BATCH `: 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 { @@ -18,6 +22,11 @@ pub fn parse(line: &str) -> Result { match fields.next() { Some("PING") => Ok(Command::Ping), 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") => { 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 -")? { @@ -91,6 +100,8 @@ mod tests { fn other_commands_and_errors() { assert_eq!(parse("PING").unwrap(), Command::Ping); 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 e 1 2 3").is_err()); assert!(parse("NOPE").is_err()); diff --git a/crates/npu-worker/Cargo.toml b/crates/npu-worker/Cargo.toml index bc9dbb6a..f882217c 100644 --- a/crates/npu-worker/Cargo.toml +++ b/crates/npu-worker/Cargo.toml @@ -13,6 +13,7 @@ path = "src/main.rs" [dependencies] leleka-cpu-worker = { path = "../cpu-worker" } leleka-gptoss-npu = { path = "../gptoss-npu" } +sysinfo = { version = "0.39.6", default-features = false, features = ["system"] } [lints] workspace = true diff --git a/crates/npu-worker/src/main.rs b/crates/npu-worker/src/main.rs index 3c807247..51a6a983 100644 --- a/crates/npu-worker/src/main.rs +++ b/crates/npu-worker/src/main.rs @@ -143,6 +143,7 @@ fn main() -> ExitCode { openvino_root, device: args.device.clone(), model: args.model.clone(), + cache_dir: None, }; match NpuPrefill::start(&config, args.batch) { Ok(npu) => { @@ -152,7 +153,10 @@ fn main() -> ExitCode { args.min_tokens, 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"), } @@ -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 { + let mut system = sysinfo::System::new(); + system.refresh_memory(); + Some(system.available_memory()).filter(|bytes| *bytes > 0) +} diff --git a/crates/openvino/src/lib.rs b/crates/openvino/src/lib.rs index 2480af96..b4577c6a 100644 --- a/crates/openvino/src/lib.rs +++ b/crates/openvino/src/lib.rs @@ -284,6 +284,7 @@ impl OpenVino { pub struct Core { ov: Arc, raw: *mut c_void, + cache_dir: Option, } // 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 { ov: ov.clone(), 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 { + 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`. pub fn devices(&self) -> Result, Error> { let mut raw = RawDevices { @@ -366,9 +377,23 @@ impl Core { )?; let d = cstring(device)?; let mut compiled = std::ptr::null_mut(); - // SAFETY: valid core, model and device name; zero optional properties (the variadic tail is empty). - let status = - unsafe { (self.ov.fns.compile)(self.raw, model, d.as_ptr(), 0usize, &mut compiled) }; + let key = cstring("CACHE_DIR")?; + // SAFETY: valid core, model and device name; the variadic tail is empty or one (key, value) pair of + // 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). unsafe { (self.ov.fns.model_free)(model) }; self.ov.check(status, "ov_core_compile_model")?; diff --git a/experiments/npu-spike/src/main.rs b/experiments/npu-spike/src/main.rs index a7e2faac..a966c31f 100644 --- a/experiments/npu-spike/src/main.rs +++ b/experiments/npu-spike/src/main.rs @@ -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; bin.extend_from_slice(&f32_to_f16(v).to_le_bytes()); } - write!(xml, "{}", dims(n, k)).unwrap(); + if param { + write!(xml, "{}", dims(n, k)).unwrap(); + } else { + write!(xml, "{}", dims(n, k)).unwrap(); + } weight_out = (1, 0); } write!(xml, "{}{}{}", 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 device = CString::new(a[3].as_str()).unwrap(); 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 group = a[4] == "i8g" || mx; 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 ); 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 { 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); } 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 { let g = k / 32; let make = |elem: u32, dims: &[i64]| { @@ -282,8 +298,9 @@ fn main() { let wbytes = if mx { n * k / 2 } else { n * k }; let ws = std::slice::from_raw_parts_mut(wd as *mut u8, wbytes); 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); let (st, sd) = make(if mx { 25 } else { 3 }, &[n as i64, g as i64, 1]); if mx { @@ -294,9 +311,10 @@ fn main() { } else { let ss = std::slice::from_raw_parts_mut(sd as *mut u16, n * g); 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); } if param { @@ -304,7 +322,7 @@ fn main() { let mut wshape = Shape { rank: 0, dims: std::ptr::null_mut() }; check(shape_create(2, wdims.as_ptr(), &mut wshape), "shape_create", err); 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(); check(tensor_data(wt, &mut wd), "tensor_data", err); let ws = std::slice::from_raw_parts_mut(wd as *mut u8, n * k); @@ -316,6 +334,44 @@ fn main() { let t = Instant::now(); check(infer(req), "first infer", err); 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(); for _ in 0..iters { check(infer(req), "infer", err);