diff --git a/crates/cpu-worker/examples/ab_speculation.rs b/crates/cpu-worker/examples/ab_speculation.rs index df010cff..e3334205 100644 --- a/crates/cpu-worker/examples/ab_speculation.rs +++ b/crates/cpu-worker/examples/ab_speculation.rs @@ -16,13 +16,15 @@ 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}; +#[path = "ab_speculation/policy_replay.rs"] +mod policy_replay; + const TASKS: [(&str, &str); 4] = [ ( "rewrite", @@ -116,122 +118,6 @@ fn parse_run(text: &str) -> Run { 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 -} - -/// The recorded greedy output of every task in a replay file: the `ids:` line, else the re-tokenized `output:` text. -fn recorded_outputs(tokenizer: &GgufBpe, text: &str, path: &str) -> Vec> { - let mut outputs: Vec> = 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}"); - } - outputs -} - -/// Every drafting policy of the grid that is replayed. -fn policy_grid() -> Vec { - let mut grid = Vec::new(); - for min_match in [2, 3, 4] { - for prior in [(2.0, 1.0), (4.0, 1.0), (9.0, 1.0)] { - extend_grid(&mut grid, min_match, prior); - } - } - grid -} - -/// The policies with this `min_match` and `prior` over the grid of the other settings. -fn extend_grid(grid: &mut Vec, min_match: usize, prior: (f64, f64)) { - 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] { - grid.push(Policy { - min_match, - max_draft: MAX_DRAFT, - prior, - forget, - min_gain, - probe_after, - }); - } - } - } -} - -/// A policy with its speed-up on every task and their geometric mean. -type PolicyRow = (Policy, Vec, f64); - -fn show_row((policy, gains, geomean): &PolicyRow) { - 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::>(), - policy - ); -} - -/// `LELEKA_AB_REPLAY=`: 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], path: &str) { - let text = std::fs::read_to_string(path).expect("replay file"); - let outputs = recorded_outputs(tokenizer, &text, path); - let mut rows: Vec = Vec::new(); - for policy in policy_grid() { - let gains: Vec = prompts - .iter() - .zip(&outputs) - .map(|(p, o)| replay(policy, p, o, &MEASURED_COST).speedup()) - .collect(); - let geomean = gains.iter().map(|g| g.ln()).sum::() / gains.len() as f64; - rows.push((policy, gains, geomean.exp())); - } - let default = rows.iter().find(|r| r.0 == Policy::default()); - println!("default policy:"); - default.into_iter().for_each(show_row); - 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_row); -} - /// The shared system and developer messages and the source file every task is asked about. fn prompt_head(name: &str, source: &str) -> String { format!( @@ -387,7 +273,7 @@ fn main() { let tokenizer = read_tokenizer(model); let prompts = task_prompts(&tokenizer, (&args[1], chars)); if let Ok(path) = std::env::var("LELEKA_AB_REPLAY") { - replay_policies(&tokenizer, &prompts, &path); + policy_replay::replay_policies(&tokenizer, &prompts, &path); return; } diff --git a/crates/cpu-worker/examples/ab_speculation/policy_replay.rs b/crates/cpu-worker/examples/ab_speculation/policy_replay.rs new file mode 100644 index 00000000..f86865b0 --- /dev/null +++ b/crates/cpu-worker/examples/ab_speculation/policy_replay.rs @@ -0,0 +1,121 @@ +//! Replaying drafting policies over recorded outputs, without a model (`LELEKA_AB_REPLAY`). + +use super::TASKS; +use leleka_gptoss::speculate::{MAX_DRAFT, MEASURED_COST, Policy, replay}; +use leleka_tokenizer::gguf_bpe::GgufBpe; + +/// 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 +} + +/// The recorded greedy output of every task in a replay file: the `ids:` line, else the re-tokenized `output:` text. +fn recorded_outputs(tokenizer: &GgufBpe, text: &str, path: &str) -> Vec> { + let mut outputs: Vec> = 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}"); + } + outputs +} + +/// Every drafting policy of the grid that is replayed. +fn policy_grid() -> Vec { + let mut grid = Vec::new(); + for min_match in [2, 3, 4] { + for prior in [(2.0, 1.0), (4.0, 1.0), (9.0, 1.0)] { + extend_grid(&mut grid, min_match, prior); + } + } + grid +} + +/// The policies with this `min_match` and `prior` over the grid of the other settings. +fn extend_grid(grid: &mut Vec, min_match: usize, prior: (f64, f64)) { + 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] { + grid.push(Policy { + min_match, + max_draft: MAX_DRAFT, + prior, + forget, + min_gain, + probe_after, + }); + } + } + } +} + +/// A policy with its speed-up on every task and their geometric mean. +type PolicyRow = (Policy, Vec, f64); + +fn show_row((policy, gains, geomean): &PolicyRow) { + 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::>(), + policy + ); +} + +/// `LELEKA_AB_REPLAY=`: 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. +pub(super) fn replay_policies(tokenizer: &GgufBpe, prompts: &[Vec], path: &str) { + let text = std::fs::read_to_string(path).expect("replay file"); + let outputs = recorded_outputs(tokenizer, &text, path); + let mut rows: Vec = Vec::new(); + for policy in policy_grid() { + let gains: Vec = prompts + .iter() + .zip(&outputs) + .map(|(p, o)| replay(policy, p, o, &MEASURED_COST).speedup()) + .collect(); + let geomean = gains.iter().map(|g| g.ln()).sum::() / gains.len() as f64; + rows.push((policy, gains, geomean.exp())); + } + let default = rows.iter().find(|r| r.0 == Policy::default()); + println!("default policy:"); + default.into_iter().for_each(show_row); + 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_row); +}