diff --git a/crates/weksa/src/context.rs b/crates/weksa/src/context.rs index 152ff76..eb1f6bc 100644 --- a/crates/weksa/src/context.rs +++ b/crates/weksa/src/context.rs @@ -263,8 +263,6 @@ impl EditFeedback { } } - // Called by run::cycle (cut commit 5 of golf-loop-edit-accept). - #[allow(dead_code)] /// `last`: whether the previous edit was accepted; `head`: the composite at /// the current inventory, rounded here to the nearest [`LADDER_STEP`]. pub(crate) fn new(last: Option, head: Option) -> Self { diff --git a/crates/weksa/src/lib.rs b/crates/weksa/src/lib.rs index f61a9b6..c741c62 100644 --- a/crates/weksa/src/lib.rs +++ b/crates/weksa/src/lib.rs @@ -23,7 +23,7 @@ pub mod store; pub mod validate; pub use corpus::{CorpusItem, CorpusItemId, NameSpan, Source, Turn}; -pub use encode::PacketDraft; +pub use encode::{EditDraft, PacketDraft}; pub use entity::{Entity, EntityOrigin, LanguageForms, Pronunciation}; pub use form::FormError; pub use inventory::{ @@ -36,7 +36,7 @@ pub use packet::{ EncoderId, EntityId, Grade, NodeId, Packet, PacketId, PacketKind, SCHEMA_VERSION, Stance, }; pub use phones::{Phone, PhoneInventory, SegmentError, Stress}; -pub use run::{RoundRecord, RunStores, round}; +pub use run::{Decision, RoundRecord, RunStores, cycle, round}; pub use score::{Embedder, ItemScore, OllamaEmbedder, Scorer, chrf}; pub use speaker::{Annotator, PairRelation, Party, Scene, Speaker}; pub use split::{Split, SplitScheme}; diff --git a/crates/weksa/src/main.rs b/crates/weksa/src/main.rs index 5e7eb28..7901ca5 100644 --- a/crates/weksa/src/main.rs +++ b/crates/weksa/src/main.rs @@ -11,7 +11,7 @@ use weksa::corpus::{CorpusItem, ModelFamily, NameSpan, Source, Turn}; use weksa::entity::{Entity, EntityOrigin, LanguageForms, Pronunciation}; use weksa::inventory::{proof_revision, seed}; use weksa::packet::proof_packet; -use weksa::run::{RoundOutcome, RunPaths, RunStores, round}; +use weksa::run::{CycleOutcome, RoundOutcome, RunPaths, RunStores, cycle, round}; use weksa::score::ScoreInput; use weksa::{ AnswerFiles, CorpusStore, EntityId, EntityStore, InventoryStore, OllamaEmbedder, PacketStore, @@ -98,6 +98,15 @@ enum LoopCommand { #[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. Prompts without answers are written to the + /// cycle's directory and the command exits 3; rerun after the `.answer` + /// files exist. + Cycle { + root: PathBuf, + #[arg(long, default_value = "http://127.0.0.1:11434")] + ollama_url: String, + }, } #[derive(Subcommand)] @@ -758,6 +767,25 @@ fn main() -> Result<()> { RoundOutcome::Recorded(r) => println!("{}", r.summary_line()), } } + Command::Loop(LoopCommand::Cycle { root, ollama_url }) => { + let unreadable = |_| anyhow::anyhow!("a store would not read"); + let mut run = RunStores::open(&root)?; + let mut files = AnswerFiles::new( + run.next_cycle_dir().map_err(unreadable)?, + run.record().model.clone(), + ); + let scorer = Scorer::new(OllamaEmbedder::new(&ollama_url, &run.record().embedder)); + match cycle(&mut run, &mut files, &scorer)? { + CycleOutcome::Unanswered { prompts } => { + for digest in &prompts { + println!("unanswered {digest}"); + } + println!("unanswered {} prompts", prompts.len()); + std::process::exit(3); + } + CycleOutcome::Decided(decision) => println!("{}", decision.summary_line()), + } + } Command::Schema { out } => { std::fs::create_dir_all(&out)?; for (name, json) in weksa::schema::published() { diff --git a/crates/weksa/src/run.rs b/crates/weksa/src/run.rs index 4120100..060f929 100644 --- a/crates/weksa/src/run.rs +++ b/crates/weksa/src/run.rs @@ -1,5 +1,8 @@ -//! One golf-loop run: the stores it pinned at open, the rounds it has recorded, -//! and the one writer of both (`RunStores::create` and, for rounds, `round`). +//! One golf-loop run: the stores it pinned at open, the rounds and decisions it +//! has recorded, and the one writer of all of them (`RunStores::create`, `round` +//! and `cycle`). A cycle asks an editor for one inventory edit, scores a +//! candidate round under it and accepts or rejects on Validation (`decide`); the +//! latest Accepted decision names the run's head inventory. //! //! A run pins its corpus and entity store files by canonical path and FNV-1a 64 //! digest of their bytes. It works on its own copy of the inventory: @@ -23,9 +26,9 @@ use cultcache_rs::{CultCache, DatabaseEntry}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; -use crate::context::{EncoderOffer, Prompt, TrainItems}; +use crate::context::{EditFeedback, EncoderOffer, Prompt, TrainItems}; use crate::corpus::{CorpusItem, CorpusItemId}; -use crate::encode::{PacketDraft, encoder_id}; +use crate::encode::{EditDraft, PacketDraft, encoder_id}; use crate::form::{is_attestation, is_slug}; use crate::lower::lower; use crate::model::{ModelPort, PortError}; @@ -329,6 +332,10 @@ pub enum RunError { Store, /// The embedder failed. Embed, + /// Rounds 1 and 2 are not two plain replicates under the run's first inventory. + NoFloor, + /// A round has no Validation reading. + NoValidation, } impl fmt::Display for RunError { @@ -342,6 +349,8 @@ impl fmt::Display for RunError { RunError::Io(kind) => write!(f, "io error {kind:?}"), RunError::Store => f.write_str("a store would not read or write"), RunError::Embed => f.write_str("the embedder failed"), + RunError::NoFloor => f.write_str("the run has no noise floor: record two rounds first"), + RunError::NoValidation => f.write_str("a reading has no validation item"), } } } @@ -395,7 +404,8 @@ fn canonical(path: &Path) -> Result { fn run_cache(root: &Path) -> Result { open_cache(&root.join("run.cc"), |c| { c.register_entry_type::()?; - c.register_entry_type::() + c.register_entry_type::()?; + c.register_entry_type::() }) .map_err(|_| RunError::Store) } @@ -480,7 +490,8 @@ impl RunStores { if file_digest(&record.entities).as_ref() != Some(&record.entity_digest) { return Err(RunError::Drift(DriftOf::Entities)); } - if file_digest_at(&root.join(INVENTORY_FILE)).as_ref() != Some(&record.inventory_digest) { + let (path, digest, _) = head_of(&cache, root, &record)?; + if file_digest_at(&path).as_ref() != Some(&digest) { return Err(RunError::Drift(DriftOf::Inventory)); } Self::with(root, cache, record) @@ -488,10 +499,11 @@ impl RunStores { fn with(root: &Path, cache: CultCache, record: RunRecord) -> Result { let store = |_| RunError::Store; + let (head, _, _) = head_of(&cache, root, &record)?; Ok(Self { root: root.to_path_buf(), corpus: CorpusStore::open(Path::new(&record.corpus)).map_err(store)?, - inventory: InventoryStore::open(&root.join(INVENTORY_FILE)).map_err(store)?, + inventory: InventoryStore::open(&head).map_err(store)?, entities: EntityStore::open(Path::new(&record.entities)).map_err(store)?, cache, record, @@ -547,6 +559,23 @@ impl RunStores { Ok(rounds) } + /// The recorded decisions, by cycle. + pub fn decisions(&self) -> anyhow::Result> { + decisions_of(&self.cache) + } + + /// The head inventory file, its digest and its establishing round. + fn head(&self) -> Result<(PathBuf, String, u32), RunError> { + head_of(&self.cache, &self.root, &self.record) + } + + /// `/cycle-` for the next undecided cycle `k`. + pub fn next_cycle_dir(&self) -> anyhow::Result { + Ok(self + .root + .join(format!("cycle-{}", self.decisions()?.len() + 1))) + } + /// `/round-` for the next unrecorded round `n`. pub fn next_round_dir(&self) -> anyhow::Result { Ok(self @@ -555,8 +584,42 @@ impl RunStores { } } -/// What a round came to. +fn decisions_of(cache: &CultCache) -> anyhow::Result> { + let mut decisions = cache.get_all::()?; + decisions.sort_by_key(Decision::k); + Ok(decisions) +} + +/// The head is derived, never stored: the latest Accepted decision names it +/// (`/cycle-/inventory.cc`, its candidate digest, its candidate round); +/// with none it is the copy `create` made and round 1. +fn head_of( + cache: &CultCache, + root: &Path, + record: &RunRecord, +) -> Result<(PathBuf, String, u32), RunError> { + let decisions = decisions_of(cache).map_err(|_| RunError::Store)?; + let accepted = decisions.iter().rfind(|d| d.verdict == Verdict::Accepted); + match accepted { + None => Ok(( + root.join(INVENTORY_FILE), + record.inventory_digest.clone(), + 1, + )), + Some(d) => Ok(( + root.join(format!("cycle-{}", d.k)).join(INVENTORY_FILE), + d.candidate_inventory_digest + .clone() + .ok_or(RunError::Store)?, + d.candidate_round.ok_or(RunError::Store)?, + )), + } +} + +/// What a round came to. One is built per call and matched at once, so the +/// size of the record is not worth an indirection. #[derive(Debug)] +#[allow(clippy::large_enum_variant)] pub enum RoundOutcome { /// Prompts nobody has answered; nothing was written to the run or admitted. Unanswered { @@ -588,7 +651,7 @@ pub fn round( check_drift(run, model, scorer)?; let store = |_| RunError::Store; let dir = run.next_round_dir().map_err(store)?; - let digest = run.record.inventory_digest.clone(); + let (_, digest, _) = run.head()?; match score_round(run, &run.inventory, &digest, &dir, None, model, scorer)? { RoundOutcome::Recorded(record) => { run.cache @@ -789,6 +852,386 @@ fn score_round( Ok(RoundOutcome::Recorded(record)) } +/// One validation reading: chrF 0 to 100, meaning 0 to 1, and their composite. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct Reading { + pub chrf: f64, + pub meaning: f64, + pub composite: f64, +} + +impl Reading { + /// `None` when the split has no items or no chrF; a missing meaning reads as + /// 0. The composite is the mean of chrF as a fraction and meaning. + pub fn of(mean: &SplitMean) -> Option { + if mean.count == 0 { + return None; + } + let chrf = mean.chrf?; + let meaning = mean.meaning.unwrap_or(0.0); + Some(Self { + chrf, + meaning, + composite: (chrf / 100.0 + meaning) / 2.0, + }) + } +} + +/// Which metric an edit regressed. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +pub enum Metric { + Chrf, + Meaning, +} + +/// Why an edit was rejected. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +pub enum Why { + /// The answer was not an edit draft. + EditParse, + /// The draft asked for no change or too many, or the inventory door refused it. + EditAdmit, + NoGain, + Regressed(Metric), +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +pub enum Verdict { + Accepted, + Rejected(Why), +} + +/// The smallest composite gain that accepts an edit: the measured floor, but +/// never under one [`LADDER_STEP`], so a zero floor from identical replicates +/// does not let a rounding-error gain through. +pub fn threshold(floor: &Reading) -> f64 { + floor.composite.max(LADDER_STEP) +} + +/// The accept rule. A metric that falls by more than its tolerance (the floor, +/// at least one step) rejects; otherwise the composite must gain strictly more +/// than [`threshold`]. Means count a refused Validation item as 0, so refusing a +/// weak item cannot raise a reading. +pub fn decide(base: &Reading, candidate: &Reading, floor: &Reading) -> Verdict { + if candidate.chrf - base.chrf < -floor.chrf.max(100.0 * LADDER_STEP) { + Verdict::Rejected(Why::Regressed(Metric::Chrf)) + } else if candidate.meaning - base.meaning < -floor.meaning.max(LADDER_STEP) { + Verdict::Rejected(Why::Regressed(Metric::Meaning)) + } else if candidate.composite - base.composite > threshold(floor) { + Verdict::Accepted + } else { + Verdict::Rejected(Why::NoGain) + } +} + +/// One closed edit-accept cycle: digests and numbers, no text. Key +/// `run: