lispm-llm / src /evaluation.rs
Ryan.K
Publish open-vocabulary bi-encoder, continual learning, and technical paper
4a54697 unverified
Raw History Blame Contribute Delete
19.8 kB
//! Frozen-corpus evaluation is separate from all calibration and training decisions.
use crate::{
actions::{Action, ActionKind, Program, parse_command},
engine::ModelEngine,
inference::InferenceError,
model::ModelError,
};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::{collections::BTreeMap, fs, path::Path};
use thiserror::Error;
/// One frozen command and its expected rendered program, if supported.
#[derive(Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct EvaluationCase {
/// Materialized instruction with quoted literals preserved as data.
pub input: String,
/// Expected Lisp; `None` means the instruction is outside the action set.
pub expected: Option<String>,
/// Supported or unsupported source partition.
pub split: String,
/// Intended single-action label; two-action cases use `actions` and leave this null.
pub action: Option<String>,
/// Ordered labels for a two-action program; legacy single-action rows omit this field.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub actions: Vec<String>,
/// Optional family of deliberately unsupported requests.
pub group: Option<String>,
/// Membership in the historical comparison's shared vocabulary novelty slice.
pub novel_to_both: bool,
}
/// Cases and the immutable source corpus identity.
#[derive(Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Corpus {
/// SHA-256 of the source corpus, or of compact serialized derived cases.
pub sha256: String,
/// Exact overlap-filtered commands in source order.
pub cases: Vec<EvaluationCase>,
}
/// Portable evaluation input; this file is never read by the trainer.
#[derive(Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct EvaluationData {
/// Schema version of this materialized dataset.
pub format_version: u32,
/// Description of corpus exposure and exclusion policy.
pub policy: String,
/// Independently named frozen corpora.
pub corpora: BTreeMap<String, Corpus>,
}
/// Accepted correctness and refusals are disjoint counts, including unsupported inputs.
#[derive(Debug, Default, Serialize)]
pub struct Counts {
/// Number of inputs observed.
pub total: usize,
/// Accepted predictions whose rendered form equals the supported expectation.
pub correct: usize,
/// Accepted wrong actions, including false acceptance of unsupported input.
pub wrong: usize,
/// Instructions explicitly refused by the command or model boundary.
pub rejected: usize,
}
impl Counts {
/// Accumulate one decision while preserving the partition of all observations.
fn observe(&mut self, actual: Option<&str>, expected: Option<&str>) {
self.total += 1;
match actual {
None => self.rejected += 1,
Some(value) if Some(value) == expected => self.correct += 1,
Some(_) => self.wrong += 1,
}
}
}
/// A wrong acceptance or supported refusal retained for manual inspection.
#[derive(Debug, Serialize)]
pub struct Failure {
/// Original instruction, copied into the durable report.
pub input: String,
/// Required form, or `None` for unsupported input.
pub expected: Option<String>,
/// Accepted form, or `None` for refusal.
pub actual: Option<String>,
/// Admission failure message, when the command was refused.
pub reason: Option<String>,
}
/// Detailed outcomes for one frozen corpus.
#[derive(Debug, Default, Serialize)]
pub struct CorpusResult {
/// Original benchmark file identity.
pub source_sha256: String,
/// Supported-command accuracy, mistakes and coverage.
pub supported: Counts,
/// Unsupported-command false acceptances and refusals.
pub unsupported: Counts,
/// Identical historical vocabulary novelty subset.
pub novel_to_both_supported: Counts,
/// Unsupported operation families, such as duplicated browser tabs.
pub unsupported_groups: BTreeMap<String, Counts>,
/// Whole-program outcomes for requests containing each intended action.
/// A two-action request contributes once to each action, so these totals overlap.
pub per_action: BTreeMap<String, Counts>,
/// Concrete mistakes and supported refusals; correct negative refusals are omitted.
pub failures: Vec<Failure>,
}
/// Artifact-bound evaluation report, never consumed for checkpoint selection.
#[derive(Debug, Serialize)]
pub struct EvaluationReport {
/// Actual SafeTensors bytes evaluated, independent of historical Python checkpoint IDs.
pub weights_sha256: String,
/// Exact configuration bytes binding vocabulary, labels, architecture and admission.
pub config_sha256: String,
/// SHA-256 of the complete materialized evaluation dataset.
pub evaluation_data_sha256: String,
/// Artifact admission settings used without threshold tuning.
pub thresholds: crate::config::Thresholds,
/// Corpus exposure and separation policy.
pub policy: String,
/// Outcomes for each named source corpus.
pub corpora: BTreeMap<String, CorpusResult>,
}
/// Evaluation input, I/O or model failures; these never inflate refusal metrics.
#[derive(Debug, Error)]
pub enum EvaluationError {
/// Dataset or artifact read failed.
#[error(transparent)]
Io(#[from] std::io::Error),
/// Dataset cannot be decoded.
#[error(transparent)]
Json(#[from] serde_json::Error),
/// Unsupported schema or contradictory source partition.
#[error("Invalid evaluation schema or partition.")]
InvalidData,
/// A configuration or weight file changed while loading or scoring the model.
#[error("Model artifacts changed during evaluation; no report was produced.")]
ArtifactChanged,
/// Artifact validation or model construction failed before scoring.
#[error(transparent)]
Model(#[from] ModelError),
/// A native inference failure interrupted evaluation.
#[error(transparent)]
Inference(#[from] InferenceError),
}
/// Identity of both files that jointly determine an artifact's predictions.
#[derive(Debug, PartialEq, Eq)]
struct ArtifactSnapshot {
/// Actual weight serialization, separate from historical checkpoint provenance.
weights_sha256: String,
/// Vocabulary, architecture, label order, thresholds and provenance metadata.
config_sha256: String,
}
impl ArtifactSnapshot {
/// Read a snapshot before loading instead of attributing later files to old predictions.
fn read(directory: &Path) -> Result<Self, EvaluationError> {
Ok(Self {
weights_sha256: format!(
"{:x}",
Sha256::digest(fs::read(directory.join("model.safetensors"))?)
),
config_sha256: format!(
"{:x}",
Sha256::digest(fs::read(directory.join("config.json"))?)
),
})
}
/// Reject changed serialized inputs before a report can be emitted.
fn verify_unchanged(&self, directory: &Path) -> Result<(), EvaluationError> {
if self != &Self::read(directory)? {
return Err(EvaluationError::ArtifactChanged);
}
Ok(())
}
}
/// Recognize source identities instead of accepting arbitrary text as hashes.
fn is_sha256(value: &str) -> bool {
value.len() == 64
&& value
.bytes()
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
}
/// Reconstruct expected code only from ordered known labels and parsed literal arguments.
fn labeled_program(case: &EvaluationCase) -> Result<Program, EvaluationError> {
let labels: Vec<&str> = match (case.action.as_deref(), case.actions.as_slice()) {
(Some(label), []) => vec![label],
(None, [first, second]) => vec![first.as_str(), second.as_str()],
_ => return Err(EvaluationError::InvalidData),
};
let clauses = parse_command(&case.input).map_err(|_| EvaluationError::InvalidData)?;
if clauses.len() != labels.len() {
return Err(EvaluationError::InvalidData);
}
let actions = labels
.into_iter()
.zip(clauses)
.map(|(label, clause)| {
let kind = ActionKind::from_label(label).map_err(|_| EvaluationError::InvalidData)?;
Action::new(kind, clause.name).map_err(|_| EvaluationError::InvalidData)
})
.collect::<Result<Vec<_>, _>>()?;
Program::new(actions).map_err(|_| EvaluationError::InvalidData)
}
/// Validate one partition and require expected code to match its labels, order and literals.
fn validate_case(case: &EvaluationCase) -> Result<(), EvaluationError> {
if case.input.trim().is_empty() {
return Err(EvaluationError::InvalidData);
}
match (case.split.as_str(), case.expected.as_deref()) {
("supported", Some(expected)) if labeled_program(case)?.to_lisp() == expected => Ok(()),
("unsupported", None) if case.action.is_none() && case.actions.is_empty() => Ok(()),
_ => Err(EvaluationError::InvalidData),
}
}
/// Validate the complete dataset before scoring so malformed rows cannot yield a partial report.
fn validate_data(data: &EvaluationData) -> Result<(), EvaluationError> {
if data.format_version != 1 || data.policy.trim().is_empty() || data.corpora.is_empty() {
return Err(EvaluationError::InvalidData);
}
for (name, corpus) in &data.corpora {
if name.trim().is_empty() || !is_sha256(&corpus.sha256) || corpus.cases.is_empty() {
return Err(EvaluationError::InvalidData);
}
for case in &corpus.cases {
validate_case(case)?;
}
}
Ok(())
}
/// Decode and validate immutable benchmark bytes without loading a numerical model.
///
/// Single-action version-one datasets remain accepted. Two-action cases use
/// `action: null` with exactly two ordered, distinct labels in `actions`.
pub fn validate_data_bytes(bytes: &[u8]) -> Result<EvaluationData, EvaluationError> {
let data: EvaluationData = serde_json::from_slice(bytes)?;
validate_data(&data)?;
Ok(data)
}
/// Load and evaluate one unchanged artifact snapshot against an explicit frozen dataset.
pub fn evaluate(model_dir: &Path, data_path: &Path) -> Result<EvaluationReport, EvaluationError> {
let bytes = fs::read(data_path)?;
let data = validate_data_bytes(&bytes)?;
let snapshot = ArtifactSnapshot::read(model_dir)?;
let engine = ModelEngine::load(model_dir)?;
snapshot.verify_unchanged(model_dir)?;
let thresholds = engine.thresholds();
let mut results = BTreeMap::new();
for (name, corpus) in data.corpora {
let mut result = CorpusResult {
source_sha256: corpus.sha256,
..CorpusResult::default()
};
for case in corpus.cases {
evaluate_case(&engine, case, &mut result)?;
}
results.insert(name, result);
}
snapshot.verify_unchanged(model_dir)?;
Ok(EvaluationReport {
weights_sha256: snapshot.weights_sha256,
config_sha256: snapshot.config_sha256,
evaluation_data_sha256: format!("{:x}", Sha256::digest(bytes)),
thresholds,
policy: data.policy,
corpora: results,
})
}
/// Reduce one decision into overall, novelty, family and action summaries.
fn evaluate_case(
engine: &ModelEngine,
case: EvaluationCase,
result: &mut CorpusResult,
) -> Result<(), EvaluationError> {
let supported = match (case.split.as_str(), case.expected.is_some()) {
("supported", true) => true,
("unsupported", false) => false,
_ => return Err(EvaluationError::InvalidData),
};
let (actual, reason) = match engine.predict(&case.input, None, None) {
Ok(program) => (Some(program.to_lisp()), None),
Err(error) if error.is_refusal() => (None, Some(error.to_string())),
Err(error) => return Err(error.into()),
};
let observe = |counts: &mut Counts| counts.observe(actual.as_deref(), case.expected.as_deref());
if supported {
observe(&mut result.supported);
if case.novel_to_both {
observe(&mut result.novel_to_both_supported);
}
for label in case.action.iter().chain(case.actions.iter()) {
observe(result.per_action.entry(label.to_owned()).or_default());
}
} else {
observe(&mut result.unsupported);
if let Some(group) = &case.group {
observe(
result
.unsupported_groups
.entry(group.to_owned())
.or_default(),
);
}
}
if actual != case.expected {
result.failures.push(Failure {
input: case.input,
expected: case.expected,
actual,
reason,
});
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
/// Construct one schema-valid supported example without any model I/O.
fn dataset(action: Option<&str>, expected: Option<&str>, split: &str) -> EvaluationData {
let case = EvaluationCase {
input: "split right".into(),
expected: expected.map(str::to_owned),
split: split.into(),
action: action.map(str::to_owned),
actions: Vec::new(),
group: None,
novel_to_both: false,
};
EvaluationData {
format_version: 1,
policy: "frozen regression fixtures".into(),
corpora: [(
"regression".into(),
Corpus {
sha256: "a".repeat(64),
cases: vec![case],
},
)]
.into_iter()
.collect(),
}
}
#[test]
fn supported_cases_require_known_actions_and_consistent_partitions()
-> Result<(), EvaluationError> {
validate_data(&dataset(
Some("split-window-right"),
Some("(split-window-right)"),
"supported",
))?;
for data in [
dataset(None, Some("(split-window-right)"), "supported"),
dataset(
Some("arbitrary-eval"),
Some("(split-window-right)"),
"supported",
),
dataset(Some("split-window-right"), None, "supported"),
dataset(Some("split-window-right"), None, "unsupported"),
dataset(None, Some("(split-window-right)"), "unsupported"),
] {
assert!(matches!(
validate_data(&data),
Err(EvaluationError::InvalidData)
));
}
validate_data(&dataset(None, None, "unsupported"))?;
Ok(())
}
#[test]
fn composed_labels_must_match_order_literals_and_program_shape() -> Result<(), EvaluationError>
{
let base = serde_json::json!({
"input":"open file \"one.el\" then search forward for \"needle\"",
"expected":"(progn (find-file \"one.el\") (search-forward \"needle\"))",
"split":"supported", "action":null,
"actions":["find-file","search-forward"], "group":null, "novel_to_both":false
});
validate_case(&serde_json::from_value(base.to_owned())?)?;
for (field, value) in [
(
"actions",
serde_json::json!(["search-forward", "find-file"]),
),
("actions", serde_json::json!(["find-file", "find-file"])),
("actions", serde_json::json!(["find-file"])),
(
"actions",
serde_json::json!(["find-file", "arbitrary-eval"]),
),
("action", serde_json::json!("find-file")),
(
"expected",
serde_json::json!("(progn (find-file \"two.el\") (search-forward \"needle\"))"),
),
(
"expected",
serde_json::json!("(progn (search-forward \"needle\") (find-file \"one.el\"))"),
),
("input", serde_json::json!("open file \"one.el\"")),
(
"input",
serde_json::json!(
"open file \"one.el\" then search forward for \"needle\" then save"
),
),
] {
let mut invalid = base.to_owned();
invalid
.as_object_mut()
.ok_or(EvaluationError::InvalidData)?
.insert(field.to_owned(), value);
assert!(matches!(
validate_case(&serde_json::from_value(invalid)?),
Err(EvaluationError::InvalidData)
));
}
Ok(())
}
#[test]
fn original_single_action_schema_stays_compatible_and_extra_fields_fail()
-> Result<(), EvaluationError> {
let valid = r#"{"input":"save the current buffer","expected":"(save-buffer)","split":"supported","action":"save-buffer","group":null,"novel_to_both":false}"#;
let case: EvaluationCase = serde_json::from_str(valid)?;
assert!(case.actions.is_empty());
validate_case(&case)?;
let mut unknown: serde_json::Value = serde_json::from_str(valid)?;
unknown
.as_object_mut()
.ok_or(EvaluationError::InvalidData)?
.insert("extra".to_owned(), serde_json::json!(true));
assert!(serde_json::from_value::<EvaluationCase>(unknown).is_err());
Ok(())
}
#[test]
fn arbitrary_source_hashes_and_unknown_schema_fields_are_rejected()
-> Result<(), EvaluationError> {
let mut data = dataset(None, None, "unsupported");
let corpus = data
.corpora
.values_mut()
.next()
.ok_or(EvaluationError::InvalidData)?;
corpus.sha256 = "not-a-checkpoint-digest".into();
assert!(matches!(
validate_data(&data),
Err(EvaluationError::InvalidData)
));
assert!(
serde_json::from_str::<EvaluationData>(
r#"{"format_version":1,"policy":"frozen","corpora":{},"unknown":true}"#
)
.is_err()
);
Ok(())
}
#[test]
fn either_changed_model_file_invalidates_the_snapshot() -> Result<(), EvaluationError> {
let directory = tempfile::tempdir()?;
let weights = directory.path().join("model.safetensors");
let config = directory.path().join("config.json");
fs::write(&weights, b"original weights")?;
fs::write(&config, b"original config")?;
let snapshot = ArtifactSnapshot::read(directory.path())?;
snapshot.verify_unchanged(directory.path())?;
fs::write(&weights, b"changed weights")?;
assert!(matches!(
snapshot.verify_unchanged(directory.path()),
Err(EvaluationError::ArtifactChanged)
));
fs::write(&weights, b"original weights")?;
fs::write(&config, b"changed vocabulary or thresholds")?;
assert!(matches!(
snapshot.verify_unchanged(directory.path()),
Err(EvaluationError::ArtifactChanged)
));
Ok(())
}
#[test]
fn malformed_datasets_are_refused_before_loading_model_files() -> Result<(), EvaluationError> {
let directory = tempfile::tempdir()?;
let path = directory.path().join("evaluation.json");
fs::write(&path, br#"{"format_version":1,"policy":"frozen","corpora":{"bad":{"sha256":"bogus","cases":[]}}}"#)?;
let missing_model = directory.path().join("no-model-here");
assert!(matches!(
evaluate(&missing_model, &path),
Err(EvaluationError::InvalidData)
));
Ok(())
}
}