Files
leleka/crates/cpu-worker/examples/ab_speculation.rs
T
Pavlo RatushnyiandClaude Opus 5.5 c58173097d test: paired speculation A/B, CPU batch-cost curve and accelerator verify cost; docs (STRA-220)
ab_speculation: four agent-style prompts, 3 alternating pairs, greedy, identical
outputs in all 96 runs; copy-heavy output 1.10-1.36x decode, new text within noise
of 1.0. batch_cost: a CPU pass over n >= 4 tokens costs about 0.65 n single steps, so
CPU speculation is capped near 1.5x. One 9-token pass takes 7.3 s on the iGPU and
6.3 s through the NPU service against 0.75-0.93 s on the CPU, so neither is used for
verification.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 12:11:02 +02:00

333 lines
13 KiB
Rust

//! Paired A/B of exact prompt-lookup speculation (`--speculate`) against plain decoding in one worker process.
//!
//! Run: `cargo run --release -p leleka-cpu-worker --example ab_speculation -- <model.gguf> <source file>
//! [pairs] [max_new] [threads] [chars]`
//!
//! Builds four agent-style Harmony prompts over the first `chars` characters (default 2400) of `source file`:
//! rewrite it with two functions renamed, a unified diff adding an attribute, a JSON list of its functions, and a
//! prose explanation. Every prompt is run greedy (`temperature=0`) through the worker's own `serve` loop once with
//! speculation off and once on, alternating which goes first per pair; the engine, its warm weights and its prefix
//! cache are shared, so prefill differs between arms but decode starts from the same cached prompt. Prints one line
//! per run (decode tokens, decode ms, whether the tokens equal the other arm's), each prompt's output text and ids,
//! and a per-prompt summary. With `LELEKA_AB_REPLAY=<that output>` no model is run: a grid of drafting policies is
//! replayed over the recorded outputs (`leleka_gptoss::speculate::replay`, measured pass costs) and ranked.
//! A measurement of these prompts on this machine, not a workload estimate; machine state is not controlled.
use leleka_cpu_worker::engine::{self, LoadOptions};
use leleka_cpu_worker::serve::serve;
use leleka_gguf::Gguf;
use leleka_gptoss::speculate::{MAX_DRAFT, MEASURED_COST, Policy, replay};
use leleka_tokenizer::gguf_bpe::GgufBpe;
use std::fs::File;
use std::io::{BufReader, Cursor, Read, Write};
use std::path::Path;
use std::sync::{Arc, Mutex, mpsc};
const TASKS: [(&str, &str); 4] = [
(
"rewrite",
"Rewrite the whole file with the function `sample` renamed to `draw_token` and `argmax` renamed to `best_index`. Output only the code.",
),
(
"diff",
"Write a unified diff for this file that adds `#[inline]` on the line before every `pub fn`. Output only the diff.",
),
(
"json",
"List every function in the file as a JSON array of objects with the fields `name` and `arguments`.",
),
(
"explain",
"Explain in one short paragraph what this file does.",
),
];
/// The worker's output; once a request is answered it sends `QUIT` on the input channel (end of input before the
/// request is taken would make `serve` drop it).
#[derive(Clone)]
struct Shared(Arc<Mutex<Vec<u8>>>, mpsc::Sender<Vec<u8>>);
impl Write for Shared {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.0.lock().unwrap().extend_from_slice(buf);
if buf.starts_with(b"DONE ") || buf.starts_with(b"ERR") {
let _ = self.1.send(b"QUIT\n".to_vec());
}
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
/// Input lines arriving on a channel; blocks until the next one.
struct Input(mpsc::Receiver<Vec<u8>>, Cursor<Vec<u8>>);
impl Read for Input {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
if self.1.position() as usize >= self.1.get_ref().len() {
match self.0.recv() {
Ok(line) => self.1 = Cursor::new(line),
Err(_) => return Ok(0),
}
}
self.1.read(buf)
}
}
struct Run {
tokens: Vec<u32>,
prompt_ms: f64,
decode_ms: f64,
}
fn run(engine: &mut engine::GptOssEngine, stops: &[u32], prompt: &[u32], max_new: usize) -> Run {
let ids = prompt
.iter()
.map(u32::to_string)
.collect::<Vec<_>>()
.join(",");
let (tx, rx) = mpsc::channel();
tx.send(format!("GEN {max_new} temperature=0 {ids}\n").into_bytes())
.expect("send");
let out = Shared(Arc::default(), tx);
serve(
engine,
BufReader::new(Input(rx, Cursor::default())),
out.clone(),
stops,
0,
)
.expect("serve");
let text = String::from_utf8(out.0.lock().unwrap().clone()).expect("utf-8");
let mut tokens = Vec::new();
for line in text.lines() {
if let Some(t) = line.strip_prefix("T ") {
tokens.push(t.parse().expect("token id"));
} else if let Some(done) = line.strip_prefix("DONE ") {
let f: Vec<&str> = done.split(' ').collect();
return Run {
tokens,
prompt_ms: f[2].parse().expect("prompt ms"),
decode_ms: f[3].parse().expect("decode ms"),
};
} else if line.starts_with("ERR") {
panic!("worker error: {line}");
}
}
panic!("no DONE line in {text}");
}
/// Undo the `{:?}` escaping of a string as printed by this example.
fn unescape(s: &str) -> String {
let mut out = String::new();
let mut chars = s.chars();
while let Some(c) = chars.next() {
if c != '\\' {
out.push(c);
continue;
}
match chars.next() {
Some('n') => out.push('\n'),
Some('t') => out.push('\t'),
Some('r') => out.push('\r'),
Some('0') => out.push('\0'),
Some('u') => {
let hex: String = chars.by_ref().skip(1).take_while(|c| *c != '}').collect();
out.extend(u32::from_str_radix(&hex, 16).ok().and_then(char::from_u32));
}
Some(other) => out.push(other),
None => {}
}
}
out
}
/// `LELEKA_AB_REPLAY=<output of an earlier run>`: replay drafting policies over the recorded greedy outputs (token
/// ids from `ids:` lines, else the re-tokenized `output:` text) with the measured pass costs; no model is run.
fn replay_policies(tokenizer: &GgufBpe, prompts: &[Vec<u32>], path: &str) {
let text = std::fs::read_to_string(path).expect("replay file");
let mut outputs: Vec<Vec<u32>> = vec![Vec::new(); TASKS.len()];
for (i, (task, _)) in TASKS.iter().enumerate() {
for line in text.lines() {
let line = line.trim_start_matches('\u{feff}');
if let Some(ids) = line.strip_prefix(&format!("{task} ids: [")) {
outputs[i] = ids
.trim_end_matches(']')
.split(", ")
.map(|t| t.parse().expect("token id"))
.collect();
} else if let Some(quoted) = line.strip_prefix(&format!("{task} output: \""))
&& outputs[i].is_empty()
{
let output = unescape(quoted.strip_suffix('"').unwrap_or(quoted));
outputs[i] = tokenizer.encode(&output, true);
}
}
assert!(!outputs[i].is_empty(), "no output of {task} in {path}");
}
let mut rows = Vec::new();
for min_match in [2, 3, 4] {
for prior in [(2.0, 1.0), (4.0, 1.0), (9.0, 1.0)] {
for forget in [0.8, 0.9, 0.95] {
for min_gain in [1.0, 1.03, 1.1] {
for probe_after in [8, 16, 24, 48] {
let policy = Policy {
min_match,
max_draft: MAX_DRAFT,
prior,
forget,
min_gain,
probe_after,
};
let gains: Vec<f64> = prompts
.iter()
.zip(&outputs)
.map(|(p, o)| replay(policy, p, o, &MEASURED_COST).speedup())
.collect();
let geomean =
gains.iter().map(|g| g.ln()).sum::<f64>() / gains.len() as f64;
rows.push((policy, gains, geomean.exp()));
}
}
}
}
}
let show = |(policy, gains, geomean): &(Policy, Vec<f64>, f64)| {
println!(
"geomean {geomean:.3} min {:.3} {:?} {:?}",
gains.iter().copied().fold(f64::INFINITY, f64::min),
gains
.iter()
.map(|g| (g * 1000.0).round() / 1000.0)
.collect::<Vec<_>>(),
policy
);
};
let default = rows.iter().find(|r| r.0 == Policy::default());
println!("default policy:");
default.into_iter().for_each(show);
rows.sort_by(|a, b| b.2.total_cmp(&a.2));
println!("best by geometric mean whose worst task is at least 0.995:");
rows.iter()
.filter(|r| r.1.iter().all(|g| *g >= 0.995))
.take(15)
.for_each(show);
}
fn main() {
let args: Vec<String> = std::env::args().skip(1).collect();
if args.len() < 2 {
eprintln!(
"usage: ab_speculation <model.gguf> <source file> [pairs] [max_new] [threads] [chars]"
);
std::process::exit(2);
}
let arg =
|i: usize, default: usize| args.get(i).and_then(|s| s.parse().ok()).unwrap_or(default);
let (pairs, max_new) = (arg(2, 3), arg(3, 320));
let threads = arg(
4,
std::thread::available_parallelism().map_or(1, |n| n.get()),
);
let chars = arg(5, 2400);
let model = Path::new(&args[0]);
let source: String = std::fs::read_to_string(&args[1])
.expect("source file")
.chars()
.take(chars)
.collect();
let name = Path::new(&args[1])
.file_name()
.map_or_else(String::new, |n| n.to_string_lossy().into_owned());
let size = std::fs::metadata(model).expect("model file").len();
let gguf = Gguf::read(
BufReader::with_capacity(1 << 20, File::open(model).expect("open")),
size,
)
.expect("valid GGUF");
let tokenizer = GgufBpe::from_gguf(&gguf).expect("tokenizer");
let head = format!(
"<|start|>system<|message|>You are ChatGPT, a large language model trained by OpenAI.\nKnowledge cutoff: 2024-06\nCurrent date: 2026-10-16\n\nReasoning: low\n\n# Valid channels: analysis, commentary, final. Channel must be included for every message.<|end|><|start|>developer<|message|># Instructions\n\nYou are a coding agent working in a Rust repository. Answer concisely.<|end|><|start|>user<|message|>Here is the file {name}:\n\n```rust\n{source}\n```<|end|>"
);
let prompts: Vec<Vec<u32>> = TASKS
.iter()
.map(|(_, task)| {
tokenizer.encode(
&format!("{head}<|start|>user<|message|>{task}<|end|><|start|>assistant"),
true,
)
})
.collect();
if let Ok(path) = std::env::var("LELEKA_AB_REPLAY") {
replay_policies(&tokenizer, &prompts, &path);
return;
}
let loaded = engine::load(&LoadOptions {
model,
threads,
context: prompts.iter().map(Vec::len).max().unwrap_or(0) + max_new + 64,
warm: true,
})
.expect("load");
let (mut engine, stops) = (loaded.engine, loaded.stop_tokens);
eprintln!(
"ab_speculation: {} prompts of {:?} tokens, {pairs} pairs, max_new {max_new}, {threads} threads",
prompts.len(),
prompts.iter().map(Vec::len).collect::<Vec<_>>()
);
// one untimed request pages in and fills the cache with the shared prefix
run(&mut engine, &stops, &prompts[0][..prompts[0].len() - 8], 1);
let mut summary = Vec::new();
for (i, prompt) in prompts.iter().enumerate() {
let (mut plain, mut spec) = (Vec::new(), Vec::new());
let mut reference: Option<Vec<u32>> = None;
let mut identical = true;
for pair in 0..pairs {
let order = if (pair + i) % 2 == 0 {
[false, true]
} else {
[true, false]
};
for speculate in order {
engine.set_speculation(speculate);
let r = run(&mut engine, &stops, prompt, max_new);
let same = reference.get_or_insert_with(|| r.tokens.clone()) == &r.tokens;
identical &= same;
let rate = r.tokens.len() as f64 / (r.decode_ms / 1000.0);
println!(
"{} pair {pair} speculate={speculate}: {} tokens, prompt {:.0} ms, decode {:.0} ms ({rate:.2} tok/s), identical={same}",
TASKS[i].0,
r.tokens.len(),
r.prompt_ms,
r.decode_ms
);
if speculate { &mut spec } else { &mut plain }.push(rate);
}
}
let median = |v: &mut Vec<f64>| {
v.sort_by(f64::total_cmp);
v[v.len() / 2]
};
let ratios: Vec<f64> = spec.iter().zip(&plain).map(|(s, p)| s / p).collect();
summary.push(format!(
"{}: plain median {:.2} tok/s, speculate median {:.2} tok/s, paired ratio mean {:.2} (runs {:?}), outputs identical: {identical}",
TASKS[i].0,
median(&mut plain.clone()),
median(&mut spec.clone()),
ratios.iter().sum::<f64>() / ratios.len() as f64,
ratios.iter().map(|r| (r * 100.0).round() / 100.0).collect::<Vec<_>>()
));
if let Some(tokens) = reference {
println!("{} output: {:?}", TASKS[i].0, tokenizer.decode(&tokens));
println!("{} ids: {tokens:?}", TASKS[i].0);
}
}
for line in summary {
println!("{line}");
}
}