File size: 11,675 Bytes
2109241 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 | //! 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(),
})
}
|