Profiling the speculative verification pass (batch_cost, position 900) showed its extra cost is compute in the int8 weight products, not expert bytes: distinct experts per layer rise only from 4 to 9.5 at 9 tokens, while the Q8_0 projections, whose weights every token shares, cost 3.6-4x a single step. Each (row, token) dot redid the MXFP4 decode and scale work. cpu-sys gains multi-activation kernels (portable, AVX2, AVX-VNNI) for MXFP4 and Q8_0 rows: the row is decoded once per 64-block segment and up to 16 activations run over it with exactly the one-token kernel's accumulators and final reduction, so every output is bit for bit the one-token kernel's (tests/multi.rs: every level, 1-16 activations, 13 row lengths). run_region uses them for jobs with two or more activations (speculative batches and prefill chunks); one-token decode keeps its kernel. A new synthetic test checks a 20-token batch at every level against feeding tokens one at a time. Model::set_multi_activation(false) restores the per-token path for paired measurements; Profile counts the expert sets read. batch_cost gains a per-size phase breakdown and an `ab` mode that runs every pass without and with the new kernels back to back and checks the logits are identical. Paired, 9 rounds, real model: identical logits in all 90 paired passes; time ratio with/without 1.01 (1 token), 0.98, 0.92, 0.90, 0.83, 0.81, 0.77, 0.79, 0.76 (2..9 tokens). MEASURED_COST becomes 0.737 + 0.421 n (was 0.30 + 0.631 n). ab_speculation (3 pairs, outputs identical in all 24 runs) gave 1.34 / 1.04 / 0.97 / 0.94, within the pair-to-pair spread of the run before the change; replaying the outputs through the drafter predicts 1.59 / 1.15 / 1.00 / 0.99, so the serving loop loses time the pass-cost model does not see. Prefill also uses the kernels (bit-identical); its speed was not measured. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
181 lines
7.1 KiB
Rust
181 lines
7.1 KiB
Rust
//! Time of one decoder pass over n tokens (n = 1..=max) at a fixed position, as used by speculative verification:
|
|
//! `forward` for one token, `logits_after_each` for a batch. The cache is cut back to the prompt after every pass,
|
|
//! sizes are interleaved in a different order each round, and the median per size is printed.
|
|
//! With `ab` every pass runs twice back to back, without and with the multi-activation kernels
|
|
//! ([`Model::set_multi_activation`], identical values), alternating which goes first, and the paired ratios are printed.
|
|
//!
|
|
//! Run: `cargo run --release -p leleka-gptoss --example batch_cost -- <model.gguf> [prompt_tokens] [max_n] [rounds] [threads] [ab]`
|
|
//! The prompt is deterministic pseudo-random ids. Machine state is not controlled.
|
|
|
|
use leleka_cpu_kernels::Dispatch;
|
|
use leleka_cpu_sys::mapping::Mapping;
|
|
use leleka_gguf::Gguf;
|
|
use leleka_gptoss::{Model, Profile, State};
|
|
use std::fs::File;
|
|
use std::io::BufReader;
|
|
use std::path::Path;
|
|
use std::time::Instant;
|
|
|
|
fn ids(n: usize, mut s: u64) -> Vec<u32> {
|
|
(0..n)
|
|
.map(|_| {
|
|
s ^= s << 13;
|
|
s ^= s >> 7;
|
|
s ^= s << 17;
|
|
1000 + (s % 60_000) as u32
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
fn main() {
|
|
let args: Vec<String> = std::env::args().skip(1).collect();
|
|
if args.is_empty() {
|
|
eprintln!("usage: batch_cost <model.gguf> [prompt_tokens] [max_n] [rounds] [threads] [ab]");
|
|
std::process::exit(2);
|
|
}
|
|
let arg = |i: usize, d: usize| args.get(i).and_then(|s| s.parse().ok()).unwrap_or(d);
|
|
let (prompt_len, max_n, rounds) = (arg(1, 900), arg(2, 9), arg(3, 5));
|
|
let threads = arg(
|
|
4,
|
|
std::thread::available_parallelism().map_or(1, |n| n.get()),
|
|
);
|
|
let paired = args.get(5).is_some_and(|s| s == "ab");
|
|
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 mut model = Model::load(
|
|
std::sync::Arc::new(map),
|
|
&gguf,
|
|
Dispatch::from_env().expect("kernel level"),
|
|
threads,
|
|
)
|
|
.expect("load model");
|
|
let prompt = ids(prompt_len, 0x2545_F491_4F6C_DD1D);
|
|
let mut state = State::new(&model.config, prompt_len + max_n + 1);
|
|
let t = Instant::now();
|
|
model.prefill(&mut state, &prompt, 0).expect("prefill");
|
|
eprintln!(
|
|
"prefill of {prompt_len} tokens: {:.1} s; {threads} threads",
|
|
t.elapsed().as_secs_f64()
|
|
);
|
|
// arm 0: one-token kernel per token, arm 1: multi-activation kernels (the default)
|
|
let arms: Vec<bool> = if paired {
|
|
vec![false, true]
|
|
} else {
|
|
vec![true]
|
|
};
|
|
let mut times: Vec<Vec<Vec<f64>>> = vec![vec![Vec::new(); max_n + 1]; arms.len()];
|
|
let mut profiles: Vec<Vec<Profile>> = vec![vec![Profile::default(); max_n + 1]; arms.len()];
|
|
let mut identical = 0usize;
|
|
for round in 0..rounds + 1 {
|
|
let mut order: Vec<usize> = (1..=max_n).collect();
|
|
order.rotate_left(round % max_n);
|
|
if round % 2 == 1 {
|
|
order.reverse();
|
|
}
|
|
for n in order {
|
|
let batch = ids(n, 77 + round as u64 * 31 + n as u64);
|
|
let mut first_arm: Option<Vec<Vec<u32>>> = None;
|
|
for k in 0..arms.len() {
|
|
// the arms of one pass run back to back, alternating which goes first
|
|
let arm = (k + round + n) % arms.len();
|
|
model.set_multi_activation(arms[arm]);
|
|
state.truncate(prompt_len);
|
|
// the pass accumulates into its profile (round 0 into a discarded one)
|
|
let mut warm_up = Profile::default();
|
|
let profile = if round > 0 {
|
|
&mut profiles[arm][n]
|
|
} else {
|
|
&mut warm_up
|
|
};
|
|
std::mem::swap(&mut state.profile, profile);
|
|
let t = Instant::now();
|
|
let logits = if n == 1 {
|
|
model
|
|
.forward(&mut state, batch[0], prompt_len)
|
|
.expect("forward");
|
|
vec![state.logits.clone()]
|
|
} else {
|
|
model
|
|
.logits_after_each(&mut state, &batch, prompt_len)
|
|
.expect("batch")
|
|
};
|
|
let elapsed = t.elapsed();
|
|
// both arms must give the same logits bit for bit
|
|
let bits: Vec<Vec<u32>> = logits
|
|
.iter()
|
|
.map(|l| l.iter().map(|x| x.to_bits()).collect())
|
|
.collect();
|
|
match &first_arm {
|
|
None => first_arm = Some(bits),
|
|
Some(first) => {
|
|
assert!(*first == bits, "the arms differ: round {round}, {n} tokens");
|
|
identical += 1;
|
|
}
|
|
}
|
|
std::mem::swap(&mut state.profile, profile);
|
|
if round > 0 {
|
|
// round 0 is a warm-up
|
|
times[arm][n].push(elapsed.as_secs_f64() * 1000.0);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
let median = |v: &[f64]| {
|
|
let mut v = v.to_vec();
|
|
v.sort_by(f64::total_cmp);
|
|
v[v.len() / 2]
|
|
};
|
|
for (arm, multi) in arms.iter().enumerate() {
|
|
let label = if *multi {
|
|
"multi-activation kernels"
|
|
} else {
|
|
"one-token kernel per token"
|
|
};
|
|
println!("{label}:");
|
|
let single = median(×[arm][1]);
|
|
println!("n\tmedian ms\tms per token\tcost vs n single steps");
|
|
for (n, v) in times[arm].iter().enumerate().skip(1) {
|
|
let m = median(v);
|
|
println!(
|
|
"{n}\t{m:.0}\t{:.0}\t{:.2}\t(runs {:?})",
|
|
m / n as f64,
|
|
m / (single * n as f64),
|
|
v.iter().map(|x| x.round()).collect::<Vec<_>>()
|
|
);
|
|
}
|
|
println!("phase breakdown, per token, summed over the measured rounds:");
|
|
for (n, p) in profiles[arm].iter().enumerate().skip(1) {
|
|
let experts = p.experts_read as f64 / (rounds * model.config.blocks) as f64;
|
|
println!(
|
|
"{n}\t{} | distinct experts per layer {experts:.1}",
|
|
p.report()
|
|
);
|
|
}
|
|
}
|
|
if paired {
|
|
println!("logits of the two arms identical bit for bit in all {identical} paired passes");
|
|
}
|
|
if paired {
|
|
println!("paired: time with multi-activation kernels / time without, per round");
|
|
println!("n\tmedian ratio\t(ratios)");
|
|
for (n, (with, without)) in times[1].iter().zip(×[0]).enumerate().skip(1) {
|
|
let ratios: Vec<f64> = with.iter().zip(without).map(|(on, off)| on / off).collect();
|
|
println!(
|
|
"{n}\t{:.3}\t{:?}",
|
|
median(&ratios),
|
|
ratios
|
|
.iter()
|
|
.map(|r| (r * 1000.0).round() / 1000.0)
|
|
.collect::<Vec<_>>()
|
|
);
|
|
}
|
|
}
|
|
}
|