Files
leleka/crates/cpu-worker/examples/ab_speculation.rs
T

317 lines
11 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_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};
#[path = "ab_speculation/policy_replay.rs"]
mod policy_replay;
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");
parse_run(&text)
}
/// The generated tokens and the timings of the `DONE` line in the worker's output.
fn parse_run(text: &str) -> Run {
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}");
}
/// The shared system and developer messages and the source file every task is asked about.
fn prompt_head(name: &str, source: &str) -> String {
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|>"
)
}
/// The rates of the plain and the speculative runs of one task, whether every output matched the first one, and
/// that first output.
struct Arms {
plain: Vec<f64>,
spec: Vec<f64>,
identical: bool,
reference: Option<Vec<u32>>,
}
/// The line of one finished run.
fn print_run((i, pair, speculate): (usize, usize, bool), r: &Run, (rate, same): (f64, bool)) {
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
);
}
/// Alternating plain and speculative runs of one task.
fn run_arms(
engine: &mut engine::GptOssEngine,
stops: &[u32],
(i, prompt): (usize, &[u32]),
(pairs, max_new): (usize, usize),
) -> Arms {
let mut arms = Arms {
plain: Vec::new(),
spec: Vec::new(),
identical: true,
reference: None,
};
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(engine, stops, prompt, max_new);
let same = arms.reference.get_or_insert_with(|| r.tokens.clone()) == &r.tokens;
arms.identical &= same;
let rate = r.tokens.len() as f64 / (r.decode_ms / 1000.0);
print_run((i, pair, speculate), &r, (rate, same));
if speculate { &mut arms.spec } else { &mut arms.plain }.push(rate);
}
}
arms
}
/// The summary line of one task's runs.
fn summary_line(i: usize, arms: &Arms) -> String {
let median = |v: &[f64]| {
let mut v = v.to_vec();
v.sort_by(f64::total_cmp);
v[v.len() / 2]
};
let ratios: Vec<f64> = arms.spec.iter().zip(&arms.plain).map(|(s, p)| s / p).collect();
format!(
"{}: plain median {:.2} tok/s, speculate median {:.2} tok/s, paired ratio mean {:.2} (runs {:?}), \
outputs identical: {}",
TASKS[i].0,
median(&arms.plain),
median(&arms.spec),
ratios.iter().sum::<f64>() / ratios.len() as f64,
ratios.iter().map(|r| (r * 100.0).round() / 100.0).collect::<Vec<_>>(),
arms.identical
)
}
/// Alternating plain and speculative runs of one task; the summary line.
fn measure_task(
engine: &mut engine::GptOssEngine,
stops: &[u32],
task: (usize, &[u32]),
settings: (usize, usize),
tokenizer: &GgufBpe,
) -> String {
let i = task.0;
let arms = run_arms(engine, stops, task, settings);
let line = summary_line(i, &arms);
if let Some(tokens) = arms.reference {
println!("{} output: {:?}", TASKS[i].0, tokenizer.decode(&tokens));
println!("{} ids: {tokens:?}", TASKS[i].0);
}
line
}
fn read_tokenizer(model: &Path) -> GgufBpe {
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");
GgufBpe::from_gguf(&gguf).expect("tokenizer")
}
/// The prompt of every task over the first `chars` characters of the source file.
fn task_prompts(tokenizer: &GgufBpe, (file, chars): (&str, usize)) -> Vec<Vec<u32>> {
let source: String = std::fs::read_to_string(file)
.expect("source file")
.chars()
.take(chars)
.collect();
let name = Path::new(file)
.file_name()
.map_or_else(String::new, |n| n.to_string_lossy().into_owned());
let head = prompt_head(&name, &source);
TASKS
.iter()
.map(|(_, task)| {
tokenizer.encode(
&format!("{head}<|start|>user<|message|>{task}<|end|><|start|>assistant"),
true,
)
})
.collect()
}
/// The optional numbers of the command line: pairs, max_new, threads and the characters of the source.
fn parse_options(args: &[String]) -> (usize, usize, usize, usize) {
let arg = |i: usize, default: usize| args.get(i).and_then(|s| s.parse().ok()).unwrap_or(default);
(
arg(2, 3),
arg(3, 320),
arg(4, std::thread::available_parallelism().map_or(1, |n| n.get())),
arg(5, 2400),
)
}
/// The engine with a context for the longest prompt, and its stop tokens; says what it is about to measure.
fn start_engine(
model: &Path,
(threads, pairs, max_new): (usize, usize, usize),
prompts: &[Vec<u32>],
) -> (engine::GptOssEngine, Vec<u32>) {
let context = prompts.iter().map(Vec::len).max().unwrap_or(0) + max_new + 64;
let loaded = engine::load(&LoadOptions {
model,
threads,
context,
warm: true,
})
.expect("load");
eprintln!(
"ab_speculation: {} prompts of {:?} tokens, {pairs} pairs, max_new {max_new}, {threads} threads",
prompts.len(),
prompts.iter().map(Vec::len).collect::<Vec<_>>()
);
(loaded.engine, loaded.stop_tokens)
}
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 (pairs, max_new, threads, chars) = parse_options(&args);
let model = Path::new(&args[0]);
let tokenizer = read_tokenizer(model);
let prompts = task_prompts(&tokenizer, (&args[1], chars));
if let Ok(path) = std::env::var("LELEKA_AB_REPLAY") {
policy_replay::replay_policies(&tokenizer, &prompts, &path);
return;
}
let (mut engine, stops) = start_engine(model, (threads, pairs, max_new), &prompts);
// 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 summary: Vec<String> = prompts
.iter()
.enumerate()
.map(|(i, prompt)| measure_task(&mut engine, &stops, (i, prompt), (pairs, max_new), &tokenizer))
.collect();
for line in summary {
println!("{line}");
}
}