From 3ebcb3ffd6e5a6635ac4a6038052fde4495781f1 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 16 Oct 2026 15:42:12 +0200 Subject: [PATCH] experiment: one prompt prefilled by the iGPU and the NPU together; measured, no gain (STRA-220) leleka-gpu-npu-worker (crates/gpu-npu-worker) splits a long prompt: the NPU path takes the first share of the tokens and the GPU path the rest, on two threads. They meet only in the KV cache, through the new leleka_gptoss::LayerCache, which both prefill paths now use instead of &mut State (same behaviour). The GPU part's cache waits for each layer the NPU part stores, so the GPU runs layer l while the NPU runs l+1. The last-token distribution matches the GPU alone (KL <= 1e-4). Measured: 2048 tokens 0.89-1.13x against the GPU alone, depending on share; agent episode (4 turns of ~2,060 new tokens, 6 alternating pairs) 0.81-1.16x per pair, a net loss. Both paths stream all weights whatever their token share and share the 15 W budget, and the NPU part's CPU attention over the growing context is the slow side. Not adopted; stays experimental. Also: NpuPrefill::with_cpu_threads, and -ArmA/-ArmB/-LogDir in Compare-PrefillWorkers.ps1. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 14 + Cargo.toml | 4 +- .../agent-episode-gpu-npu-ab-2026-10-16.jsonl | 50 +++ ...t-episode-gpu-npu-split-log-2026-10-16.txt | 19 + benchmarks/tools/Compare-PrefillWorkers.ps1 | 31 +- crates/gptoss-igpu/src/lib.rs | 23 +- crates/gptoss-npu/src/lib.rs | 30 +- crates/gptoss-npu/src/par.rs | 14 +- crates/gptoss/src/lib.rs | 37 +- crates/gpu-npu-worker/Cargo.toml | 26 ++ .../examples/dump_logprobs_split.rs | 96 +++++ .../gpu-npu-worker/examples/split_prefill.rs | 177 +++++++++ crates/gpu-npu-worker/src/lib.rs | 376 ++++++++++++++++++ crates/gpu-npu-worker/src/main.rs | 243 +++++++++++ docs/gpu-npu-prefill.md | 61 +++ docs/igpu-prefill.md | 3 + docs/npu-service.md | 2 + 17 files changed, 1172 insertions(+), 34 deletions(-) create mode 100644 benchmarks/results/agent-episode-gpu-npu-ab-2026-10-16.jsonl create mode 100644 benchmarks/results/agent-episode-gpu-npu-split-log-2026-10-16.txt create mode 100644 crates/gpu-npu-worker/Cargo.toml create mode 100644 crates/gpu-npu-worker/examples/dump_logprobs_split.rs create mode 100644 crates/gpu-npu-worker/examples/split_prefill.rs create mode 100644 crates/gpu-npu-worker/src/lib.rs create mode 100644 crates/gpu-npu-worker/src/main.rs create mode 100644 docs/gpu-npu-prefill.md diff --git a/Cargo.lock b/Cargo.lock index 29bb2cb7..59c88004 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1312,6 +1312,20 @@ dependencies = [ "leleka-shm", ] +[[package]] +name = "leleka-gpu-npu-worker" +version = "0.1.0" +dependencies = [ + "leleka-cpu-kernels", + "leleka-cpu-sys", + "leleka-cpu-worker", + "leleka-gguf", + "leleka-gptoss", + "leleka-gptoss-igpu", + "leleka-gptoss-npu", + "sysinfo", +] + [[package]] name = "leleka-harmony" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index ac84ff5c..9186004e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [workspace] resolver = "3" -members = ["crates/backend-api", "crates/cpu-kernels", "crates/cpu-sys", "crates/cpu-worker", "crates/gguf", "crates/gptoss", "crates/gptoss-igpu", "crates/harmony", "crates/igpu", "crates/kar-codec", "crates/igpu-worker", "crates/shm", "crates/openvino", "crates/npu-service", "crates/gptoss-npu", "crates/npu-worker", "crates/tokenizer", "control-plane", "desktop-core"] -default-members = ["crates/backend-api", "crates/cpu-kernels", "crates/cpu-sys", "crates/cpu-worker", "crates/gguf", "crates/gptoss", "crates/gptoss-igpu", "crates/harmony", "crates/igpu", "crates/kar-codec", "crates/igpu-worker", "crates/shm", "crates/openvino", "crates/npu-service", "crates/gptoss-npu", "crates/npu-worker", "crates/tokenizer", "control-plane", "desktop-core"] +members = ["crates/backend-api", "crates/cpu-kernels", "crates/cpu-sys", "crates/cpu-worker", "crates/gguf", "crates/gptoss", "crates/gptoss-igpu", "crates/harmony", "crates/igpu", "crates/kar-codec", "crates/igpu-worker", "crates/shm", "crates/openvino", "crates/npu-service", "crates/gptoss-npu", "crates/npu-worker", "crates/gpu-npu-worker", "crates/tokenizer", "control-plane", "desktop-core"] +default-members = ["crates/backend-api", "crates/cpu-kernels", "crates/cpu-sys", "crates/cpu-worker", "crates/gguf", "crates/gptoss", "crates/gptoss-igpu", "crates/harmony", "crates/igpu", "crates/kar-codec", "crates/igpu-worker", "crates/shm", "crates/openvino", "crates/npu-service", "crates/gptoss-npu", "crates/npu-worker", "crates/gpu-npu-worker", "crates/tokenizer", "control-plane", "desktop-core"] [workspace.package] edition = "2024" diff --git a/benchmarks/results/agent-episode-gpu-npu-ab-2026-10-16.jsonl b/benchmarks/results/agent-episode-gpu-npu-ab-2026-10-16.jsonl new file mode 100644 index 00000000..639fe3fd --- /dev/null +++ b/benchmarks/results/agent-episode-gpu-npu-ab-2026-10-16.jsonl @@ -0,0 +1,50 @@ +{"turns":4,"model":"gpt-oss-20b-MXFP4.gguf (sha256 65D06D31A3977D553CB3AF137B5C26B5F1E9297A6AAA29AE7CAA98788CDE53AB)","context":16384,"npu_share":0.5,"split_min_tokens":1024,"threads":10,"max_output":32,"arm_a":"leleka-igpu-worker","arm_b":"leleka-gpu-npu-worker","kind":"meta","tool_tokens":1500,"gpu_min_tokens":256,"date":"2026-10-16 14:53","pairs":3} +{"worker":"leleka-igpu-worker","turn":1,"wall_s":41.09,"input_tokens":2189,"cached_tokens":59,"output_tokens":32,"pair":1} +{"worker":"leleka-igpu-worker","turn":2,"wall_s":47.51,"input_tokens":4247,"cached_tokens":2189,"output_tokens":32,"pair":1} +{"worker":"leleka-igpu-worker","turn":3,"wall_s":46.81,"input_tokens":6303,"cached_tokens":4247,"output_tokens":32,"pair":1} +{"worker":"leleka-igpu-worker","turn":4,"wall_s":52.24,"input_tokens":8353,"cached_tokens":6303,"output_tokens":32,"pair":1} +{"worker":"leleka-gpu-npu-worker","turn":1,"wall_s":35.19,"input_tokens":2189,"cached_tokens":59,"output_tokens":32,"pair":1} +{"worker":"leleka-gpu-npu-worker","turn":2,"wall_s":84.24,"input_tokens":4247,"cached_tokens":2189,"output_tokens":32,"pair":1} +{"worker":"leleka-gpu-npu-worker","turn":3,"wall_s":109.58,"input_tokens":6303,"cached_tokens":4247,"output_tokens":32,"pair":1} +{"worker":"leleka-gpu-npu-worker","turn":4,"wall_s":147.81,"input_tokens":8353,"cached_tokens":6303,"output_tokens":32,"pair":1} +{"worker":"leleka-gpu-npu-worker","turn":1,"wall_s":35.5,"input_tokens":2189,"cached_tokens":59,"output_tokens":32,"pair":2} +{"worker":"leleka-gpu-npu-worker","turn":2,"wall_s":40.46,"input_tokens":4247,"cached_tokens":2189,"output_tokens":32,"pair":2} +{"worker":"leleka-gpu-npu-worker","turn":3,"wall_s":47.15,"input_tokens":6303,"cached_tokens":4247,"output_tokens":32,"pair":2} +{"worker":"leleka-gpu-npu-worker","turn":4,"wall_s":54.27,"input_tokens":8353,"cached_tokens":6303,"output_tokens":32,"pair":2} +{"worker":"leleka-igpu-worker","turn":1,"wall_s":33.99,"input_tokens":2189,"cached_tokens":59,"output_tokens":32,"pair":2} +{"worker":"leleka-igpu-worker","turn":2,"wall_s":42.13,"input_tokens":4247,"cached_tokens":2189,"output_tokens":32,"pair":2} +{"worker":"leleka-igpu-worker","turn":3,"wall_s":43.57,"input_tokens":6303,"cached_tokens":4247,"output_tokens":32,"pair":2} +{"worker":"leleka-igpu-worker","turn":4,"wall_s":50.82,"input_tokens":8353,"cached_tokens":6303,"output_tokens":32,"pair":2} +{"worker":"leleka-igpu-worker","turn":1,"wall_s":39.03,"input_tokens":2189,"cached_tokens":59,"output_tokens":32,"pair":3} +{"worker":"leleka-igpu-worker","turn":2,"wall_s":42.57,"input_tokens":4247,"cached_tokens":2189,"output_tokens":32,"pair":3} +{"worker":"leleka-igpu-worker","turn":3,"wall_s":44.53,"input_tokens":6303,"cached_tokens":4247,"output_tokens":32,"pair":3} +{"worker":"leleka-igpu-worker","turn":4,"wall_s":50,"input_tokens":8353,"cached_tokens":6303,"output_tokens":32,"pair":3} +{"worker":"leleka-gpu-npu-worker","turn":1,"wall_s":29.53,"input_tokens":2189,"cached_tokens":59,"output_tokens":32,"pair":3} +{"worker":"leleka-gpu-npu-worker","turn":2,"wall_s":33.01,"input_tokens":4247,"cached_tokens":2189,"output_tokens":32,"pair":3} +{"worker":"leleka-gpu-npu-worker","turn":3,"wall_s":42.01,"input_tokens":6303,"cached_tokens":4247,"output_tokens":32,"pair":3} +{"worker":"leleka-gpu-npu-worker","turn":4,"wall_s":47.72,"input_tokens":8353,"cached_tokens":6303,"output_tokens":32,"pair":3} +{"turns":4,"model":"gpt-oss-20b-MXFP4.gguf (sha256 65D06D31A3977D553CB3AF137B5C26B5F1E9297A6AAA29AE7CAA98788CDE53AB)","context":16384,"npu_share":0.5,"split_min_tokens":1024,"threads":10,"max_output":32,"arm_a":"leleka-igpu-worker","arm_b":"leleka-gpu-npu-worker","kind":"meta","tool_tokens":1500,"gpu_min_tokens":256,"date":"2026-10-16 15:16","pairs":3} +{"worker":"leleka-igpu-worker","turn":1,"wall_s":40.23,"input_tokens":2189,"cached_tokens":59,"output_tokens":32,"pair":1} +{"worker":"leleka-igpu-worker","turn":2,"wall_s":47.69,"input_tokens":4247,"cached_tokens":2189,"output_tokens":32,"pair":1} +{"worker":"leleka-igpu-worker","turn":3,"wall_s":54.06,"input_tokens":6303,"cached_tokens":4247,"output_tokens":32,"pair":1} +{"worker":"leleka-igpu-worker","turn":4,"wall_s":60.32,"input_tokens":8353,"cached_tokens":6303,"output_tokens":32,"pair":1} +{"worker":"leleka-gpu-npu-worker","turn":1,"wall_s":44.21,"input_tokens":2189,"cached_tokens":59,"output_tokens":32,"pair":1} +{"worker":"leleka-gpu-npu-worker","turn":2,"wall_s":45.21,"input_tokens":4247,"cached_tokens":2189,"output_tokens":32,"pair":1} +{"worker":"leleka-gpu-npu-worker","turn":3,"wall_s":55.48,"input_tokens":6303,"cached_tokens":4247,"output_tokens":32,"pair":1} +{"worker":"leleka-gpu-npu-worker","turn":4,"wall_s":65.02,"input_tokens":8353,"cached_tokens":6303,"output_tokens":32,"pair":1} +{"worker":"leleka-gpu-npu-worker","turn":1,"wall_s":43.62,"input_tokens":2189,"cached_tokens":59,"output_tokens":32,"pair":2} +{"worker":"leleka-gpu-npu-worker","turn":2,"wall_s":48.45,"input_tokens":4247,"cached_tokens":2189,"output_tokens":32,"pair":2} +{"worker":"leleka-gpu-npu-worker","turn":3,"wall_s":56.59,"input_tokens":6303,"cached_tokens":4247,"output_tokens":32,"pair":2} +{"worker":"leleka-gpu-npu-worker","turn":4,"wall_s":65.5,"input_tokens":8353,"cached_tokens":6303,"output_tokens":32,"pair":2} +{"worker":"leleka-igpu-worker","turn":1,"wall_s":38.9,"input_tokens":2189,"cached_tokens":59,"output_tokens":32,"pair":2} +{"worker":"leleka-igpu-worker","turn":2,"wall_s":42.57,"input_tokens":4247,"cached_tokens":2189,"output_tokens":32,"pair":2} +{"worker":"leleka-igpu-worker","turn":3,"wall_s":46.74,"input_tokens":6303,"cached_tokens":4247,"output_tokens":32,"pair":2} +{"worker":"leleka-igpu-worker","turn":4,"wall_s":50.03,"input_tokens":8353,"cached_tokens":6303,"output_tokens":32,"pair":2} +{"worker":"leleka-igpu-worker","turn":1,"wall_s":32.73,"input_tokens":2189,"cached_tokens":59,"output_tokens":32,"pair":3} +{"worker":"leleka-igpu-worker","turn":2,"wall_s":40.48,"input_tokens":4247,"cached_tokens":2189,"output_tokens":32,"pair":3} +{"worker":"leleka-igpu-worker","turn":3,"wall_s":46.94,"input_tokens":6303,"cached_tokens":4247,"output_tokens":32,"pair":3} +{"worker":"leleka-igpu-worker","turn":4,"wall_s":53.16,"input_tokens":8353,"cached_tokens":6303,"output_tokens":32,"pair":3} +{"worker":"leleka-gpu-npu-worker","turn":1,"wall_s":44.69,"input_tokens":2189,"cached_tokens":59,"output_tokens":32,"pair":3} +{"worker":"leleka-gpu-npu-worker","turn":2,"wall_s":47.42,"input_tokens":4247,"cached_tokens":2189,"output_tokens":32,"pair":3} +{"worker":"leleka-gpu-npu-worker","turn":3,"wall_s":56.5,"input_tokens":6303,"cached_tokens":4247,"output_tokens":32,"pair":3} +{"worker":"leleka-gpu-npu-worker","turn":4,"wall_s":65.81,"input_tokens":8353,"cached_tokens":6303,"output_tokens":32,"pair":3} diff --git a/benchmarks/results/agent-episode-gpu-npu-split-log-2026-10-16.txt b/benchmarks/results/agent-episode-gpu-npu-split-log-2026-10-16.txt new file mode 100644 index 00000000..d7c1a30a --- /dev/null +++ b/benchmarks/results/agent-episode-gpu-npu-split-log-2026-10-16.txt @@ -0,0 +1,19 @@ +# split prefill (leleka-gpu-npu-worker) logs of run 2, agent episode, 2026-10-16 +# LELEKA_SPLIT_LOG lines per turn (npu tokens + gpu tokens); model/hardware as in agent-episode-gpu-npu-ab-2026-10-16.jsonl +pair 1: +leleka-gpu-npu: 1065 + 1065 tokens in 38.66 s: npu part 34.52 s | gpu part 38.66 s, of which waiting for the npu 2.51 s +leleka-gpu-npu: 1029 + 1029 tokens in 41.14 s: npu part 39.47 s | gpu part 41.13 s, of which waiting for the npu 6.12 s +leleka-gpu-npu: 1028 + 1028 tokens in 49.95 s: npu part 46.30 s | gpu part 49.95 s, of which waiting for the npu 4.05 s +leleka-gpu-npu: 1025 + 1025 tokens in 60.43 s: npu part 57.48 s | gpu part 60.43 s, of which waiting for the npu 6.25 s +pair 2: +leleka-gpu-npu: 1065 + 1065 tokens in 39.41 s: npu part 38.08 s | gpu part 39.41 s, of which waiting for the npu 10.65 s +leleka-gpu-npu: 1029 + 1029 tokens in 44.22 s: npu part 42.43 s | gpu part 44.22 s, of which waiting for the npu 7.55 s +leleka-gpu-npu: 1028 + 1028 tokens in 52.47 s: npu part 50.62 s | gpu part 52.47 s, of which waiting for the npu 7.86 s +leleka-gpu-npu: 1025 + 1025 tokens in 60.10 s: npu part 58.35 s | gpu part 60.10 s, of which waiting for the npu 6.34 s +pair 3: +leleka-gpu-npu: 1065 + 1065 tokens in 40.85 s: npu part 38.78 s | gpu part 40.85 s, of which waiting for the npu 12.33 s +leleka-gpu-npu: 1029 + 1029 tokens in 43.01 s: npu part 40.22 s | gpu part 43.01 s, of which waiting for the npu 6.35 s +leleka-gpu-npu: 1028 + 1028 tokens in 51.75 s: npu part 48.28 s | gpu part 51.75 s, of which waiting for the npu 2.62 s +leleka-gpu-npu: 1025 + 1025 tokens in 61.07 s: npu part 58.89 s | gpu part 61.07 s, of which waiting for the npu 6.67 s + +# run 1 (no logs): pair 1 of the split arm took 35.2, 84.2, 109.6, 147.8 s per turn; cause not captured, not reproduced in run 2 diff --git a/benchmarks/tools/Compare-PrefillWorkers.ps1 b/benchmarks/tools/Compare-PrefillWorkers.ps1 index a3ff61b2..49081b4a 100644 --- a/benchmarks/tools/Compare-PrefillWorkers.ps1 +++ b/benchmarks/tools/Compare-PrefillWorkers.ps1 @@ -1,6 +1,7 @@ <# .SYNOPSIS - Paired, alternating comparison of the CPU worker and the GPU-prefill worker on an agent-shaped episode, + Paired, alternating comparison of two workers (default: the CPU worker and the GPU-prefill worker; -ArmA/-ArmB + choose others, such as leleka-gpu-npu-worker with -OpenvinoRoot) on an agent-shaped episode, through the control plane's /v1/responses. .DESCRIPTION @@ -27,7 +28,15 @@ param( [int] $ToolTokens = 1500, [int] $MaxOutput = 32, [int] $Pairs = 3, - [int] $GpuMinTokens = 256 + [int] $GpuMinTokens = 256, + [string] $ArmA = 'leleka-cpu-worker', + [string] $ArmB = 'leleka-igpu-worker', + [string] $OpenvinoRoot = $env:LELEKA_OPENVINO_ROOT, + [double] $NpuShare = 0.45, + [int] $SplitMinTokens = 1024, + # keep each arm's control-plane and worker standard error here (as -pair

.err.txt); also turns on + # the GPU+NPU worker's split timing log + [string] $LogDir ) $ErrorActionPreference = 'Stop' if (-not $RepoRoot) { $RepoRoot = (Resolve-Path (Join-Path (Split-Path -Parent $MyInvocation.MyCommand.Path) '..\..')).Path } @@ -55,7 +64,11 @@ function Start-Arm([string]$worker) { $work = Join-Path ([IO.Path]::GetTempPath()) ("leleka-ab-" + [Guid]::NewGuid().ToString('N')) New-Item -ItemType Directory $work | Out-Null $workerArgs = @('--model', $Model, '--ctx', "$Context", '--threads', "$Threads") - if ($worker -eq 'leleka-igpu-worker') { $workerArgs += @('--gpu-min-tokens', "$GpuMinTokens") } + if ($worker -in 'leleka-igpu-worker', 'leleka-gpu-npu-worker') { $workerArgs += @('--gpu-min-tokens', "$GpuMinTokens") } + if ($worker -in 'leleka-npu-worker', 'leleka-gpu-npu-worker') { $workerArgs += @('--openvino-root', $OpenvinoRoot) } + if ($worker -eq 'leleka-gpu-npu-worker') { + $workerArgs += @('--npu-share', "$NpuShare", '--split-min-tokens', "$SplitMinTokens") + } $config = @{ bind = "127.0.0.1:$Port"; model = 'gpt-oss-20b' engine = @{ executable = (Join-Path $bin "$worker.exe"); args = $workerArgs; gptoss_gguf = $Model startup_timeout_s = 300; generation_timeout_s = 1200 } } | ConvertTo-Json -Depth 5 @@ -69,13 +82,16 @@ function Start-Arm([string]$worker) { try { if ((Invoke-WebRequest "http://127.0.0.1:$Port/ready" -UseBasicParsing -TimeoutSec 3).StatusCode -eq 200) { $ready = $true; break } } catch {} } if (-not $ready) { throw "not ready; see $work\err.txt" } - [pscustomobject]@{ Server = $server; Work = $work } + [pscustomobject]@{ Server = $server; Work = $work; Worker = $worker; Pair = $script:pair } } function Stop-Arm($arm) { Get-CimInstance Win32_Process -Filter "ParentProcessId=$($arm.Server.Id)" -ErrorAction SilentlyContinue | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue } if (-not $arm.Server.HasExited) { Stop-Process $arm.Server -Force } Start-Sleep 2 + if ($LogDir) { + Copy-Item (Join-Path $arm.Work 'err.txt') (Join-Path $LogDir "$($arm.Worker)-pair$($arm.Pair).err.txt") -ErrorAction SilentlyContinue + } Remove-Item $arm.Work -Recurse -Force -ErrorAction SilentlyContinue } function Send([object]$body) { @@ -104,10 +120,13 @@ function Run-Episode([string]$worker) { } $meta = @{ kind = 'meta'; date = (Get-Date -Format 'yyyy-MM-dd HH:mm'); model = $Model; turns = $Turns; tool_tokens = $ToolTokens - max_output = $MaxOutput; pairs = $Pairs; context = $Context; threads = $Threads; gpu_min_tokens = $GpuMinTokens } + max_output = $MaxOutput; pairs = $Pairs; context = $Context; threads = $Threads; gpu_min_tokens = $GpuMinTokens + arm_a = $ArmA; arm_b = $ArmB; npu_share = $NpuShare; split_min_tokens = $SplitMinTokens } ($meta | ConvertTo-Json -Compress) | Add-Content $Output +if ($LogDir) { New-Item -ItemType Directory -Force $LogDir | Out-Null; $env:LELEKA_SPLIT_LOG = '1' } foreach ($p in 1..$Pairs) { - $order = if ($p % 2 -eq 1) { 'leleka-cpu-worker', 'leleka-igpu-worker' } else { 'leleka-igpu-worker', 'leleka-cpu-worker' } + $script:pair = $p + $order = if ($p % 2 -eq 1) { $ArmA, $ArmB } else { $ArmB, $ArmA } foreach ($w in $order) { "pair $p, $w" foreach ($row in (Run-Episode $w)) { diff --git a/crates/gptoss-igpu/src/lib.rs b/crates/gptoss-igpu/src/lib.rs index b140c1d1..1cb26f8c 100644 --- a/crates/gptoss-igpu/src/lib.rs +++ b/crates/gptoss-igpu/src/lib.rs @@ -13,8 +13,8 @@ //! passes (`benchmarks/quality`). use leleka_gptoss::{ - Kind, LayerView, Model, ModelError, PrefillAccelerator, SWIGLU_ALPHA, SWIGLU_LIMIT, State, - WeightView, + Kind, LayerCache, LayerView, Model, ModelError, PrefillAccelerator, SWIGLU_ALPHA, SWIGLU_LIMIT, + State, WeightView, }; use leleka_igpu::{ AttentionShape, Buf, Gpu, GpuActivations, GpuError, GpuMatrix, SwigluParams, WeightKind, @@ -264,7 +264,7 @@ impl PrefillAccelerator for GpuPrefill { pos0: usize, progress: &mut dyn FnMut(f64) -> bool, ) -> Result>, ModelError> { - self.run(model, state, tokens, pos0, progress, false) + self.prefill_part(model, state, tokens, pos0, progress, false) } fn admit(&mut self, model: &Model, tokens: usize) -> bool { let Some(probe) = self.memory_probe.as_ref() else { @@ -298,14 +298,17 @@ impl GpuPrefill { pos0: usize, ) -> Result, ModelError> { Ok(self - .run(model, state, tokens, pos0, &mut |_| true, true)? + .prefill_part(model, state, tokens, pos0, &mut |_| true, true)? .expect("not cancelled")) } - fn run( + /// Prefill `tokens` at positions `pos0..` reading the earlier rows from and storing this run's rows into `cache` + /// layer by layer; returns the hidden state of the last token (of every token with `all_hidden`), or `None` + /// when `progress` asked to stop. [`PrefillAccelerator::prefill`] is this with the decoder's own cache. + pub fn prefill_part( &mut self, model: &Model, - state: &mut State, + cache: &dyn LayerCache, tokens: &[u32], pos0: usize, progress: &mut dyn FnMut(f64) -> bool, @@ -320,10 +323,10 @@ impl GpuPrefill { let c = &model.config; let (e, hd, qw, kw, ff) = (c.n_embd, c.head_dim, c.q_width(), c.kv_width(), c.n_ff); let n = tokens.len(); - if n == 0 || pos0 + n > state.capacity() { + if n == 0 || pos0 + n > cache.capacity() { return Err(ModelError::ContextFull { position: pos0 + n, - capacity: state.capacity(), + capacity: cache.capacity(), }); } let gpu = &self.gpu; @@ -380,7 +383,7 @@ impl GpuPrefill { ModelError::Invalid("the weight upload thread ended early".into()) })??; if pos0 > 0 { - let (k, v) = state.kv_rows(l, 0, pos0); + let (k, v) = cache.prefix(l, pos0)?; gpu.write_u32(&kcache, 0, &pack_halves(&k)) .map_err(gpu_error)?; gpu.write_u32(&vcache, 0, &pack_halves(&v)) @@ -464,7 +467,7 @@ impl GpuPrefill { let words = n * kw / 2; let keys = gpu.read_u32_at(&kcache, first, words).map_err(gpu_error)?; let values = gpu.read_u32_at(&vcache, first, words).map_err(gpu_error)?; - state.store_kv(l, pos0, &unpack_halves(&keys), &unpack_halves(&values)); + cache.store(l, pos0, &unpack_halves(&keys), &unpack_halves(&values)); self.timings.readback += t3.elapsed(); if !progress((l + 1) as f64 / c.blocks as f64) { return Ok(false); diff --git a/crates/gptoss-npu/src/lib.rs b/crates/gptoss-npu/src/lib.rs index c6a4fa3b..18e58f56 100644 --- a/crates/gptoss-npu/src/lib.rs +++ b/crates/gptoss-npu/src/lib.rs @@ -17,7 +17,8 @@ mod par; 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, + LayerCache, LayerView, Model, ModelError, PrefillAccelerator, SWIGLU_ALPHA, SWIGLU_LIMIT, + State, ops, }; use std::time::{Duration, Instant}; @@ -127,6 +128,14 @@ impl NpuPrefill { self } + /// Run the CPU part of the NPU prefill (attention, activation, conversions) on at most `threads` threads (0: all + /// cores; the default). The limit is process-wide. Leaving cores free matters when the GPU prefill runs at the + /// same time, since its driver and weight-repacking threads need the CPU too. + pub fn with_cpu_threads(self, threads: usize) -> Self { + par::set_threads(threads); + 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 { @@ -166,7 +175,7 @@ impl NpuPrefill { pos0: usize, ) -> Result, ModelError> { Ok(self - .run(model, state, tokens, pos0, &mut |_| true, true)? + .prefill_part(model, state, tokens, pos0, &mut |_| true, true)? .expect("not cancelled")) } @@ -256,10 +265,13 @@ impl NpuPrefill { Ok(()) } - fn run( + /// Prefill `tokens` at positions `pos0..` reading the earlier rows from and storing this run's rows into `cache` + /// layer by layer; returns the hidden state of the last token (of every token with `all_hidden`), or `None` + /// when `progress` asked to stop. [`PrefillAccelerator::prefill`] is this with the decoder's own cache. + pub fn prefill_part( &mut self, model: &Model, - state: &mut State, + cache: &dyn LayerCache, tokens: &[u32], pos0: usize, progress: &mut dyn FnMut(f64) -> bool, @@ -273,10 +285,10 @@ impl NpuPrefill { let c = &model.config; let (e, hd, qw, kw, ff) = (c.n_embd, c.head_dim, c.q_width(), c.kv_width(), c.n_ff); let n = tokens.len(); - if n == 0 || pos0 + n > state.capacity() { + if n == 0 || pos0 + n > cache.capacity() { return Err(ModelError::ContextFull { position: pos0 + n, - capacity: state.capacity(), + capacity: cache.capacity(), }); } for (width, limit) in [(e, 3072), (ff, 3072), (qw, 4096)] { @@ -315,7 +327,7 @@ impl NpuPrefill { let mut kc = vec![0u16; positions * kw]; let mut vc = vec![0u16; positions * kw]; if pos0 > 0 { - let (k, v) = state.kv_rows(l, 0, pos0); + let (k, v) = cache.prefix(l, pos0)?; kc[..pos0 * kw].copy_from_slice(&k); vc[..pos0 * kw].copy_from_slice(&v); } @@ -513,7 +525,7 @@ impl NpuPrefill { self.timings.part(4, t5.elapsed()); } - state.store_kv(l, pos0, &kc[pos0 * kw..], &vc[pos0 * kw..]); + cache.store(l, pos0, &kc[pos0 * kw..], &vc[pos0 * kw..]); if !progress((l + 1) as f64 / c.blocks as f64) { self.timings.total = started.elapsed(); return Ok(None); @@ -717,7 +729,7 @@ impl PrefillAccelerator for NpuPrefill { pos0: usize, progress: &mut dyn FnMut(f64) -> bool, ) -> Result>, ModelError> { - self.run(model, state, tokens, pos0, progress, false) + self.prefill_part(model, state, tokens, pos0, progress, false) } fn admit(&mut self, model: &Model, tokens: usize) -> bool { diff --git a/crates/gptoss-npu/src/par.rs b/crates/gptoss-npu/src/par.rs index f0b42cd9..ed02c540 100644 --- a/crates/gptoss-npu/src/par.rs +++ b/crates/gptoss-npu/src/par.rs @@ -2,8 +2,20 @@ use std::sync::atomic::{AtomicUsize, Ordering}; +/// Threads the helpers use; 0 means all cores. +static LIMIT: AtomicUsize = AtomicUsize::new(0); + +/// Use at most `n` threads in this process from now on (0: all cores). +pub fn set_threads(n: usize) { + LIMIT.store(n, Ordering::Relaxed); +} + pub fn threads() -> usize { - std::thread::available_parallelism().map_or(1, |n| n.get()) + let all = std::thread::available_parallelism().map_or(1, |n| n.get()); + match LIMIT.load(Ordering::Relaxed) { + 0 => all, + n => n.min(all), + } } /// Split `data` into chunks of `chunk` elements and run `f(chunk index, chunk)` over them on all cores. diff --git a/crates/gptoss/src/lib.rs b/crates/gptoss/src/lib.rs index a5c5fe33..77768b7f 100644 --- a/crates/gptoss/src/lib.rs +++ b/crates/gptoss/src/lib.rs @@ -877,12 +877,7 @@ impl State { /// Store keys and values (`[position][kv_width]` halves) of `layer` for positions `pos0..`. The cached /// token list is not changed: call [`State::set_cached_tokens`] once all layers are in. pub fn store_kv(&mut self, layer: usize, pos0: usize, keys: &[u16], values: &[u16]) { - let mut k = self.k[layer].write().expect("KV cache lock"); - let width = k.len() / self.capacity; - debug_assert!(keys.len() == values.len() && keys.len().is_multiple_of(width)); - k[pos0 * width..pos0 * width + keys.len()].copy_from_slice(keys); - self.v[layer].write().expect("KV cache lock")[pos0 * width..pos0 * width + values.len()] - .copy_from_slice(values); + LayerCache::store(self, layer, pos0, keys, values); } /// Record that the cache holds exactly `tokens` (their keys and values were stored by the caller). @@ -898,6 +893,36 @@ impl State { } } +/// The key and value cache as a layer-by-layer prefill on other hardware sees it: it reads the rows before its +/// tokens one layer at a time and stores its own rows when a layer is done. [`State`] is one; a prefill split +/// between two devices gives the second a cache that waits until the first has stored the layer it needs. +pub trait LayerCache: Sync { + fn capacity(&self) -> usize; + /// Keys and values of `layer` at positions `0..to` (`[position][kv_width]` halves). + fn prefix(&self, layer: usize, to: usize) -> Result<(Vec, Vec), ModelError>; + /// Store keys and values of `layer` for positions `pos0..` (as [`State::store_kv`]). + fn store(&self, layer: usize, pos0: usize, keys: &[u16], values: &[u16]); +} + +impl LayerCache for State { + fn capacity(&self) -> usize { + self.capacity + } + + fn prefix(&self, layer: usize, to: usize) -> Result<(Vec, Vec), ModelError> { + Ok(self.kv_rows(layer, 0, to)) + } + + fn store(&self, layer: usize, pos0: usize, keys: &[u16], values: &[u16]) { + let mut k = self.k[layer].write().expect("KV cache lock"); + let width = k.len() / self.capacity; + debug_assert!(keys.len() == values.len() && keys.len().is_multiple_of(width)); + k[pos0 * width..pos0 * width + keys.len()].copy_from_slice(keys); + self.v[layer].write().expect("KV cache lock")[pos0 * width..pos0 * width + values.len()] + .copy_from_slice(values); + } +} + /// A prefill that runs on other hardware (the integrated GPU). It runs `tokens` at positions `pos0..` /// through all layers, stores their keys and values into `state` (it must not change the cached token list), /// and returns the hidden state of the last token, or `None` when `progress` (given the finished fraction diff --git a/crates/gpu-npu-worker/Cargo.toml b/crates/gpu-npu-worker/Cargo.toml new file mode 100644 index 00000000..12d16265 --- /dev/null +++ b/crates/gpu-npu-worker/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name = "leleka-gpu-npu-worker" +version = "0.1.0" +description = "Leleka inference worker that prefills one long prompt on the integrated GPU and the NPU at the same time: the CPU worker's decoder, the GPU prefill and the NPU service client (experimental)" +edition.workspace = true +license.workspace = true +rust-version.workspace = true + +[[bin]] +name = "leleka-gpu-npu-worker" +path = "src/main.rs" + +[dependencies] +leleka-cpu-worker = { path = "../cpu-worker" } +leleka-gptoss = { path = "../gptoss" } +leleka-gptoss-igpu = { path = "../gptoss-igpu" } +leleka-gptoss-npu = { path = "../gptoss-npu" } +sysinfo = { version = "0.39.6", default-features = false, features = ["system"] } + +[dev-dependencies] +leleka-cpu-kernels = { path = "../cpu-kernels" } +leleka-cpu-sys = { path = "../cpu-sys" } +leleka-gguf = { path = "../gguf" } + +[lints] +workspace = true diff --git a/crates/gpu-npu-worker/examples/dump_logprobs_split.rs b/crates/gpu-npu-worker/examples/dump_logprobs_split.rs new file mode 100644 index 00000000..77f293d5 --- /dev/null +++ b/crates/gpu-npu-worker/examples/dump_logprobs_split.rs @@ -0,0 +1,96 @@ +//! Teacher-forced log-probabilities with the prompt prefilled by the NPU and the GPU together (the first `share` of +//! the tokens through the NPU service, the rest on the GPU): the format of `dump_logprobs`, for `compare_logprobs`. +//! Every position's hidden state comes from the split prefill; the output projection runs on the CPU. +//! +//! Run: `cargo run --release -p leleka-gpu-npu-worker --example dump_logprobs_split -- [top_n] [npu share]` + +use leleka_cpu_kernels::Dispatch; +use leleka_cpu_sys::mapping::Mapping; +use leleka_gguf::Gguf; +use leleka_gptoss::{Model, State}; +use leleka_gptoss_igpu::GpuPrefill; +use leleka_gptoss_npu::NpuPrefill; +use leleka_gptoss_npu::client::ServiceConfig; +use leleka_gpu_npu_worker::{DEFAULT_NPU_SHARE, GpuNpuPrefill}; +use std::fs::File; +use std::io::{BufReader, BufWriter, Write}; +use std::path::Path; + +fn main() { + let args: Vec = std::env::args().skip(1).collect(); + if args.len() < 6 { + eprintln!( + "usage: dump_logprobs_split [top_n] [npu share]" + ); + std::process::exit(2); + } + let ids: Vec = std::fs::read_to_string(&args[4]) + .expect("ids file") + .trim() + .split(',') + .map(|s| s.trim().parse().expect("token id")) + .collect(); + let top_n: usize = args.get(6).and_then(|s| s.parse().ok()).unwrap_or(20); + let share: f64 = args + .get(7) + .and_then(|s| s.parse().ok()) + .unwrap_or(DEFAULT_NPU_SHARE); + let path = Path::new(&args[0]); + let size = std::fs::metadata(path).expect("model file").len(); + let gguf = Gguf::read( + BufReader::with_capacity(1 << 20, File::open(path).expect("open")), + size, + ) + .expect("valid GGUF"); + let model = Model::load( + std::sync::Arc::new(Mapping::open(path).expect("map model")), + &gguf, + Dispatch::from_env().expect("kernel level"), + std::thread::available_parallelism().map_or(1, |n| n.get()), + ) + .expect("load model"); + let e = model.config.n_embd; + let mut state = State::new(&model.config, ids.len() + 1); + let config = ServiceConfig { + service: args[2].clone().into(), + openvino_root: args[1].clone().into(), + device: args[3].clone(), + model: path.to_path_buf(), + cache_dir: None, + }; + let npu = NpuPrefill::start(&config, leleka_gptoss_npu::DEFAULT_BATCH) + .expect("start the NPU service"); + let mut accel = GpuNpuPrefill::new(GpuPrefill::new().expect("a GPU"), npu) + .with_npu_share(share) + .with_split_min_tokens(2); + let hidden = accel + .prefill_all_hidden(&model, &mut state, &ids, 0) + .expect("split prefill"); + eprintln!("{}", accel.timings().report()); + let mut out = BufWriter::new(File::create(&args[5]).expect("output file")); + for pos in 0..ids.len() { + model + .next_from_hidden(&mut state, &hidden[pos * e..(pos + 1) * e]) + .expect("output projection"); + let logits = &state.logits; + let max = logits.iter().copied().fold(f32::NEG_INFINITY, f32::max); + let z: f64 = logits.iter().map(|l| f64::from(l - max).exp()).sum(); + let mut order: Vec = (0..logits.len()).collect(); + order.sort_by(|a, b| logits[*b].total_cmp(&logits[*a]).then(a.cmp(b))); + let top: Vec = order + .iter() + .take(top_n) + .map(|i| format!("[{},{:.6}]", i, f64::from(logits[*i] - max) - z.ln())) + .collect(); + let next = ids + .get(pos + 1) + .map_or("null".to_owned(), |n| n.to_string()); + writeln!( + out, + "{{\"pos\":{pos},\"next\":{next},\"top\":[{}]}}", + top.join(",") + ) + .expect("write"); + } + eprintln!("wrote {} positions", ids.len()); +} diff --git a/crates/gpu-npu-worker/examples/split_prefill.rs b/crates/gpu-npu-worker/examples/split_prefill.rs new file mode 100644 index 00000000..f674cbac --- /dev/null +++ b/crates/gpu-npu-worker/examples/split_prefill.rs @@ -0,0 +1,177 @@ +//! Time one prompt's prefill on the GPU alone and split between the NPU and the GPU, alternating, and compare what +//! the two leave behind (the last token's distribution). With `prefix > 0` the first `prefix` tokens are prefilled +//! on the GPU first (untimed) and the rest is timed at positions `prefix..`, as the later turns of an agent episode +//! reuse their earlier context. Correctness and speed probe; machine state is not controlled. +//! +//! Run: `cargo run --release -p leleka-gpu-npu-worker --example split_prefill -- +//! [rounds] [npu share] [prefix] [gpu batch] [npu batch]` +//! `LELEKA_NPU_CPU_THREADS=N` caps the threads of the NPU part's CPU work (default: all cores). + +use leleka_cpu_kernels::Dispatch; +use leleka_cpu_sys::mapping::Mapping; +use leleka_gguf::Gguf; +use leleka_gptoss::{Model, PrefillAccelerator, State}; +use leleka_gptoss_igpu::GpuPrefill; +use leleka_gptoss_npu::NpuPrefill; +use leleka_gptoss_npu::client::ServiceConfig; +use leleka_gpu_npu_worker::{DEFAULT_NPU_SHARE, GpuNpuPrefill}; +use std::fs::File; +use std::io::BufReader; +use std::path::Path; +use std::time::Instant; + +fn log_softmax(logits: &[f32]) -> Vec { + let max = logits.iter().copied().fold(f32::NEG_INFINITY, f32::max); + let z: f64 = logits.iter().map(|l| f64::from(l - max).exp()).sum(); + logits.iter().map(|l| f64::from(l - max) - z.ln()).collect() +} + +fn main() { + let args: Vec = std::env::args().skip(1).collect(); + if args.len() < 5 { + eprintln!( + "usage: split_prefill [rounds] [npu share] [prefix] [gpu batch] [npu batch]" + ); + std::process::exit(2); + } + let ids: Vec = if let Some(n) = args[4].strip_prefix("synth:") { + let mut s = 0x2545_F491_4F6C_DD1Du64; + (0..n.parse::().expect("synth:N")) + .map(|_| { + s ^= s << 13; + s ^= s >> 7; + s ^= s << 17; + 1000 + (s % 60_000) as u32 + }) + .collect() + } else { + std::fs::read_to_string(&args[4]) + .expect("ids file") + .trim() + .split(',') + .map(|s| s.trim().parse().expect("token id")) + .collect() + }; + let num = |i: usize, d: usize| args.get(i).and_then(|s| s.parse().ok()).unwrap_or(d); + let rounds = num(5, 2); + let share: f64 = args + .get(6) + .and_then(|s| s.parse().ok()) + .unwrap_or(DEFAULT_NPU_SHARE); + let prefix = num(7, 0).min(ids.len().saturating_sub(1)); + let gpu_batch = num(8, leleka_gptoss_igpu::DEFAULT_BATCH); + let npu_batch = num(9, leleka_gptoss_npu::DEFAULT_BATCH); + let path = Path::new(&args[0]); + let size = std::fs::metadata(path).expect("model file").len(); + let gguf = Gguf::read( + BufReader::with_capacity(1 << 20, File::open(path).expect("open")), + size, + ) + .expect("valid GGUF"); + let map = Mapping::open(path).expect("map model"); + map.touch_pages(); + let model = Model::load( + std::sync::Arc::new(map), + &gguf, + Dispatch::from_env().expect("kernel level"), + std::thread::available_parallelism().map_or(1, |n| n.get()), + ) + .expect("load model"); + let npu = NpuPrefill::start( + &ServiceConfig { + service: args[2].clone().into(), + openvino_root: args[1].clone().into(), + device: args[3].clone(), + model: path.to_path_buf(), + cache_dir: None, + }, + npu_batch, + ) + .expect("start the NPU service"); + let npu_threads = std::env::var("LELEKA_NPU_CPU_THREADS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(0); + let npu = npu.with_cpu_threads(npu_threads); + let gpu = GpuPrefill::new().expect("a GPU").with_batch(gpu_batch); + let mut split = GpuNpuPrefill::new(gpu, npu).with_split_min_tokens(2); + let rest = &ids[prefix..]; + println!( + "{} tokens after a prefix of {prefix}; npu share {share} ({} tokens); gpu batch {gpu_batch}, npu batch {npu_batch}", + rest.len(), + ((rest.len() as f64 * share).round() as usize).min(rest.len() - 1) + ); + let mut run = |npu_share: f64, warm: bool| -> (f64, u32, Vec) { + let mut state = State::new(&model.config, ids.len() + 1); + if prefix > 0 { + split.set_npu_share(0.0); + split + .prefill(&model, &mut state, &ids[..prefix], 0, &mut |_| true) + .expect("prefix") + .expect("not cancelled"); + } + split.set_npu_share(npu_share); + let t = Instant::now(); + let hidden = split + .prefill(&model, &mut state, rest, prefix, &mut |_| true) + .expect("prefill") + .expect("not cancelled"); + let seconds = t.elapsed().as_secs_f64(); + if !warm { + println!(" gpu: {}", split.gpu().timings().report()); + } + let next = model + .next_from_hidden(&mut state, &hidden) + .expect("output projection"); + if !warm && npu_share > 0.0 { + println!(" {}", split.timings().report()); + println!(" npu: {}", split.npu().timings().report()); + } + (seconds, next, log_softmax(&state.logits)) + }; + // one untimed run of each first: graphs, pipelines and caches + run(0.0, true); + run(share, true); + let (mut gpu_times, mut split_times) = (Vec::new(), Vec::new()); + for r in 0..rounds { + let order = if r % 2 == 0 { + [0.0, share] + } else { + [share, 0.0] + }; + let mut results = Vec::new(); + for s in order { + let (seconds, next, lp) = run(s, false); + let rate = rest.len() as f64 / seconds; + println!( + "round {r} {}: {seconds:.2} s ({rate:.1} tok/s), next {next}", + if s == 0.0 { "gpu alone" } else { "npu+gpu" } + ); + if s == 0.0 { + gpu_times.push(seconds) + } else { + split_times.push(seconds) + } + results.push((s, next, lp)); + } + let (a, b) = (&results[0].2, &results[1].2); + let kl: f64 = a.iter().zip(b).map(|(p, q)| p.exp() * (p - q)).sum(); + println!( + " last token: same top-1 {}, KL between the two arms {kl:.6}", + results[0].1 == results[1].1 + ); + } + let ratios: Vec = gpu_times + .iter() + .zip(&split_times) + .map(|(g, s)| g / s) + .collect(); + println!( + "paired speed-up of the split over the GPU alone: {:?} (mean {:.2})", + ratios + .iter() + .map(|r| (r * 100.0).round() / 100.0) + .collect::>(), + ratios.iter().sum::() / ratios.len() as f64 + ); +} diff --git a/crates/gpu-npu-worker/src/lib.rs b/crates/gpu-npu-worker/src/lib.rs new file mode 100644 index 00000000..f103e53f --- /dev/null +++ b/crates/gpu-npu-worker/src/lib.rs @@ -0,0 +1,376 @@ +//! 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, 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 Option + 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 { + 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, Vec), 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, Vec), 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, + 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, ModelError> { + Ok(self + .run(model, state, tokens, pos0, &mut |_| true, true)? + .expect("not cancelled")) + } + + fn run( + &mut self, + model: &Model, + cache: &dyn LayerCache, + tokens: &[u32], + pos0: usize, + progress: &mut dyn FnMut(f64) -> bool, + all_hidden: bool, + ) -> Result>, ModelError> { + let started = Instant::now(); + let n = tokens.len(); + let s = self.npu_tokens(n); + self.timings = SplitTimings { + npu_tokens: s, + gpu_tokens: n - s, + ..SplitTimings::default() + }; + if s == 0 { + 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) + }); + 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 + })) + } +} + +impl PrefillAccelerator for GpuNpuPrefill { + fn prefill( + &mut self, + model: &Model, + state: &mut State, + tokens: &[u32], + pos0: usize, + progress: &mut dyn FnMut(f64) -> bool, + ) -> Result>, ModelError> { + let out = self.run(model, state, tokens, pos0, progress, false); + 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(); + } +} diff --git a/crates/gpu-npu-worker/src/main.rs b/crates/gpu-npu-worker/src/main.rs new file mode 100644 index 00000000..51aa5365 --- /dev/null +++ b/crates/gpu-npu-worker/src/main.rs @@ -0,0 +1,243 @@ +//! `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]` (experimental) +//! +//! The CPU worker's decoder and protocol, with long prompts prefilled by the integrated GPU and the NPU together +//! (`leleka_gpu_npu_worker::GpuNpuPrefill`): prompts with at least `--split-min-tokens` tokens to compute give the +//! first `--npu-share` of them to the NPU service process and the rest to the GPU, at the same time; prompts with at +//! least `--gpu-min-tokens` but fewer than `--split-min-tokens` go to the GPU alone; shorter ones and all decoding +//! stay on the CPU. Without a usable GPU this worker serves from the CPU only (`leleka-npu-worker` is the NPU-only +//! worker); without the NPU service it prefills on the GPU alone. If a prefill fails it is redone on the CPU and the +//! accelerators are not used again in that session. + +use leleka_cpu_worker::engine::{self, LoadOptions}; +use leleka_cpu_worker::serve::serve; +use leleka_gptoss_igpu::GpuPrefill; +use leleka_gptoss_npu::NpuPrefill; +use leleka_gptoss_npu::client::ServiceConfig; +use leleka_gpu_npu_worker::{DEFAULT_NPU_SHARE, DEFAULT_SPLIT_MIN_TOKENS, GpuNpuPrefill}; +use std::io::{self, BufReader}; +use std::path::PathBuf; +use std::process::ExitCode; + +const DEFAULT_CONTEXT: usize = 32_768; +/// Below this many tokens the CPU is as fast or faster than the GPU (see docs/igpu-prefill.md). +const DEFAULT_GPU_MIN_TOKENS: usize = 256; + +struct Args { + model: PathBuf, + threads: usize, + context: usize, + warm: bool, + seed: u64, + speculate: bool, + openvino_root: Option, + service: Option, + device: String, + gpu_min_tokens: usize, + gpu_batch: usize, + npu_batch: usize, + npu_share: f64, + split_min_tokens: usize, +} + +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]" +} + +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 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, + "--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, + "--npu-share" => { + npu_share = args + .next() + .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; + } + other => return Err(format!("unknown argument {other}")), + } + } + if !serving { + return Err("only --serve mode exists".into()); + } + Ok(Args { + model: model.ok_or("--model is required")?, + threads, + context, + warm, + seed, + speculate, + openvino_root, + service, + device, + gpu_min_tokens, + gpu_batch, + npu_batch, + npu_share, + split_min_tokens, + }) +} + +/// The service executable next to this one, unless the caller named another. +fn default_service() -> PathBuf { + let name = if cfg!(windows) { + "leleka-npu-service.exe" + } else { + "leleka-npu-service" + }; + std::env::current_exe() + .ok() + .and_then(|exe| exe.parent().map(|dir| dir.join(name))) + .unwrap_or_else(|| PathBuf::from(name)) +} + +fn main() -> ExitCode { + let args = match parse_args() { + Ok(args) => args, + Err(message) => { + eprintln!("leleka-gpu-npu-worker: {message}\n{}", usage()); + return ExitCode::from(2); + } + }; + let loaded = match engine::load(&LoadOptions { + model: &args.model, + threads: args.threads, + context: args.context, + warm: args.warm, + }) { + Ok(loaded) => loaded, + Err(message) => { + eprintln!("leleka-gpu-npu-worker: {message}"); + return ExitCode::FAILURE; + } + }; + let mut engine = loaded.engine; + engine.set_speculation(args.speculate); + let gpu = match GpuPrefill::new() { + Ok(gpu) => gpu.with_batch(args.gpu_batch), + Err(e) => { + eprintln!("leleka-gpu-npu-worker: {e}; serving from the CPU only"); + return run(&mut engine, &loaded.stop_tokens, args.seed); + } + }; + 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 { + 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", + args.split_min_tokens, + args.gpu_batch, + npu.device_name(), + args.npu_batch, + args.npu_share, + args.gpu_min_tokens + ); + engine.set_accelerator( + Box::new( + GpuNpuPrefill::new(gpu, npu) + .with_npu_share(args.npu_share) + .with_split_min_tokens(args.split_min_tokens) + .with_memory_probe(Box::new(available_memory)), + ), + args.gpu_min_tokens, + ); + } + Err(e) => { + eprintln!( + "leleka-gpu-npu-worker: NPU unavailable ({e}); prefilling on the GPU ({adapter}) alone from {} tokens", + args.gpu_min_tokens + ); + engine.set_accelerator( + Box::new(gpu.with_memory_probe(Box::new(available_memory))), + args.gpu_min_tokens, + ); + } + } + run(&mut engine, &loaded.stop_tokens, args.seed) +} + +fn run(engine: &mut engine::GptOssEngine, stop_tokens: &[u32], seed: u64) -> ExitCode { + match serve( + engine, + BufReader::new(io::stdin()), + io::stdout(), + stop_tokens, + seed, + ) { + Ok(()) => ExitCode::SUCCESS, + Err(e) => { + eprintln!("leleka-gpu-npu-worker: {e}"); + ExitCode::FAILURE + } + } +} + +/// 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/docs/gpu-npu-prefill.md b/docs/gpu-npu-prefill.md new file mode 100644 index 00000000..6c9f1985 --- /dev/null +++ b/docs/gpu-npu-prefill.md @@ -0,0 +1,61 @@ +# One prompt prefilled by the iGPU and the NPU together (STRA-220, experimental; measured: no gain) + +`leleka-gpu-npu-worker` is the CPU worker's decoder and protocol with long prompts split between the two accelerators +(`crates/gpu-npu-worker`). The NPU path (`docs/npu-service.md`) takes the first `--npu-share` of the tokens and the GPU +path (`docs/igpu-prefill.md`) the rest, on two threads at once. Both run the prompt layer by layer and meet only in the +key and value cache (`leleka_gptoss::LayerCache`): 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. +The GPU part runs layer `l` while the NPU part runs layer `l + 1`. Each part keeps its own numerics; the last token's +distribution agreed with the GPU alone (same top token, KL 8e-5 to 1e-4 in every probe run). + +```powershell +cargo build --release -p leleka-gpu-npu-worker -p leleka-npu-service +.\target\release\leleka-gpu-npu-worker.exe --serve --model --openvino-root ` + [--npu-share 0.45] [--split-min-tokens 1024] [--gpu-min-tokens 256] [--gpu-batch 512] [--npu-batch 2048] +``` + +`LELEKA_SPLIT_LOG=1` prints the time of each part and how long the GPU part waited. Without the NPU service it prefills +on the GPU alone; without a GPU it serves from the CPU. + +## Why it was tried + +Run as two separate processes on two separate prompts, the iGPU and the NPU together prefill 93-98 tokens/s against +73-77 for the faster one alone (`benchmarks/results/igpu-npu-concurrent-prefill-2026-10-16.txt`), so the two units do add +throughput where decode cannot (decode is limited by the one memory channel). The question was whether one prompt can +use that. + +## Results (Core Ultra 7 265U, gpt-oss-20b-MXFP4, 2026-10-16; machine otherwise idle, power and clocks not controlled) + +Probe `examples/split_prefill.rs`, 2048 synthetic tokens, GPU alone against the split, alternating (one pair per line): + +| NPU share | GPU alone | split | speed-up | +| --- | --- | --- | --- | +| 0.45 | 28.6 s, 28.5 s, 28.7 s | 25.3 s, 26.6 s, 28.9 s | 1.13, 1.07, 0.99 | +| 0.5 | 31.6-35.2 s | 31.8-33.7 s | 1.05, 0.94, 1.06, 1.09 (last two with the NPU part capped at 8 and 4 CPU threads) | +| 0.6 | 29.3 s | 33.0 s | 0.89 | +| 0.7 | 32.7 s | 36.5 s | 0.90 | + +Agent-shaped episode through the control plane (`benchmarks/tools/Compare-PrefillWorkers.ps1 -ArmA leleka-igpu-worker +-ArmB leleka-gpu-npu-worker`, NPU share 0.5, four turns of about 2,060 new tokens each over a growing cached context, 32 +output tokens per turn, 3 + 3 alternating pairs; `benchmarks/results/agent-episode-gpu-npu-ab-2026-10-16.jsonl`, split +log in `agent-episode-gpu-npu-split-log-2026-10-16.txt`). Episode totals, iGPU worker against the split worker: +170.5 vs 177.4 s, 176.1 vs 152.3 s (run 1, pairs 2-3), 202.3 vs 209.9 s, 178.2 vs 214.2 s, 173.3 vs 214.4 s (run 2). +In run 1 the split arm's first pair took 35, 84, 110 and 148 s per turn; the cause was not captured and did not recur. + +Conclusion: no reliable gain, and a loss over the episode. Not adopted; the worker stays as an experiment. + +## Why it does not pay + +* Each part's time hardly falls with its share of the tokens: both paths stream every layer's weights once per prefill + whatever the token count, and when both run, they share the 15 W power budget and the memory channel. With the NPU + path running, the GPU's 1,024-1,126 tokens took as long as 2,048 tokens alone (attention about 10 s, experts about + 19 s in both cases); 819 and 614 tokens took longer still. +* The NPU part is the slow one: 1,025-1,065 tokens took 35-39 s in the first turn and 46-59 s in later turns, because + its attention runs on the CPU over the whole cached context, which grows by about 2,000 tokens a turn. The GPU part + waited 3-12 s per turn for it. +* Capping the NPU part's CPU threads (`NpuPrefill::with_cpu_threads`, 8 or 4 of 14) changed nothing measurable, so the + GPU was not starved of CPU time. + +Splitting the experts instead (each device streams half of the expert weights for every token) would remove the +duplicated weight streaming, but by the timings above the gain would be about 1.1x after contention, so it was not built. +Two concurrent requests, one per device, are the case where the two accelerators measurably add throughput. diff --git a/docs/igpu-prefill.md b/docs/igpu-prefill.md index 37400e91..37755120 100644 --- a/docs/igpu-prefill.md +++ b/docs/igpu-prefill.md @@ -137,3 +137,6 @@ used for verification: one 9-token pass takes 7.3 s against 0.75 s on the CPU, b Not done yet: an A/B run of a full agent workload through the control plane at the charter's required measurement detail. + +Splitting one prompt between this GPU path and the NPU path at the same time (`leleka-gpu-npu-worker`) was built and +measured: no reliable gain over this worker on the agent episode, see `docs/gpu-npu-prefill.md`. diff --git a/docs/npu-service.md b/docs/npu-service.md index 28914028..22a6d1cb 100644 --- a/docs/npu-service.md +++ b/docs/npu-service.md @@ -99,6 +99,8 @@ unpinned threads; Windows leaves the two low-power E-cores idle. ## Limits * Prefill only; below roughly 1024 tokens the CPU is as fast or faster (`--npu-min-tokens` default 1024). +* Running at the same time as the GPU prefill on parts of one prompt (`leleka-gpu-npu-worker`, `docs/gpu-npu-prefill.md`) + gave no reliable gain over the GPU alone; the NPU part, whose attention runs on the CPU, was the slow side. * Not usable for verifying speculative drafts: one 9-token pass takes 6.3 s against 0.93 s on the CPU (`docs/cpu-runtime.md`, `--speculate` section); `--speculate` verifies on the CPU in this worker too. * The service and the worker both map the 12 GB model; they share pages, but total memory use is high on a 32 GB