Files
leleka/crates/gptoss-npu/examples/dump_logprobs_npu.rs
T
Pavlo RatushnyiandClaude Sonnet 5.5 8d96e9c44c perf: overlap weight expansion with NPU execution, batch products, SIMD half conversion, graph cache (STRA-207)
- service: BATCH n lets it see each product's successor and expand the next weights on a thread
  while the device runs the current one; buckets up to 4096; OpenVINO CACHE_DIR compile cache
- client: batched expert products, layout sized by batch, default batch 2048
- cpu-sys/cpu-kernels: AVX2 F16C f16_to_f32 kernel, exact for every half bit pattern
- npu-worker: memory admission before an NPU prefill (falls back to the CPU when RAM is short)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-15 12:22:13 +02:00

91 lines
3.6 KiB
Rust

//! Teacher-forced log-probabilities with the prompt prefilled through the NPU service: the same output format
//! as `dump_logprobs` of the CPU decoder, so `compare_logprobs` can compare it with llama.cpp's reference.
//! Every position's hidden state comes from the NPU prefill; the output projection runs on the CPU.
//!
//! Run: `cargo run --release -p leleka-gptoss-npu --example dump_logprobs_npu -- <model.gguf> <openvino root> <service exe> <device> <ids.txt> <out.jsonl> [top_n] [batch]`
use leleka_cpu_kernels::Dispatch;
use leleka_cpu_sys::mapping::Mapping;
use leleka_gguf::Gguf;
use leleka_gptoss::{Model, State};
use leleka_gptoss_npu::NpuPrefill;
use leleka_gptoss_npu::client::ServiceConfig;
use std::fs::File;
use std::io::{BufReader, BufWriter, Write};
use std::path::Path;
fn main() {
let args: Vec<String> = std::env::args().skip(1).collect();
if args.len() < 6 {
eprintln!(
"usage: dump_logprobs_npu <model.gguf> <openvino root> <service exe> <device> <ids.txt> <out.jsonl> [top_n] [batch]"
);
std::process::exit(2);
}
let ids: Vec<u32> = 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 batch: usize = args
.get(7)
.and_then(|s| s.parse().ok())
.unwrap_or(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 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 mut accel = NpuPrefill::start(&config, batch).expect("start the NPU service");
let hidden = accel
.prefill_all_hidden(&model, &mut state, &ids, 0)
.expect("gpu 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<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 = 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());
}