Files
leleka/crates/gpu-npu-worker/examples/split_prefill.rs
T

198 lines
8.0 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, PrefillSpan, 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()
}
/// The token ids: `synth:N` makes N deterministic pseudo-random ids, else a file of comma separated ids.
fn parse_ids(arg: &str) -> Vec<u32> {
if let Some(n) = arg.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(arg)
.expect("ids file")
.trim()
.split(',')
.map(|s| s.trim().parse().expect("token id"))
.collect()
}
}
fn load_model(path: &Path) -> Model {
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();
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")
}
/// The GPU and the NPU service together, ready to split prompts.
fn start_split(args: &[String], path: &Path, (gpu_batch, npu_batch): (usize, usize)) -> GpuNpuPrefill {
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);
GpuNpuPrefill::new(gpu, npu).with_split_min_tokens(2)
}
/// The timings of the split and of its NPU part.
fn print_split_timings(split: &GpuNpuPrefill) {
println!(" {}", split.timings().report());
println!(" npu: {}", split.npu().timings().report());
}
/// One prefill of `ids[prefix..]` after a GPU-only prefix, with the given NPU share: seconds, the next token and the
/// last distribution. Timings are printed unless `warm`.
fn run_once(
model: &Model,
split: &mut GpuNpuPrefill,
(ids, prefix): (&[u32], usize),
(npu_share, warm): (f64, 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, PrefillSpan { tokens: &ids[..prefix], pos0: 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, PrefillSpan { tokens: &ids[prefix..], pos0: 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 {
print_split_timings(split);
}
(seconds, next, log_softmax(&state.logits))
}
/// The paired speed-ups of the split over the GPU alone.
fn report_ratios(gpu_times: &[f64], split_times: &[f64]) {
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
);
}
/// The timed rounds, alternating which arm goes first, and the speed-up of the split over the GPU alone.
fn run_rounds(model: &Model, split: &mut GpuNpuPrefill, (ids, prefix): (&[u32], usize), (rounds, share): (usize, f64)) {
let rest_len = ids.len() - prefix;
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_once(model, split, (ids, prefix), (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
);
}
report_ratios(&gpu_times, &split_times);
}
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 = parse_ids(&args[4]);
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 model = load_model(path);
let mut split = start_split(&args, path, (gpu_batch, npu_batch));
let rest_len = ids.len() - prefix;
println!(
"{rest_len} tokens after a prefix of {prefix}; npu share {share} ({} tokens); gpu batch {gpu_batch}, \
npu batch {npu_batch}",
((rest_len as f64 * share).round() as usize).min(rest_len - 1)
);
// one untimed run of each first: graphs, pipelines and caches
run_once(&model, &mut split, (&ids, prefix), (0.0, true));
run_once(&model, &mut split, (&ids, prefix), (share, true));
run_rounds(&model, &mut split, (&ids, prefix), (rounds, share));
}