lispm-llm / src /training /data.rs
Ryan.K
Add reusable Emacs retraining workflow and C FFI API
2109241 unverified
Raw History Blame Contribute Delete
11.7 kB
//! Portable corpus validation and immutable incumbent provenance.
use std::collections::{BTreeMap, HashSet};
use std::fs;
use std::path::Path;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use sha2::{Digest, Sha256};
use super::{SamplingPools, TrainingError};
use crate::config::{Thresholds, expected_labels};
use crate::metrics::{MetricsError, ReferenceMetrics};
/// Frozen incumbent data; additional provenance fields are retained verbatim.
#[derive(Debug, Deserialize, Serialize)]
pub(super) struct SelectionReference {
/// Version of the immutable incumbent-reference schema.
pub(super) format_version: u32,
/// Historical incumbent checkpoint used to measure the reference counts.
checkpoint_sha256: String,
/// Original probability and margin ceilings retained during selection.
pub(super) thresholds: Thresholds,
/// Ordered digest of the exact original calibration prefix.
calibration_sha256: String,
/// Incumbent outcome partition and individual selection bounds.
pub(super) metrics: ReferenceMetrics,
/// Number of original rows at the start of the calibration corpus.
pub(super) calibration_size: usize,
/// Additional descriptive provenance preserved during serialization.
#[serde(flatten)]
pub(super) extra: BTreeMap<String, Value>,
}
/// Transport schema contains only training and calibration, never final tests.
#[derive(Debug, Deserialize)]
pub(super) struct TrainingData {
/// Version of the portable training input schema.
pub(super) format_version: u32,
/// Unique training phrases paired with their action or rejection labels.
pub(super) training_rows: Vec<(String, String)>,
/// Disjoint ordered validation phrases, with the original subset first.
pub(super) calibration_rows: Vec<(String, String)>,
/// Materialized validation requests for runtime syntax/argument admission.
pub(super) calibration_commands: Vec<String>,
/// Training-only indices oversampled for hard positive/reject distinctions.
pub(super) hard_training_indices: Vec<usize>,
/// Frozen original-subset constraints, independent of model candidates.
pub(super) reference: SelectionReference,
/// Exact source reference bytes retained to verify its historical digest.
pub(super) selection_reference_json: String,
/// Claimed digest of the ordered training rows.
pub(super) training_sha256: String,
/// Claimed digest of the ordered full calibration rows.
pub(super) calibration_sha256: String,
/// Claimed digest of the reference source bytes.
pub(super) selection_reference_sha256: String,
}
/// Validated labels and corpus bytes make later training transitions total.
pub(super) struct ValidatedData {
/// Validated portable corpus and frozen-reference contents.
pub(super) source: TrainingData,
/// Training targets in the authoritative classifier output order.
pub(super) training_labels: Vec<usize>,
/// Calibration targets in the same output order.
pub(super) calibration_labels: Vec<usize>,
/// Exact portable-data digest binding rows, commands and sampling indices.
pub(super) source_sha256: String,
/// Final classifier output index reserved for rejection.
pub(super) reject_index: usize,
}
/// Fingerprint bytes without changing their serialization or whitespace.
pub(super) fn sha256(bytes: &[u8]) -> String {
format!("{:x}", Sha256::digest(bytes))
}
/// Match `json.dumps(rows, ensure_ascii=False)` including its default spaces.
pub fn rows_sha256(rows: &[(String, String)]) -> Result<String, TrainingError> {
let mut bytes = String::from("[");
for (index, (phrase, label)) in rows.iter().enumerate() {
if index != 0 {
bytes.push_str(", ");
}
bytes.push('[');
bytes.push_str(&serde_json::to_string(phrase)?);
bytes.push_str(", ");
bytes.push_str(&serde_json::to_string(label)?);
bytes.push(']');
}
bytes.push(']');
Ok(sha256(bytes.as_bytes()))
}
/// Recognize a canonical SHA-256 representation before comparing provenance.
fn canonical_hash(value: &str) -> bool {
value.len() == 64
&& value
.bytes()
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
}
/// Resolve all labels against the single ordered classifier vocabulary.
fn label_indices(
rows: &[(String, String)],
labels: &[String],
) -> Result<Vec<usize>, TrainingError> {
rows.iter()
.map(|(_, label)| {
labels
.iter()
.position(|known| known == label)
.ok_or_else(|| TrainingError::UnknownLabel(label.to_owned()))
})
.collect()
}
/// Ensure corpus rows are distinct and no phrase crosses the split boundary.
fn validate_splits(data: &TrainingData) -> Result<(), TrainingError> {
let mut training = HashSet::new();
let mut calibration = HashSet::new();
if data
.training_rows
.iter()
.any(|(phrase, _)| phrase.is_empty() || !training.insert(phrase))
|| data
.calibration_rows
.iter()
.any(|(phrase, _)| phrase.is_empty() || !calibration.insert(phrase))
|| !training.is_disjoint(&calibration)
{
return Err(TrainingError::InvalidData(
"training/calibration phrases must be nonempty, unique and disjoint",
));
}
Ok(())
}
/// Verify every declared digest against its bytes and every incumbent count.
fn validate_reference(
data: &TrainingData,
calibration_labels: &[usize],
reject: usize,
) -> Result<(), TrainingError> {
let reference = &data.reference;
let prefix = data
.calibration_rows
.get(..reference.calibration_size)
.ok_or(TrainingError::InvalidData(
"reference must be a calibration prefix",
))?;
if reference.format_version != 1
|| reference.calibration_size == 0
|| reference.thresholds.probability != 0.8
|| reference.thresholds.margin != 0.1
|| !canonical_hash(&reference.checkpoint_sha256)
|| reference.calibration_sha256 != rows_sha256(prefix)?
{
return Err(TrainingError::InvalidData(
"frozen selection reference is inconsistent",
));
}
let source_reference: Value = serde_json::from_str(&data.selection_reference_json)?;
if source_reference != serde_json::to_value(reference)?
|| data.selection_reference_sha256 != sha256(data.selection_reference_json.as_bytes())
{
return Err(TrainingError::InvalidData(
"selection reference source bytes or hash do not match",
));
}
reference.metrics.validate(
calibration_labels
.get(..reference.calibration_size)
.ok_or(MetricsError::Reference)?,
reject,
)?;
Ok(())
}
impl ValidatedData {
/// Read once and validate the complete immutable portable-data contract.
pub(super) fn load(path: &Path) -> Result<Self, TrainingError> {
let bytes = fs::read(path)?;
Self::from_bytes(&bytes)
}
/// Validate already-owned bytes without rereading or modifying a document.
fn from_bytes(bytes: &[u8]) -> Result<Self, TrainingError> {
let source: TrainingData = serde_json::from_slice(bytes)?;
if source.format_version != 1
|| source.training_rows.is_empty()
|| source.calibration_rows.is_empty()
|| source.calibration_commands.len() != source.calibration_rows.len()
{
return Err(TrainingError::InvalidData(
"invalid data format or missing aligned rows",
));
}
validate_splits(&source)?;
if source.training_sha256 != rows_sha256(&source.training_rows)?
|| source.calibration_sha256 != rows_sha256(&source.calibration_rows)?
{
return Err(TrainingError::InvalidData(
"ordered training/calibration hashes do not match",
));
}
let labels = expected_labels();
let reject_index = labels
.len()
.checked_sub(1)
.ok_or(TrainingError::InvalidData("no labels"))?;
let training_labels = label_indices(&source.training_rows, &labels)?;
let calibration_labels = label_indices(&source.calibration_rows, &labels)?;
validate_reference(&source, &calibration_labels, reject_index)?;
Ok(Self {
source,
training_labels,
calibration_labels,
source_sha256: sha256(bytes),
reject_index,
})
}
/// Refuse publication if any source byte changed during optimization.
pub(super) fn ensure_unchanged(&self, path: &Path) -> Result<(), TrainingError> {
if sha256(&fs::read(path)?) != self.source_sha256 {
return Err(TrainingError::DataChanged);
}
Ok(())
}
}
/// Auditable counts and digests of a fully validated portable training document.
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct TrainingDataSummary {
/// Number of distinct training examples, covering every output label.
pub train_unique: usize,
/// Number of distinct calibration examples, disjoint from training.
pub calibration_unique: usize,
/// Frozen original calibration prefix length.
pub original_calibration_unique: usize,
/// Additional calibration suffix length.
pub added_calibration_unique: usize,
/// Ordered training text/label digest.
pub training_sha256: String,
/// Ordered calibration text/label digest.
pub calibration_sha256: String,
/// Digest of the exact original reference JSON bytes.
pub selection_reference_sha256: String,
/// Digest of every input byte, including whitespace and sampling indices.
pub source_sha256: String,
/// Supported examples eligible for additional hard-example sampling.
pub hard_supported_rows: usize,
/// Rejected examples eligible for additional hard-example sampling.
pub hard_reject_rows: usize,
}
/// Validate a dataset file without constructing a model or changing the runtime.
pub fn validate_training_data(path: &Path) -> Result<TrainingDataSummary, TrainingError> {
validate_training_data_bytes(&fs::read(path)?)
}
/// Validate candidate document bytes before an immutable dataset write.
///
/// Checks include schema alignment, unique disjoint splits, all labels, ordered
/// row digests, frozen reference bytes/counts and complete hard-sampling pools.
/// No path is written and no LibTorch seed or thread configuration is changed.
pub fn validate_training_data_bytes(bytes: &[u8]) -> Result<TrainingDataSummary, TrainingError> {
let data = ValidatedData::from_bytes(bytes)?;
let pools = SamplingPools::build(&data)?;
let original = data.source.reference.calibration_size;
let calibration = data.source.calibration_rows.len();
Ok(TrainingDataSummary {
train_unique: data.source.training_rows.len(),
calibration_unique: calibration,
original_calibration_unique: original,
added_calibration_unique: calibration
.checked_sub(original)
.ok_or(TrainingError::InvalidData("reference length"))?,
training_sha256: data.source.training_sha256,
calibration_sha256: data.source.calibration_sha256,
selection_reference_sha256: data.source.selection_reference_sha256,
source_sha256: data.source_sha256,
hard_supported_rows: pools.hard_supported.len(),
hard_reject_rows: pools.hard_rejected.len(),
})
}