Files
leleka/crates/gpu-npu-worker/src/lib.rs
T

355 lines
12 KiB
Rust

//! One prompt's prefill split between the integrated GPU and the NPU (experimental).
//!
//! Both prefills run the prompt layer after layer. Here the NPU path (`leleka-gptoss-npu`, products in the NPU
//! service process, attention on the CPU) takes the first part of the tokens and the GPU path (`leleka-gptoss-igpu`)
//! takes the rest, on two threads at once. The two parts meet only in the key and value cache: the GPU part's
//! attention at layer `l` needs the NPU part's keys and values of layer `l`, so its cache view waits until the NPU
//! part has stored that layer, while the NPU part never waits (its tokens come first). The GPU part therefore runs
//! layer `l` while the NPU part runs layer `l + 1`: a two-stage pipeline with one layer of lag. Each part keeps its
//! own numerics, so the result is that of the NPU path for the first tokens and of the GPU path for the rest.
use leleka_gptoss::{LayerCache, Model, ModelError, PrefillAccelerator, PrefillJob, PrefillSpan, State};
use leleka_gptoss_igpu::GpuPrefill;
use leleka_gptoss_npu::NpuPrefill;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Condvar, Mutex};
use std::time::{Duration, Instant};
/// Fraction of a split prompt that goes to the NPU unless changed: alone the two run at about the same speed, and
/// at the same time the GPU kept about 59 tokens/s and the NPU about 48 (2048 tokens each, 2026-10-16).
pub const DEFAULT_NPU_SHARE: f64 = 0.45;
/// Prompts with fewer tokens to compute than this go to the GPU alone (below about 1024 tokens the NPU path is not
/// faster than the CPU, see `docs/npu-service.md`).
pub const DEFAULT_SPLIT_MIN_TOKENS: usize = 1024;
/// Reports the memory that can be used without paging (the OS's "available" figure).
pub type MemoryProbe = Box<dyn Fn() -> Option<u64> + Send>;
/// Where the time of the last split prefill went.
#[derive(Clone, Debug, Default)]
pub struct SplitTimings {
pub npu_tokens: usize,
pub gpu_tokens: usize,
pub npu: Duration,
pub gpu: Duration,
/// Time the GPU part spent waiting for the NPU part's layers.
pub gpu_wait: Duration,
pub total: Duration,
}
impl SplitTimings {
/// Timings of nothing yet for a prompt of `n` tokens cut after `npu_tokens` of them.
fn cut_at(npu_tokens: usize, n: usize) -> Self {
Self {
npu_tokens,
gpu_tokens: n - npu_tokens,
..Self::default()
}
}
pub fn report(&self) -> String {
let s = |d: Duration| d.as_secs_f64();
format!(
"{} + {} tokens in {:.2} s: npu part {:.2} s | gpu part {:.2} s, of which waiting for the npu {:.2} s",
self.npu_tokens,
self.gpu_tokens,
s(self.total),
s(self.npu),
s(self.gpu),
s(self.gpu_wait)
)
}
}
/// How many layers the first part has stored, or that it ended without storing the rest.
#[derive(Default)]
struct Handoff {
state: Mutex<(usize, bool)>,
changed: Condvar,
}
impl Handoff {
fn stored(&self, layers: usize) {
let mut s = self.state.lock().expect("handoff lock");
s.0 = s.0.max(layers);
self.changed.notify_all();
}
fn abandon(&self) {
self.state.lock().expect("handoff lock").1 = true;
self.changed.notify_all();
}
/// Wait until layer `layer` is stored; an error if the first part ended without it.
fn wait_for(&self, layer: usize) -> Result<(), ModelError> {
let mut s = self.state.lock().expect("handoff lock");
while s.0 <= layer {
if s.1 {
return Err(ModelError::Invalid(
"the NPU part of a split prefill ended early".into(),
));
}
s = self.changed.wait(s).expect("handoff lock");
}
Ok(())
}
}
/// The first part's cache: stores go to the decoder's cache and are announced.
struct FirstPart<'a> {
cache: &'a dyn LayerCache,
handoff: &'a Handoff,
}
impl LayerCache for FirstPart<'_> {
fn capacity(&self) -> usize {
self.cache.capacity()
}
fn prefix(&self, layer: usize, to: usize) -> Result<(Vec<u16>, Vec<u16>), ModelError> {
self.cache.prefix(layer, to)
}
fn store(&self, layer: usize, pos0: usize, keys: &[u16], values: &[u16]) {
self.cache.store(layer, pos0, keys, values);
self.handoff.stored(layer + 1);
}
}
/// The second part's cache: reading a layer waits until the first part has stored it.
struct SecondPart<'a> {
cache: &'a dyn LayerCache,
handoff: &'a Handoff,
waited_ns: AtomicU64,
}
impl LayerCache for SecondPart<'_> {
fn capacity(&self) -> usize {
self.cache.capacity()
}
fn prefix(&self, layer: usize, to: usize) -> Result<(Vec<u16>, Vec<u16>), ModelError> {
let started = Instant::now();
self.handoff.wait_for(layer)?;
self.waited_ns
.fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed);
self.cache.prefix(layer, to)
}
fn store(&self, layer: usize, pos0: usize, keys: &[u16], values: &[u16]) {
self.cache.store(layer, pos0, keys, values);
}
}
pub struct GpuNpuPrefill {
gpu: GpuPrefill,
npu: NpuPrefill,
npu_share: f64,
split_min_tokens: usize,
memory_probe: Option<MemoryProbe>,
timings: SplitTimings,
}
impl GpuNpuPrefill {
pub fn new(gpu: GpuPrefill, npu: NpuPrefill) -> Self {
Self {
gpu,
npu,
npu_share: DEFAULT_NPU_SHARE,
split_min_tokens: DEFAULT_SPLIT_MIN_TOKENS,
memory_probe: None,
timings: SplitTimings::default(),
}
}
/// Fraction of a split prompt's tokens for the NPU (clamped to 0..=1; 0 sends every prompt to the GPU).
pub fn with_npu_share(mut self, share: f64) -> Self {
self.npu_share = share.clamp(0.0, 1.0);
self
}
/// Change the NPU share between prefills (0 sends every prompt to the GPU alone).
pub fn set_npu_share(&mut self, share: f64) {
self.npu_share = share.clamp(0.0, 1.0);
}
/// Prompts with fewer tokens to compute go to the GPU alone.
pub fn with_split_min_tokens(mut self, tokens: usize) -> Self {
self.split_min_tokens = tokens;
self
}
/// Admit a prefill only while `probe` reports room for both parts (see the two `estimate_bytes`).
pub fn with_memory_probe(mut self, probe: MemoryProbe) -> Self {
self.memory_probe = Some(probe);
self
}
pub fn timings(&self) -> &SplitTimings {
&self.timings
}
pub fn gpu(&self) -> &GpuPrefill {
&self.gpu
}
pub fn npu(&self) -> &NpuPrefill {
&self.npu
}
/// Tokens of an `n`-token prompt that go to the NPU.
pub fn npu_tokens(&self, n: usize) -> usize {
if n < self.split_min_tokens.max(2) {
return 0;
}
((n as f64 * self.npu_share).round() as usize).min(n - 1)
}
/// As [`PrefillAccelerator::prefill`], but returns the hidden state of every token; for quality evaluation.
pub fn prefill_all_hidden(
&mut self,
model: &Model,
state: &mut State,
tokens: &[u32],
pos0: usize,
) -> Result<Vec<f32>, ModelError> {
let job = PrefillJob {
model,
cache: state,
span: PrefillSpan { tokens, pos0 },
all_hidden: true,
};
Ok(self.run(job, &mut |_| true)?.expect("not cancelled"))
}
fn run(
&mut self,
job: PrefillJob,
mut progress: &mut dyn FnMut(f64) -> bool,
) -> Result<Option<Vec<f32>>, ModelError> {
let PrefillJob { model, cache, span, all_hidden } = job;
let PrefillSpan { tokens, pos0 } = span;
let started = Instant::now();
let n = tokens.len();
let s = self.npu_tokens(n);
self.timings = SplitTimings::cut_at(s, n);
let job = SplitJob::new(model, tokens, (s, pos0), all_hidden);
let handoff = Handoff::default();
let first = FirstPart {
cache,
handoff: &handoff,
};
let second = SecondPart {
cache,
handoff: &handoff,
waited_ns: AtomicU64::new(0),
};
if s == 0 {
return self.run_gpu_alone(&job, &second, &mut progress, started);
}
self.run_split(&job, (&first, &second), &mut progress, started)
}
/// A prompt too short to split: the GPU part takes every token.
fn run_gpu_alone(
&mut self,
job: &SplitJob<'_>,
second: &SecondPart<'_>,
progress: &mut impl FnMut(f64) -> bool,
started: Instant,
) -> Result<Option<Vec<f32>>, ModelError> {
let part = PrefillJob {
model: job.model,
cache: second.cache,
span: PrefillSpan { tokens: job.tokens, pos0: job.pos0 },
all_hidden: job.all_hidden,
};
let out = self.gpu.prefill_part(part, progress);
self.timings.gpu = started.elapsed();
self.timings.total = self.timings.gpu;
out
}
/// The NPU part and the GPU part at the same time, joined into the prompt's hidden state.
fn run_split(
&mut self,
job: &SplitJob<'_>,
(first, second): (&FirstPart<'_>, &SecondPart<'_>),
progress: &mut impl FnMut(f64) -> bool,
started: Instant,
) -> Result<Option<Vec<f32>>, ModelError> {
let ((npu_result, npu_time), (gpu_result, gpu_time)) =
run_parts((&mut self.npu, &mut self.gpu), job, (first, second), progress);
self.timings.npu = npu_time;
self.timings.gpu = gpu_time;
self.timings.gpu_wait = Duration::from_nanos(second.waited_ns.load(Ordering::Relaxed));
self.timings.total = started.elapsed();
// an NPU failure is the cause when the GPU part stopped waiting for it
join_hidden(npu_result?, gpu_result?, job.all_hidden)
}
}
mod split_run;
use split_run::{SplitJob, join_hidden, run_parts};
impl PrefillAccelerator for GpuNpuPrefill {
fn prefill(
&mut self,
model: &Model,
state: &mut State,
span: PrefillSpan,
progress: &mut dyn FnMut(f64) -> bool,
) -> Result<Option<Vec<f32>>, ModelError> {
let job = PrefillJob { model, cache: state, span, all_hidden: false };
let out = self.run(job, progress);
if std::env::var_os("LELEKA_SPLIT_LOG").is_some() {
eprintln!("leleka-gpu-npu: {}", self.timings.report());
}
out
}
fn admit(&mut self, model: &Model, tokens: usize) -> bool {
let Some(available) = self.memory_probe.as_ref().and_then(|probe| probe()) else {
return true; // no probe, or it cannot tell
};
let s = self.npu_tokens(tokens);
let mut needed = self.gpu.estimate_bytes(model, tokens - s);
if s > 0 {
needed += self.npu.estimate_bytes(model, s);
}
let admitted = available >= needed;
if !admitted {
eprintln!(
"leleka-gpu-npu: prefill of {tokens} tokens needs about {} MiB and {} MiB are available; using the CPU \
for this prompt",
needed >> 20,
available >> 20
);
}
admitted
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
#[test]
fn the_second_part_waits_for_each_layer_and_learns_of_an_early_end() {
let handoff = Arc::new(Handoff::default());
let h = handoff.clone();
let writer = std::thread::spawn(move || {
for layer in 0..3 {
std::thread::sleep(Duration::from_millis(20));
h.stored(layer + 1);
}
h.abandon();
});
let started = Instant::now();
handoff.wait_for(0).unwrap();
assert!(started.elapsed() >= Duration::from_millis(15));
handoff.wait_for(2).unwrap();
assert!(handoff.wait_for(3).is_err());
writer.join().unwrap();
// a stored layer stays readable after the end
handoff.wait_for(1).unwrap();
}
}