//! Validated architecture, vocabulary and artifact metadata. use std::collections::{BTreeMap, HashMap, HashSet}; use std::path::Path; use serde::{Deserialize, Serialize}; use serde_json::Value; use thiserror::Error; use crate::actions::ACTION_LABELS; /// Dimensions of the Python-compatible word/character Transformer. #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct ModelConfig { /// Hidden and embedding width. pub width: i64, /// Number of independently initialized encoder layers. pub layers: usize, /// Number of attention heads; divides width. pub heads: i64, /// Inner feed-forward width. pub feedforward: i64, /// Character hash buckets, including zero padding. pub char_buckets: i64, /// Maximum stored character fragments per token. pub max_ngrams: i64, /// Position embedding capacity, including CLS. pub max_words: i64, /// Embedding, attention and feed-forward dropout probability. pub dropout: f64, } impl Default for ModelConfig { fn default() -> Self { Self { width: 64, layers: 2, heads: 4, feedforward: 128, char_buckets: 1024, max_ngrams: 32, max_words: 60, dropout: 0.1, } } } /// Confidence gates applied by the separate typed inference boundary. #[derive(Clone, Copy, Debug, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct Thresholds { /// Minimum top-class probability. pub probability: f64, /// Minimum lead over the runner-up probability. pub margin: f64, } /// Portable artifact configuration; metadata snapshots preserve unknown fields. #[derive(Clone, Debug, Serialize, Deserialize)] pub struct ArtifactConfig { /// Tensor architecture. pub architecture: ModelConfig, /// Exact ordered action labels followed by rejection. pub labels: Vec, /// Contiguous word identifiers with fixed reserved-token identifiers. pub vocab: HashMap, /// Runtime confidence gates. pub thresholds: Thresholds, /// Source/training provenance and future nonarchitectural metadata. #[serde(flatten)] pub extra: BTreeMap, } /// Failures of the configuration contract, before tensor allocation. #[derive(Debug, Error)] pub enum ConfigError { /// A dimension is nonpositive or its product cannot be represented. #[error("invalid architecture dimension: {0}")] Dimension(&'static str), /// Attention width does not divide evenly into heads. #[error("architecture.width must be divisible by architecture.heads")] HeadWidth, /// A probability is nonfinite or outside the unit interval. #[error("{0} must be finite and in [0, 1]")] Probability(&'static str), /// Output labels differ in identity or order. #[error("artifact labels do not match the ordered action set")] Labels, /// Word identifiers or reserved tokens violate the encoding contract. #[error("vocabulary must contain unique contiguous identifiers and reserved tokens 0, 1, 2")] Vocabulary, /// Required portable provenance is absent or malformed. #[error("invalid artifact metadata: {0}")] Metadata(&'static str), /// A file could not be read or written. #[error(transparent)] Io(#[from] std::io::Error), /// JSON parsing or serialization failed. #[error(transparent)] Json(#[from] serde_json::Error), } /// Return the sole authoritative action order plus the rejection label. pub fn expected_labels() -> Vec { ACTION_LABELS .iter() .copied() .chain(std::iter::once("reject")) .map(str::to_owned) .collect() } /// Name the finite-probability predicate shared by architecture and admission. fn unit_interval(value: f64) -> bool { value.is_finite() && (0.0..=1.0).contains(&value) } impl ModelConfig { /// Validate all dimensions used in indexing, arithmetic and tensor shapes. pub fn validate(&self) -> Result<(), ConfigError> { for (name, dimension) in [ ("width", self.width), ("heads", self.heads), ("feedforward", self.feedforward), ("char_buckets", self.char_buckets), ("max_ngrams", self.max_ngrams), ("max_words", self.max_words), ] { if dimension <= 0 { return Err(ConfigError::Dimension(name)); } usize::try_from(dimension).map_err(|_| ConfigError::Dimension(name))?; } if self.layers == 0 { return Err(ConfigError::Dimension("layers")); } i64::try_from(self.layers).map_err(|_| ConfigError::Dimension("layers"))?; if self.width % self.heads != 0 { return Err(ConfigError::HeadWidth); } if self.char_buckets < 2 { return Err(ConfigError::Dimension("char_buckets")); } if self.max_words < 59 { return Err(ConfigError::Dimension("max_words")); } for dimension in [ self.width, self.feedforward, self.char_buckets, self.max_words, ] { self.width .checked_mul(dimension) .and_then(|size| size.checked_mul(4)) .ok_or(ConfigError::Dimension("tensor element count"))?; } self.width .checked_mul(3) .ok_or(ConfigError::Dimension("attention projection"))?; if !unit_interval(self.dropout) { return Err(ConfigError::Probability("dropout")); } Ok(()) } } impl ArtifactConfig { /// Validate computation fields; fresh training may initially have no provenance. pub fn validate(&self) -> Result<(), ConfigError> { self.architecture.validate()?; if self.labels != expected_labels() { return Err(ConfigError::Labels); } if !unit_interval(self.thresholds.probability) { return Err(ConfigError::Probability("thresholds.probability")); } if !unit_interval(self.thresholds.margin) { return Err(ConfigError::Probability("thresholds.margin")); } let size = i64::try_from(self.vocab.len()).map_err(|_| ConfigError::Vocabulary)?; let identifiers: HashSet = self.vocab.values().copied().collect(); let valid_identifiers = identifiers.len() == self.vocab.len() && identifiers.iter().all(|id| (0..size).contains(id)); let reserved = [("", 0), ("", 1), ("", 2)] .iter() .all(|(word, id)| self.vocab.get(*word) == Some(id)); if !valid_identifiers || !reserved || self.vocab.keys().any(String::is_empty) { return Err(ConfigError::Vocabulary); } Ok(()) } /// Validate computation and the required serialized artifact provenance. pub fn validate_artifact(&self) -> Result<(), ConfigError> { self.validate()?; if self .extra .get("artifact_format_version") .and_then(Value::as_u64) != Some(1) { return Err(ConfigError::Metadata("artifact_format_version must be 1")); } let source = self .extra .get("source_checkpoint_sha256") .and_then(Value::as_str) .ok_or(ConfigError::Metadata("source_checkpoint_sha256 is missing"))?; if source.len() != 64 || !source .bytes() .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) { return Err(ConfigError::Metadata( "source_checkpoint_sha256 must be lowercase SHA-256", )); } if !self.extra.get("training").is_some_and(Value::is_object) { return Err(ConfigError::Metadata("training must be an object")); } Ok(()) } /// Read a portable configuration and reject duplicate JSON keys recursively. pub fn load(path: impl AsRef) -> Result { let bytes = std::fs::read(path)?; let unique: UniqueValue = serde_json::from_slice(&bytes)?; let config: Self = serde_json::from_value(unique.0)?; config.validate_artifact()?; Ok(config) } /// Serialize a validated portable configuration without losing provenance. pub fn save(&self, path: impl AsRef) -> Result<(), ConfigError> { self.validate_artifact()?; let mut bytes = serde_json::to_vec_pretty(self)?; bytes.push(b'\n'); std::fs::write(path, bytes)?; Ok(()) } } /// Recursive JSON value that rejects duplicate keys before serde flattens metadata. struct UniqueValue(Value); impl<'de> Deserialize<'de> for UniqueValue { fn deserialize>(deserializer: D) -> Result { /// Preserve JSON primitives while checking every nested object map. struct Visitor; impl<'de> serde::de::Visitor<'de> for Visitor { type Value = UniqueValue; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("JSON with unique object keys") } fn visit_bool(self, value: bool) -> Result { Ok(UniqueValue(value.into())) } fn visit_i64(self, value: i64) -> Result { Ok(UniqueValue(value.into())) } fn visit_u64(self, value: u64) -> Result { Ok(UniqueValue(value.into())) } fn visit_f64(self, value: f64) -> Result { serde_json::Number::from_f64(value) .map(|number| UniqueValue(Value::Number(number))) .ok_or_else(|| E::custom("nonfinite JSON number")) } fn visit_str(self, value: &str) -> Result { Ok(UniqueValue(value.into())) } fn visit_unit(self) -> Result { Ok(UniqueValue(Value::Null)) } fn visit_seq>( self, mut sequence: A, ) -> Result { let mut values = Vec::new(); while let Some(value) = sequence.next_element::()? { values.push(value.0); } Ok(UniqueValue(Value::Array(values))) } fn visit_map>( self, mut map: A, ) -> Result { let mut values = serde_json::Map::new(); while let Some((key, value)) = map.next_entry::()? { if values.insert(key, value.0).is_some() { return Err(serde::de::Error::custom("duplicate JSON field")); } } Ok(UniqueValue(Value::Object(values))) } } deserializer.deserialize_any(Visitor) } } #[cfg(test)] mod tests { use super::*; #[test] fn duplicate_nested_json_fields_are_rejected() { assert!( serde_json::from_str::(r#"{"training":{"seed":1,"seed":2}}"#).is_err() ); } #[test] fn architecture_rejects_zero_heads_and_incompatible_width() { let mut config = ModelConfig { heads: 0, ..ModelConfig::default() }; assert!(config.validate().is_err()); config.heads = 3; assert!(matches!(config.validate(), Err(ConfigError::HeadWidth))); } #[test] fn labels_and_reserved_vocabulary_ids_are_part_of_the_artifact_contract() -> Result<(), ConfigError> { let mut config = ArtifactConfig { architecture: ModelConfig::default(), labels: expected_labels(), vocab: [ ("".into(), 0), ("".into(), 1), ("".into(), 2), ] .into_iter() .collect(), thresholds: Thresholds { probability: 0.8, margin: 0.1, }, extra: BTreeMap::new(), }; config.validate()?; *config.labels.first_mut().ok_or(ConfigError::Labels)? = "arbitrary-eval".into(); assert!(matches!(config.validate(), Err(ConfigError::Labels))); config.labels = expected_labels(); config.vocab.insert("extra".into(), 2); assert!(matches!(config.validate(), Err(ConfigError::Vocabulary))); Ok(()) } }