Ryan.K
Publish open-vocabulary bi-encoder, continual learning, and technical paper
4a54697 unverified Download src/inference.rs from ElderRyan/lispm-llm: direct link, hf CLI and curl.
- Browser
- Download file 6.66 kB
-
https://huggingface.co/ElderRyan/lispm-llm/resolve/main/src/inference.rs
- Command line
-
hf download hf://ElderRyan/lispm-llm/src/inference.rs
-
curl -L -o inference.rs https://huggingface.co/ElderRyan/lispm-llm/resolve/main/src/inference.rs
6.66 kB
| //! 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. | |
| pub enum InferenceError { | |
| /// Invalid instruction syntax or an incompatible typed action argument. | |
| Input( InputError), | |
| /// The learned reject category received the largest probability. | |
| UnsupportedIntent, | |
| /// The selected action failed the calibrated confidence or margin requirement. | |
| Uncertain, | |
| /// The model returned an invalid probability vector. | |
| InvalidScores, | |
| /// Tokenization failed despite the validated artifact and command boundary. | |
| Tokenizer( TokenizerError), | |
| /// Clause key normalization for episodic lookup failed. | |
| Dataset( DatasetError), | |
| /// A model operation failed; this must not be counted as a semantic rejection. | |
| Model( ModelError), | |
| /// Native tensor computation failed. | |
| Tensor( 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<Vec<f64>, 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::<f32>::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<Program, InferenceError> { | |
| 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<Program, InferenceError> { | |
| 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)?) | |
| } | |
| mod tests { | |
| use std::collections::BTreeMap; | |
| use std::path::Path; | |
| use super::*; | |
| use crate::runtime::test_serial_guard; | |
| fn episodic_memory_composes_with_neural_inference_and_vetoes_rejections() | |
| -> Result<(), Box<dyn std::error::Error>> { | |
| 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(()) | |
| } | |
| } | |