diff --git a/crates/weksa/src/main.rs b/crates/weksa/src/main.rs index f70887a..6ce2281 100644 --- a/crates/weksa/src/main.rs +++ b/crates/weksa/src/main.rs @@ -15,7 +15,7 @@ use weksa::packet::{FeatValue, FeatureValue, Grade}; use weksa::packet::proof_packet; use weksa::model::{ModelPort, RecordedAnswers}; use weksa::run::{ - AblationOutcome, CycleOutcome, LowererReach, OntologyMintOutcome, RecallOutcome, RelowerOutcome, RoundOutcome, RunPaths, RunStores, cycle, round, + AblationOutcome, CalibrateOutcome, CycleOutcome, FLOOR_ARMS_MIN, LowererReach, OntologyMintOutcome, RecallOutcome, RelowerOutcome, RoundOutcome, RunPaths, RunStores, cycle, round, }; use weksa::score::ScoreInput; use weksa::{ @@ -174,6 +174,31 @@ enum LoopCommand { #[arg(long, default_value = "http://127.0.0.1:11434")] ollama_url: String, }, + /// Replay the accept rule over answered relower draws of round ROUND, to + /// measure how often it accepts, rejects or regresses what it should. Reads + /// the recorded lowering and each draw (--prompted: repeats of it, at least + /// four; --degraded: arms that should regress; --candidate: arms to rate), + /// answered through `weksa loop relower ROOT --round N --arm LABEL`, and + /// prints counts over all Validation items and over each --class + /// NAME=PREFIX[,PREFIX...] (items whose key starts with a prefix). Writes + /// no prompts; exits 1 naming the draws still unanswered. Procedure: + /// docs/calibration.md. A diagnostic, never a gate; records nothing; Test + /// and Train are never touched. Labels match [a-z0-9-]{1,32} and differ. + Calibrate { + root: PathBuf, + #[arg(long)] + round: u32, + #[arg(long)] + prompted: Vec, + #[arg(long)] + degraded: Vec, + #[arg(long)] + candidate: Vec, + #[arg(long)] + class: Vec, + #[arg(long, default_value = "http://127.0.0.1:11434")] + ollama_url: String, + }, /// Run one edit-accept cycle of the run at ROOT. The stores are read only /// from the run's record. The editor's prompt, then the candidate round's /// encode prompts, then its lowering prompts are written in turn; the @@ -661,6 +686,12 @@ impl AddArgs { } /// The split of an item as `Train`, `Validation`, `Test` or `excluded`. +/// A draw or arm label: [a-z0-9-]{1,32}. +fn is_label(l: &str) -> bool { + (1..=32).contains(&l.len()) + && l.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') +} + fn split_text(item: &CorpusItem) -> String { SplitScheme::V1 .split(item) @@ -1146,12 +1177,8 @@ fn main() -> Result<()> { floor, ollama_url, }) => { - let label = |l: &str| { - (1..=32).contains(&l.len()) - && l.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') - }; - if !label(&arm) - || floor.iter().any(|f| !label(f) || *f == arm) + if !is_label(&arm) + || floor.iter().any(|f| !is_label(f) || *f == arm) || floor.iter().enumerate().any(|(i, f)| floor[..i].contains(f)) { anyhow::bail!("arm and floor labels must match [a-z0-9-]{{1,32}} and differ"); @@ -1197,6 +1224,95 @@ fn main() -> Result<()> { } } } + Command::Loop(LoopCommand::Calibrate { + root, + round, + prompted, + degraded, + candidate, + class, + ollama_url, + }) => { + let labels: Vec<&String> = prompted.iter().chain(°raded).chain(&candidate).collect(); + if labels.iter().any(|l| !is_label(l)) + || labels.iter().enumerate().any(|(i, l)| labels[..i].contains(l)) + { + anyhow::bail!("draw labels must match [a-z0-9-]{{1,32}} and differ"); + } + if prompted.len() < FLOOR_ARMS_MIN + 1 { + anyhow::bail!("at least {} --prompted labels are needed", FLOOR_ARMS_MIN + 1); + } + let mut classes: Vec<(String, Vec)> = Vec::new(); + for c in &class { + let Some((name, prefixes)) = c.split_once('=') else { + anyhow::bail!("--class is NAME=PREFIX[,PREFIX...]"); + }; + if !is_label(name) + || name == "all" + || classes.iter().any(|(n, _)| n == name) + || prefixes.split(',').any(str::is_empty) + { + anyhow::bail!("--class is NAME=PREFIX[,PREFIX...] with a new label NAME other than all"); + } + classes.push((name.to_string(), prefixes.split(',').map(String::from).collect())); + } + let run = RunStores::open(&root)?; + let scorer = Scorer::new(OllamaEmbedder::new(&ollama_url, &run.record().embedder)); + match run.calibrate(round, &prompted, °raded, &candidate, &classes, &scorer)? { + CalibrateOutcome::Unanswered(missing) => { + for (label, n) in &missing { + println!("unanswered {label} {n}"); + } + eprintln!( + "answer it through weksa loop relower ROOT --round N --arm LABEL first" + ); + std::process::exit(1); + } + CalibrateOutcome::Read { unusable, classes } => { + println!( + "{}", + run.labelled(&format!( + "calibrate draws prompted={} degraded={} candidate={} floor-arms={FLOOR_ARMS_MIN} unusable={unusable}", + prompted.len(), + degraded.len(), + candidate.len(), + )) + ); + for c in classes { + let items: String = c + .languages + .iter() + .map(|l| format!(" {} n={} skipped={}", l.language, l.n, l.skipped)) + .collect(); + let t = &c.trials; + println!("{}", run.labelled(&format!("calibrate class={} items{items}", c.name))); + println!( + "{}", + run.labelled(&format!( + "calibrate class={} prompted trials={} nogain={} accepted={} regressed={} noise={:.4}", + c.name, t.prompted.trials, t.prompted.nogain, t.prompted.accepted, t.prompted.regressed, t.noise + )) + ); + for (label, d) in degraded.iter().zip(&t.degraded) { + println!( + "{}", + run.labelled(&format!( + "calibrate class={} degraded={label} trials={} regressed={}", + c.name, d.trials, d.regressed + )) + ); + } + println!( + "{}", + run.labelled(&format!( + "calibrate class={} candidate trials={} accepted={} nogain={} regressed={}", + c.name, t.candidate.trials, t.candidate.accepted, t.candidate.nogain, t.candidate.regressed + )) + ); + } + } + } + } Command::Loop(LoopCommand::Recall { root }) => { let run = RunStores::open(&root)?; let mut files = run.answer_files(run.recall_dir())?; diff --git a/crates/weksa/src/run.rs b/crates/weksa/src/run.rs index 3819e3a..d1ee79e 100644 --- a/crates/weksa/src/run.rs +++ b/crates/weksa/src/run.rs @@ -44,7 +44,7 @@ use crate::encode::{ EditDraft, LoweringDraft, MAX_EDIT_CHANGES, OntologyDraft, PacketDraft, encoder_id, }; use crate::form::{is_attestation, is_language_tag, is_slug}; -use crate::model::{AnswerFiles, ModelPort, PortError}; +use crate::model::{AnswerFiles, ModelPort, PortError, RecordedAnswers}; use crate::packet::{Packet, Stance}; use crate::score::{CHRF_VERSION, chrf, Embedder, ItemScore, ScoreInput, Scorer, SplitMean, aggregate, validation_items}; use crate::split::{Split, SplitScheme, fnv1a64, fnv1a64_of, hex16}; @@ -1863,6 +1863,215 @@ fn reading_of(scored: &[ItemScore]) -> Result { .ok_or(RunError::NoValidation) } +/// How trials of one kind read: counts, not rates. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Counts { + pub trials: u32, + pub accepted: u32, + pub nogain: u32, + pub regressed: u32, +} + +impl Counts { + fn tally(&mut self, v: Verdict) { + self.trials += 1; + match v { + Verdict::Accepted => self.accepted += 1, + Verdict::Rejected(Why::Regressed(_)) => self.regressed += 1, + Verdict::Rejected(_) => self.nogain += 1, + } + } +} + +/// What [`calibration_trials`] counted over one set of items. +#[derive(Clone, Debug, PartialEq)] +pub struct Trials { + /// Ordered (base, candidate) pairs of prompted draws, each over every floor. + pub prompted: Counts, + /// Per degraded arm in the order given: the arm as the candidate. + pub degraded: Vec, + /// Every candidate arm as the candidate, pooled. + pub candidate: Counts, + /// The mean of [`panel_noise`] over every (base, floor) choice. + pub noise: f64, +} + +/// Every `k`-subset of `pool`, in order. +fn subsets(pool: &[usize], k: usize) -> Vec> { + if k == 0 { + return vec![Vec::new()]; + } + let mut out = Vec::new(); + for (i, &first) in pool.iter().enumerate() { + for mut rest in subsets(&pool[i + 1..], k - 1) { + rest.insert(0, first); + out.push(rest); + } + } + out +} + +/// The accept rule replayed over draws that are all lowerings of one round, as +/// the live loop would meet them: [`decide_panel`] over (base, candidate, +/// [`paired_floor`] of the base against `FLOOR_ARMS_MIN` other prompted draws), +/// one row per language. `draws` is `[port][language][item]`; ports +/// `0..prompted` are prompted draws (the recorded lowering first), then +/// `degraded` and `candidate` ports follow. A language with no items reads +/// NaN, which fails closed. +pub fn calibration_trials( + draws: &[Vec>], + prompted: usize, + degraded: usize, + candidate: usize, +) -> Trials { + let languages = draws.first().map_or(0, Vec::len); + let rows = |b: usize, c: usize, floors: &[usize]| -> Vec<(Reading, Reading, Reading)> { + let read = |scores: &[ItemScore]| { + reading_of(scores).unwrap_or(Reading { chrf: f64::NAN, meaning: f64::NAN, composite: f64::NAN }) + }; + (0..languages) + .map(|l| { + let arms: Vec> = floors.iter().map(|&f| draws[f][l].clone()).collect(); + (read(&draws[b][l]), read(&draws[c][l]), paired_floor(&draws[b][l], &arms)) + }) + .collect() + }; + let pool: Vec = (0..prompted).collect(); + let without = |out: &[usize]| -> Vec { pool.iter().copied().filter(|p| !out.contains(p)).collect() }; + let (mut prompted_counts, mut candidate_counts) = (Counts::default(), Counts::default()); + let mut degraded_counts = vec![Counts::default(); degraded]; + let (mut noise, mut noises) = (0.0, 0u32); + for &b in &pool { + for floors in subsets(&without(&[b]), FLOOR_ARMS_MIN) { + for (d, counts) in degraded_counts.iter_mut().enumerate() { + counts.tally(decide_panel(&rows(b, prompted + d, &floors))); + } + for c in prompted + degraded..prompted + degraded + candidate { + candidate_counts.tally(decide_panel(&rows(b, c, &floors))); + } + noise += panel_noise(&rows(b, b, &floors)); + noises += 1; + } + for &c in pool.iter().filter(|&&c| c != b) { + for floors in subsets(&without(&[b, c]), FLOOR_ARMS_MIN) { + prompted_counts.tally(decide_panel(&rows(b, c, &floors))); + } + } + } + Trials { + prompted: prompted_counts, + degraded: degraded_counts, + candidate: candidate_counts, + noise: noise / f64::from(noises), + } +} + +/// One panel language of a class: items read and live Validation items of the +/// class not read. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ClassLanguage { + pub language: String, + pub n: u32, + pub skipped: u32, +} + +/// The trials over one class of items. +#[derive(Clone, Debug, PartialEq)] +pub struct ClassTrials { + pub name: String, + pub languages: Vec, + pub trials: Trials, +} + +#[derive(Debug)] +pub enum CalibrateOutcome { + /// Draw labels with the number of prompts each has no answer to. + Unanswered(Vec<(String, u32)>), + /// `unusable` over every prompted, degraded and candidate draw; `all` first, + /// then the classes in the order given. + Read { unusable: u32, classes: Vec }, +} + +impl RunStores { + /// Replays the accept rule over answered relower draws: reads every draw of + /// round `n` (the recorded lowering and the `relower--