//! Model scores become validated proposals through one explicit admission boundary. use crate::actions::{Action, ActionKind, InputError, Program, parse_command}; use crate::dataset::DatasetError; use crate::episodic::EpisodicMemory; use crate::model::{ModelBundle, ModelError}; use crate::tokenizer::{TokenizerError, collate, encode}; use tch::Kind; use thiserror::Error; /// Runtime refusal or infrastructure error; only refusal variants are evaluation rejections. #[derive(Debug, Error)] pub enum InferenceError { /// Invalid instruction syntax or an incompatible typed action argument. #[error(transparent)] Input(#[from] InputError), /// The learned reject category received the largest probability. #[error("This operation is outside the supported action set.")] UnsupportedIntent, /// The selected action failed the calibrated confidence or margin requirement. #[error("The model is uncertain; rephrase the requested operation.")] Uncertain, /// The model returned an invalid probability vector. #[error("The model returned invalid probabilities.")] InvalidScores, /// Tokenization failed despite the validated artifact and command boundary. #[error(transparent)] Tokenizer(#[from] TokenizerError), /// Clause key normalization for episodic lookup failed. #[error(transparent)] Dataset(#[from] DatasetError), /// A model operation failed; this must not be counted as a semantic rejection. #[error(transparent)] Model(#[from] ModelError), /// Native tensor computation failed. #[error(transparent)] Tensor(#[from] tch::TchError), } impl InferenceError { /// Identify expected command refusals without hiding infrastructure failures. pub fn is_refusal(&self) -> bool { matches!( self, Self::Input(_) | Self::UnsupportedIntent | Self::Uncertain ) } } /// Score all fixed labels for an already normalized clause, without recording gradients. pub fn probabilities(bundle: &ModelBundle, phrase: &str) -> Result, InferenceError> { let encoded = encode( phrase, &bundle.metadata.vocab, &bundle.metadata.architecture, )?; let (words, characters) = collate(&[encoded], &bundle.metadata.architecture)?; let scores = tch::no_grad(|| { bundle .model .forward(&words, &characters, false)? .f_softmax(-1, Kind::Float) .map_err(ModelError::from) })?; let values = Vec::::try_from(scores.f_squeeze_dim(0)?)?; if values.len() != bundle.metadata.labels.len() || values .iter() .any(|value| !value.is_finite() || !(0.0..=1.0).contains(value)) { return Err(InferenceError::InvalidScores); } Ok(values.into_iter().map(f64::from).collect()) } /// Classify one or two clauses and render only validated members of the fixed action set. pub fn predict(bundle: &ModelBundle, command: &str) -> Result { predict_with_episodic(bundle, None, command) } /// Classify one or two clauses, consulting optional verified episodic memory before neural scoring. /// /// Law: `predict_with_episodic(bundle, None, cmd) == predict(bundle, cmd)` for all `cmd`. /// Every episodic hit passes the identical `Action::new` and `Program::new` invariants. pub fn predict_with_episodic( bundle: &ModelBundle, episodic: Option<&EpisodicMemory>, command: &str, ) -> Result { let clauses = parse_command(command)?; let mut actions = Vec::with_capacity(clauses.len()); for clause in clauses { if let Some(label) = episodic .map(|memory| memory.lookup_clause(&clause.text)) .transpose()? .flatten() { if label == "reject" { return Err(InferenceError::UnsupportedIntent); } actions.push(Action::new(ActionKind::from_label(label)?, clause.name)?); continue; } let scores = probabilities(bundle, &clause.text)?; let mut ranked: Vec<_> = scores.into_iter().enumerate().collect(); ranked.sort_by(|left, right| { right .1 .total_cmp(&left.1) .then_with(|| left.0.cmp(&right.0)) }); let (index, confidence) = ranked.first().ok_or(InferenceError::InvalidScores)?; let (_, runner_up) = ranked.get(1).ok_or(InferenceError::InvalidScores)?; let label = bundle .metadata .labels .get(*index) .ok_or(InferenceError::InvalidScores)?; if label == "reject" { return Err(InferenceError::UnsupportedIntent); } let limits = &bundle.metadata.thresholds; if *confidence < limits.probability || confidence - runner_up < limits.margin { return Err(InferenceError::Uncertain); } actions.push(Action::new(ActionKind::from_label(label)?, clause.name)?); } Ok(Program::new(actions)?) } #[cfg(test)] mod tests { use std::collections::BTreeMap; use std::path::Path; use super::*; use crate::runtime::test_serial_guard; #[test] fn episodic_memory_composes_with_neural_inference_and_vetoes_rejections() -> Result<(), Box> { let _guard = test_serial_guard(); let root = Path::new(env!("CARGO_MANIFEST_DIR")); let bundle = ModelBundle::load(root)?; // Without episodic memory, an invented idiom is refused. assert!(predict(&bundle, "beam into dossier \"notes.el\"").is_err()); let memory = EpisodicMemory::new(BTreeMap::from([ ( String::from("beam into dossier name"), String::from("find-file"), ), ( String::from("save the current buffer"), String::from("reject"), ), ]))?; // Episodic clause composes with an ordinary neural second clause in one pass. let composed = predict_with_episodic( &bundle, Some(&memory), "beam into dossier \"notes.el\" then split right", )?; assert_eq!( composed.to_lisp(), "(progn (find-file \"notes.el\") (split-window-right))" ); // Episodic reject overrides even a high-confidence neural positive clause. assert!(matches!( predict_with_episodic(&bundle, Some(&memory), "save the current buffer"), Err(InferenceError::UnsupportedIntent) )); Ok(()) } }