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 <noreply@anthropic.com>
178 lines
6.8 KiB
Rust
178 lines
6.8 KiB
Rust
//! 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 -- <model.gguf> <openvino root>
|
|
//! <service exe> <device> <ids file|synth:N> [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<f64> {
|
|
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<String> = std::env::args().skip(1).collect();
|
|
if args.len() < 5 {
|
|
eprintln!(
|
|
"usage: split_prefill <model.gguf> <openvino root> <service exe> <device> <ids file|synth:N> [rounds] [npu share] [prefix] [gpu batch] [npu batch]"
|
|
);
|
|
std::process::exit(2);
|
|
}
|
|
let ids: Vec<u32> = if let Some(n) = args[4].strip_prefix("synth:") {
|
|
let mut s = 0x2545_F491_4F6C_DD1Du64;
|
|
(0..n.parse::<usize>().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<f64>) {
|
|
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<f64> = 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::<Vec<_>>(),
|
|
ratios.iter().sum::<f64>() / ratios.len() as f64
|
|
);
|
|
}
|