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

108 lines
4.5 KiB
Rust

//! 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 -- <model.gguf> <openvino root>
//! <service exe> <device> <ids.txt> <out.jsonl> [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;
/// The comma separated token ids in the file.
fn read_ids(path: &str) -> Vec<u32> {
std::fs::read_to_string(path)
.expect("ids file")
.trim()
.split(',')
.map(|s| s.trim().parse().expect("token id"))
.collect()
}
fn load_model(path: &Path, threads: usize) -> 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");
Model::load(
std::sync::Arc::new(Mapping::open(path).expect("map model")),
&gguf,
Dispatch::from_env().expect("kernel level"),
threads,
)
.expect("load model")
}
/// One output line: the top-N log-probabilities of the distribution after position `pos`.
fn write_position(out: &mut impl Write, logits: &[f32], (pos, next): (usize, Option<&u32>), top_n: usize) {
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<usize> = (0..logits.len()).collect();
order.sort_by(|a, b| logits[*b].total_cmp(&logits[*a]).then(a.cmp(b)));
let top: Vec<String> = order
.iter()
.take(top_n)
.map(|i| format!("[{},{:.6}]", i, f64::from(logits[*i] - max) - z.ln()))
.collect();
let next = next.map_or("null".to_owned(), |n| n.to_string());
writeln!(out, "{{\"pos\":{pos},\"next\":{next},\"top\":[{}]}}", top.join(",")).expect("write");
}
/// Write the distribution after every prompt token, from the hidden states the accelerator left.
fn write_from_hidden(model: &Model, state: &mut State, ids: &[u32], hidden: &[f32], (path, top_n): (&str, usize)) {
let e = model.config.n_embd;
let mut out = BufWriter::new(File::create(path).expect("output file"));
for pos in 0..ids.len() {
model
.next_from_hidden(state, &hidden[pos * e..(pos + 1) * e])
.expect("output projection");
write_position(&mut out, &state.logits, (pos, ids.get(pos + 1)), top_n);
}
eprintln!("wrote {} positions", ids.len());
}
/// The NPU service named on the command line.
fn service_config(args: &[String], model: &Path) -> ServiceConfig {
ServiceConfig {
service: args[2].clone().into(),
openvino_root: args[1].clone().into(),
device: args[3].clone(),
model: model.to_path_buf(),
cache_dir: None,
}
}
fn main() {
let args: Vec<String> = std::env::args().skip(1).collect();
if args.len() < 6 {
eprintln!(
"usage: dump_logprobs_split <model.gguf> <openvino root> <service exe> <device> <ids.txt> <out.jsonl> \
[top_n] [npu share]"
);
std::process::exit(2);
}
let ids = read_ids(&args[4]);
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 model = load_model(path, std::thread::available_parallelism().map_or(1, |n| n.get()));
let mut state = State::new(&model.config, ids.len() + 1);
let config = service_config(&args, path);
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());
write_from_hidden(&model, &mut state, &ids, &hidden, (&args[5], top_n));
}