From 569e7026ed5c83dfd44d86739582b60403bd95a7 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 6 Nov 2026 17:24:36 +0100 Subject: [PATCH] STRA-338 size-fn: gpu-npu-worker: run, argument parsing and main split --- crates/gpu-npu-worker/src/lib.rs | 85 ++------ crates/gpu-npu-worker/src/main.rs | 282 +++++++++++++++---------- crates/gpu-npu-worker/src/split_run.rs | 106 ++++++++++ 3 files changed, 296 insertions(+), 177 deletions(-) create mode 100644 crates/gpu-npu-worker/src/split_run.rs diff --git a/crates/gpu-npu-worker/src/lib.rs b/crates/gpu-npu-worker/src/lib.rs index f103e53f..72cc6c05 100644 --- a/crates/gpu-npu-worker/src/lib.rs +++ b/crates/gpu-npu-worker/src/lib.rs @@ -223,94 +223,39 @@ impl GpuNpuPrefill { ..SplitTimings::default() }; if s == 0 { - let out = self - .gpu - .prefill_part(model, cache, tokens, pos0, progress, all_hidden); + let out = self.gpu.prefill_part(model, cache, tokens, pos0, progress, all_hidden); self.timings.gpu = started.elapsed(); self.timings.total = self.timings.gpu; return out; } let handoff = Handoff::default(); - let first = FirstPart { - cache, - handoff: &handoff, - }; let second = SecondPart { cache, handoff: &handoff, waited_ns: AtomicU64::new(0), }; - let stop = AtomicBool::new(false); - // the NPU part's finished fraction, in millionths - let npu_done = AtomicU64::new(0); - let (npu, gpu) = (&mut self.npu, &mut self.gpu); - let (npu_result, npu_time, gpu_result, gpu_time) = std::thread::scope(|scope| { - let npu_job = scope.spawn(|| { - let t = Instant::now(); - let result = npu.prefill_part( - model, - &first, - &tokens[..s], - pos0, - &mut |fraction| { - npu_done.store((fraction * 1e6) as u64, Ordering::Relaxed); - !stop.load(Ordering::Relaxed) - }, - all_hidden, - ); - if !matches!(result, Ok(Some(_))) { - handoff.abandon(); - } - (result, t.elapsed()) - }); - let t = Instant::now(); - let gpu_result = gpu.prefill_part( - model, - &second, - &tokens[s..], - pos0 + s, - &mut |fraction| { - let npu_fraction = npu_done.load(Ordering::Relaxed) as f64 / 1e6; - let go_on = progress(fraction.min(npu_fraction)); - if !go_on { - stop.store(true, Ordering::Relaxed); - } - go_on - }, - all_hidden, - ); - let gpu_time = t.elapsed(); - if !matches!(gpu_result, Ok(Some(_))) { - stop.store(true, Ordering::Relaxed); - } - let (npu_result, npu_time) = npu_job.join().unwrap_or_else(|_| { - ( - Err(ModelError::Invalid("the NPU part panicked".into())), - Duration::ZERO, - ) - }); - (npu_result, npu_time, gpu_result, gpu_time) - }); + let job = SplitJob { + model, + cache, + tokens, + split: s, + pos0, + all_hidden, + }; + let ((npu_result, npu_time), (gpu_result, gpu_time)) = + run_parts((&mut self.npu, &mut self.gpu), &job, (&handoff, &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 - let npu_hidden = npu_result?; - let gpu_hidden = gpu_result?; - let (Some(npu_hidden), Some(gpu_hidden)) = (npu_hidden, gpu_hidden) else { - return Ok(None); - }; - Ok(Some(if all_hidden { - let mut all = npu_hidden; - all.extend(gpu_hidden); - all - } else { - gpu_hidden - })) + join_hidden(npu_result?, gpu_result?, all_hidden) } } +mod split_run; +use split_run::{SplitJob, join_hidden, run_parts}; + impl PrefillAccelerator for GpuNpuPrefill { fn prefill( &mut self, diff --git a/crates/gpu-npu-worker/src/main.rs b/crates/gpu-npu-worker/src/main.rs index ed908181..4c7aa8dd 100644 --- a/crates/gpu-npu-worker/src/main.rs +++ b/crates/gpu-npu-worker/src/main.rs @@ -46,92 +46,147 @@ fn usage() -> &'static str { "usage: leleka-gpu-npu-worker --serve --model --openvino-root [--npu-service ] [--npu-device NPU] [--gpu-min-tokens N] [--gpu-batch N] [--npu-batch N] [--npu-share F] [--split-min-tokens N] [--threads N] [--ctx N] [--no-warm] [--seed N] [--speculate] [--cache-slots N]" } -fn parse_args() -> Result { - let mut args = std::env::args().skip(1); - let mut model = None; - let mut threads = std::thread::available_parallelism().map_or(1, |n| n.get()); - let mut context = DEFAULT_CONTEXT; - let mut warm = true; - let mut seed = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map_or(0x5EED, |d| d.as_nanos() as u64); - let mut speculate = false; - let mut cache_slots = 1usize; - let mut openvino_root = std::env::var_os("LELEKA_OPENVINO_ROOT").map(PathBuf::from); - let mut service = None; - let mut device = "NPU".to_owned(); - let mut gpu_min_tokens = DEFAULT_GPU_MIN_TOKENS; - let mut gpu_batch = leleka_gptoss_igpu::DEFAULT_BATCH; - let mut npu_batch = leleka_gptoss_npu::DEFAULT_BATCH; - let mut npu_share = DEFAULT_NPU_SHARE; - let mut split_min_tokens = DEFAULT_SPLIT_MIN_TOKENS; - let mut serving = false; - let number = |name: &str, value: Option| -> Result { - value - .and_then(|v| v.parse::().ok()) - .ok_or_else(|| format!("{name} needs a number")) - }; - while let Some(arg) = args.next() { - match arg.as_str() { - "--serve" => serving = true, - "--model" => model = Some(PathBuf::from(args.next().ok_or("--model needs a path")?)), - "--threads" => threads = number("--threads", args.next())?.max(1) as usize, - "--ctx" => context = number("--ctx", args.next())?.max(16) as usize, - "--no-warm" => warm = false, - "--speculate" => speculate = true, - "--cache-slots" => { - cache_slots = number("--cache-slots", args.next())?.clamp(1, 64) as usize - } - "--seed" => seed = number("--seed", args.next())?, - "--openvino-root" => { - openvino_root = Some(PathBuf::from( - args.next().ok_or("--openvino-root needs a path")?, - )); - } - "--npu-service" => { - service = Some(PathBuf::from( - args.next().ok_or("--npu-service needs a path")?, - )); - } - "--npu-device" => device = args.next().ok_or("--npu-device needs a name")?, - "--gpu-min-tokens" => { - gpu_min_tokens = number("--gpu-min-tokens", args.next())?.max(1) as usize; - } - "--gpu-batch" => gpu_batch = number("--gpu-batch", args.next())?.max(1) as usize, - "--npu-batch" => npu_batch = number("--npu-batch", args.next())?.max(1) as usize, +/// The options as they are read, before the required ones are checked. +struct Parsed { + model: Option, + threads: usize, + context: usize, + warm: bool, + seed: u64, + speculate: bool, + cache_slots: usize, + openvino_root: Option, + service: Option, + device: String, + gpu_min_tokens: usize, + gpu_batch: usize, + npu_batch: usize, + npu_share: f64, + split_min_tokens: usize, + serving: bool, +} + +fn number(name: &str, value: Option) -> Result { + value + .and_then(|v| v.parse::().ok()) + .ok_or_else(|| format!("{name} needs a number")) +} + +/// The path after an option. +fn path_after(name: &str, args: &mut impl Iterator) -> Result { + args.next() + .map(PathBuf::from) + .ok_or_else(|| format!("{name} needs a path")) +} + +impl Parsed { + fn new() -> Self { + Self { + model: None, + threads: std::thread::available_parallelism().map_or(1, |n| n.get()), + context: DEFAULT_CONTEXT, + warm: true, + seed: std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0x5EED, |d| d.as_nanos() as u64), + speculate: false, + cache_slots: 1, + openvino_root: std::env::var_os("LELEKA_OPENVINO_ROOT").map(PathBuf::from), + service: None, + device: "NPU".to_owned(), + gpu_min_tokens: DEFAULT_GPU_MIN_TOKENS, + gpu_batch: leleka_gptoss_igpu::DEFAULT_BATCH, + npu_batch: leleka_gptoss_npu::DEFAULT_BATCH, + npu_share: DEFAULT_NPU_SHARE, + split_min_tokens: DEFAULT_SPLIT_MIN_TOKENS, + serving: false, + } + } + + /// Take one argument, and the values that follow it from `rest`. + fn apply(&mut self, arg: &str, rest: &mut impl Iterator) -> Result<(), String> { + match arg { + "--serve" => self.serving = true, + "--no-warm" => self.warm = false, + "--speculate" => self.speculate = true, + "--model" => self.model = Some(path_after("--model", rest)?), + "--openvino-root" => self.openvino_root = Some(path_after("--openvino-root", rest)?), + "--npu-service" => self.service = Some(path_after("--npu-service", rest)?), + _ => return self.apply_number(arg, rest.next()), + } + Ok(()) + } + + /// The options that take a number (`value` is the argument after the option). + fn apply_number(&mut self, arg: &str, value: Option) -> Result<(), String> { + match arg { + "--threads" => self.threads = number("--threads", value)?.max(1) as usize, + "--ctx" => self.context = number("--ctx", value)?.max(16) as usize, + "--cache-slots" => self.cache_slots = number("--cache-slots", value)?.clamp(1, 64) as usize, + "--seed" => self.seed = number("--seed", value)?, + _ => return self.apply_accelerator(arg, value), + } + Ok(()) + } + + /// The GPU and NPU options (`value` is the argument after the option). + fn apply_accelerator(&mut self, arg: &str, value: Option) -> Result<(), String> { + match arg { + "--npu-device" => self.device = value.ok_or("--npu-device needs a name")?, + "--gpu-min-tokens" => self.gpu_min_tokens = number("--gpu-min-tokens", value)?.max(1) as usize, + "--gpu-batch" => self.gpu_batch = number("--gpu-batch", value)?.max(1) as usize, + "--npu-batch" => self.npu_batch = number("--npu-batch", value)?.max(1) as usize, + _ => return self.apply_split(arg, value), + } + Ok(()) + } + + /// The split options (`value` is the argument after the option). + fn apply_split(&mut self, arg: &str, value: Option) -> Result<(), String> { + match arg { "--npu-share" => { - npu_share = args - .next() + self.npu_share = value .and_then(|v| v.parse::().ok()) .filter(|f| (0.0..=1.0).contains(f)) .ok_or("--npu-share needs a fraction between 0 and 1")?; } - "--split-min-tokens" => { - split_min_tokens = number("--split-min-tokens", args.next())? as usize; - } + "--split-min-tokens" => self.split_min_tokens = number("--split-min-tokens", value)? as usize, other => return Err(format!("unknown argument {other}")), } + Ok(()) } - if !serving { - return Err("only --serve mode exists".into()); + + fn finish(self) -> Result { + if !self.serving { + return Err("only --serve mode exists".into()); + } + Ok(Args { + model: self.model.ok_or("--model is required")?, + threads: self.threads, + context: self.context, + warm: self.warm, + seed: self.seed, + speculate: self.speculate, + cache_slots: self.cache_slots, + openvino_root: self.openvino_root, + service: self.service, + device: self.device, + gpu_min_tokens: self.gpu_min_tokens, + gpu_batch: self.gpu_batch, + npu_batch: self.npu_batch, + npu_share: self.npu_share, + split_min_tokens: self.split_min_tokens, + }) } - Ok(Args { - model: model.ok_or("--model is required")?, - threads, - context, - warm, - seed, - speculate, - cache_slots, - openvino_root, - service, - device, - gpu_min_tokens, - gpu_batch, - npu_batch, - npu_share, - split_min_tokens, - }) +} + +fn parse_args() -> Result { + let mut args = std::env::args().skip(1); + let mut parsed = Parsed::new(); + while let Some(arg) = args.next() { + parsed.apply(&arg, &mut args)?; + } + parsed.finish() } /// The service executable next to this one, unless the caller named another. @@ -155,18 +210,23 @@ fn main() -> ExitCode { return ExitCode::from(2); } }; - let loaded = match engine::load(&LoadOptions { + let options = LoadOptions { model: &args.model, threads: args.threads, context: args.context, warm: args.warm, - }) { - Ok(loaded) => loaded, + }; + match engine::load(&options) { + Ok(loaded) => serve_with_accelerators(&args, loaded), Err(message) => { eprintln!("leleka-gpu-npu-worker: {message}"); - return ExitCode::FAILURE; + ExitCode::FAILURE } - }; + } +} + +/// Install the GPU, or the GPU and NPU split, as the prefill accelerator and serve. +fn serve_with_accelerators(args: &Args, loaded: engine::Loaded) -> ExitCode { let mut engine = loaded.engine; engine.set_speculation(args.speculate); engine.set_cache_slots(args.cache_slots); @@ -177,25 +237,22 @@ fn main() -> ExitCode { return run(&mut engine, &loaded.stop_tokens, args.seed); } }; + install_accelerator(&mut engine, gpu, args); + run(&mut engine, &loaded.stop_tokens, args.seed) +} + +/// Start the NPU service; with it the prefill is split between the GPU and the NPU, without it the GPU works alone. +fn install_accelerator(engine: &mut engine::GptOssEngine, gpu: GpuPrefill, args: &Args) { let adapter = gpu.adapter_name(); - let npu = match args.openvino_root.clone() { - None => Err("no --openvino-root (or LELEKA_OPENVINO_ROOT)".to_owned()), - Some(openvino_root) => NpuPrefill::start( - &ServiceConfig { - service: args.service.clone().unwrap_or_else(default_service), - openvino_root, - device: args.device.clone(), - model: args.model.clone(), - cache_dir: None, - }, - args.npu_batch, - ), - }; - match npu { + match start_npu(args) { Ok(npu) => { eprintln!( - "leleka-gpu-npu-worker: prompts of at least {} tokens split between the GPU ({adapter}, batch {}) and the NPU ({}, batch {}, share {}); from {} tokens the GPU alone", + concat!( + "leleka-gpu-npu-worker: prompts of at least {} tokens split between the GPU ({}, batch {}) ", + "and the NPU ({}, batch {}, share {}); from {} tokens the GPU alone" + ), args.split_min_tokens, + adapter, args.gpu_batch, npu.device_name(), args.npu_batch, @@ -214,8 +271,11 @@ fn main() -> ExitCode { } Err(e) => { eprintln!( - "leleka-gpu-npu-worker: NPU unavailable ({e}); prefilling on the GPU ({adapter}) alone from {} tokens", - args.gpu_min_tokens + concat!( + "leleka-gpu-npu-worker: NPU unavailable ({}); ", + "prefilling on the GPU ({}) alone from {} tokens" + ), + e, adapter, args.gpu_min_tokens ); engine.set_accelerator( Box::new(gpu.with_memory_probe(Box::new(available_memory))), @@ -223,17 +283,25 @@ fn main() -> ExitCode { ); } } - run(&mut engine, &loaded.stop_tokens, args.seed) +} + +/// The NPU prefill, or why there is none. +fn start_npu(args: &Args) -> Result { + let Some(openvino_root) = args.openvino_root.clone() else { + return Err("no --openvino-root (or LELEKA_OPENVINO_ROOT)".to_owned()); + }; + let config = ServiceConfig { + service: args.service.clone().unwrap_or_else(default_service), + openvino_root, + device: args.device.clone(), + model: args.model.clone(), + cache_dir: None, + }; + NpuPrefill::start(&config, args.npu_batch) } fn run(engine: &mut engine::GptOssEngine, stop_tokens: &[u32], seed: u64) -> ExitCode { - match serve( - engine, - BufReader::new(io::stdin()), - io::stdout(), - stop_tokens, - seed, - ) { + match serve(engine, BufReader::new(io::stdin()), io::stdout(), stop_tokens, seed) { Ok(()) => ExitCode::SUCCESS, Err(e) => { eprintln!("leleka-gpu-npu-worker: {e}"); diff --git a/crates/gpu-npu-worker/src/split_run.rs b/crates/gpu-npu-worker/src/split_run.rs new file mode 100644 index 00000000..050bf052 --- /dev/null +++ b/crates/gpu-npu-worker/src/split_run.rs @@ -0,0 +1,106 @@ +//! The two threads of a split prefill: the NPU part and the GPU part, run at the same time. + +#[allow(unused_imports)] +use super::*; + +/// One split prefill: the prompt tokens, where they are cut and what both parts read and write. +pub(super) struct SplitJob<'a> { + pub(super) model: &'a Model, + pub(super) cache: &'a dyn LayerCache, + pub(super) tokens: &'a [u32], + /// Tokens for the NPU part; the rest go to the GPU. + pub(super) split: usize, + pub(super) pos0: usize, + pub(super) all_hidden: bool, +} + +/// What one part of a split prefill returns, and how long it took. +type PartOutcome = (Result>, ModelError>, Duration); + +/// Run the NPU part on its own thread and the GPU part on this one, at the same time. +pub(super) fn run_parts( + (npu, gpu): (&mut NpuPrefill, &mut GpuPrefill), + job: &SplitJob<'_>, + (handoff, second): (&Handoff, &SecondPart<'_>), + progress: &mut dyn FnMut(f64) -> bool, +) -> (PartOutcome, PartOutcome) { + let first = FirstPart { + cache: job.cache, + handoff, + }; + let stop = AtomicBool::new(false); + // the NPU part's finished fraction, in millionths + let npu_done = AtomicU64::new(0); + std::thread::scope(|scope| { + let npu_job = scope.spawn(|| run_npu_part(npu, job, &first, &npu_done, &stop)); + let t = Instant::now(); + let gpu_result = gpu.prefill_part( + job.model, + second, + &job.tokens[job.split..], + job.pos0 + job.split, + &mut |fraction| { + let npu_fraction = npu_done.load(Ordering::Relaxed) as f64 / 1e6; + let go_on = progress(fraction.min(npu_fraction)); + if !go_on { + stop.store(true, Ordering::Relaxed); + } + go_on + }, + job.all_hidden, + ); + let gpu_time = t.elapsed(); + if !matches!(gpu_result, Ok(Some(_))) { + stop.store(true, Ordering::Relaxed); + } + let npu_outcome = npu_job + .join() + .unwrap_or_else(|_| (Err(ModelError::Invalid("the NPU part panicked".into())), Duration::ZERO)); + (npu_outcome, (gpu_result, gpu_time)) + }) +} + +/// The NPU part: the first tokens, announcing every stored layer; the hand-off is abandoned if it does not finish. +fn run_npu_part( + npu: &mut NpuPrefill, + job: &SplitJob<'_>, + first: &FirstPart<'_>, + npu_done: &AtomicU64, + stop: &AtomicBool, +) -> PartOutcome { + let t = Instant::now(); + let result = npu.prefill_part( + job.model, + first, + &job.tokens[..job.split], + job.pos0, + &mut |fraction| { + npu_done.store((fraction * 1e6) as u64, Ordering::Relaxed); + !stop.load(Ordering::Relaxed) + }, + job.all_hidden, + ); + if !matches!(result, Ok(Some(_))) { + first.handoff.abandon(); + } + (result, t.elapsed()) +} + +/// The hidden state of a split prefill: every token's (NPU part first), or the last one's; `None` if either part +/// stopped. +pub(super) fn join_hidden( + npu_hidden: Option>, + gpu_hidden: Option>, + all_hidden: bool, +) -> Result>, ModelError> { + let (Some(npu_hidden), Some(gpu_hidden)) = (npu_hidden, gpu_hidden) else { + return Ok(None); + }; + Ok(Some(if all_hidden { + let mut all = npu_hidden; + all.extend(gpu_hidden); + all + } else { + gpu_hidden + })) +}