//! Trainable CPU Transformer with the original PyTorch parameter namespace. use std::collections::BTreeMap; use std::path::Path; use serde_json::Value; use sha2::{Digest, Sha256}; use tch::{Device, Kind, Tensor, nn}; use thiserror::Error; use crate::config::{ArtifactConfig, ConfigError, ModelConfig, expected_labels}; use crate::tokenizer::TokenizerError; /// Recoverable model construction, tensor execution and artifact failures. #[derive(Debug, Error)] pub enum ModelError { /// Configuration invariants failed. #[error(transparent)] Config(#[from] ConfigError), /// Input encoding failed. #[error(transparent)] Tokenizer(#[from] TokenizerError), /// A LibTorch operation failed. #[error(transparent)] Tensor(#[from] tch::TchError), /// Filesystem access failed. #[error(transparent)] Io(#[from] std::io::Error), /// Tensor shape arithmetic cannot be represented. #[error("model dimensions exceed supported integer ranges")] Dimensions, /// Artifact tensor names differ from the architecture. #[error("incompatible parameters: missing={missing:?}, unexpected={unexpected:?}")] ParameterNames { /// Required names missing from the artifact. missing: Vec, /// Artifact names absent from the architecture. unexpected: Vec, }, /// A parameter has a different shape. #[error("incompatible shape for {name}: expected {expected:?}, received {actual:?}")] ParameterShape { /// Parameter identity. name: String, /// Architecture shape. expected: Vec, /// Loaded tensor shape. actual: Vec, }, /// A parameter is not a CPU float32 tensor. #[error("parameter {0} must be a CPU float32 tensor")] ParameterType(String), /// Nonfinite parameters are never accepted or serialized. #[error("parameter {0} contains nonfinite values")] NonFinite(String), /// Duplicate parameter names are not allowed. #[error("duplicate parameter name: {0}")] DuplicateParameter(String), /// Native-source provenance must identify the actual SafeTensors file. #[error("SafeTensors source hash does not match the weight file")] SourceHashMismatch, /// The batch shape or leading CLS token is invalid. #[error("invalid model input: {0}")] InputShape(&'static str), /// Word or character identifiers exceed embedding ranges. #[error("input identifiers are outside the {0} embedding range")] InputIdentifiers(&'static str), } /// A registered affine map; tensor handles share storage with the VarStore. pub(crate) struct Linear { /// Row-major [output, input] trainable matrix. pub(crate) weight: Tensor, /// One trainable offset per output coordinate. pub(crate) bias: Tensor, } impl Linear { /// Match PyTorch Linear's uniform initialization from its fan-in width. pub(crate) fn new( path: &nn::Path<'_>, input: i64, output: i64, zero_bias: bool, ) -> Result { let input_float = f64::from(u32::try_from(input).map_err(|_| ModelError::Dimensions)?); let bound = input_float.sqrt().recip(); let initialization = nn::Init::Uniform { lo: -bound, up: bound, }; Ok(Self { weight: path.f_var("weight", &[output, input], initialization)?, bias: path.f_var( "bias", &[output], if zero_bias { nn::Init::Const(0.0) } else { initialization }, )?, }) } /// Apply the affine map to the last axis without changing preceding axes. pub(crate) fn forward(&self, input: &Tensor) -> Result { Ok(input.f_linear(&self.weight, Some(&self.bias))?) } } /// Affine last-axis normalization with PyTorch's default epsilon of 1e-5. pub(crate) struct LayerNorm { /// Trainable coordinate scale, initialized to one. weight: Tensor, /// Trainable coordinate shift, initialized to zero. bias: Tensor, /// Last-axis length over which mean and population variance are computed. width: i64, } impl LayerNorm { /// Register the identity affine transform under the owning layer path. pub(crate) fn new(path: &nn::Path<'_>, width: i64) -> Result { Ok(Self { weight: path.f_ones("weight", &[width])?, bias: path.f_zeros("bias", &[width])?, width, }) } /// Normalize each token independently; padding is handled by attention. pub(crate) fn forward(&self, input: &Tensor) -> Result { Ok(input.f_layer_norm( [self.width], Some(&self.weight), Some(&self.bias), 1e-5, true, )?) } } /// One post-norm TransformerEncoderLayer with packed Q/K/V projections. pub(crate) struct EncoderLayer { /// Three concatenated [width, width] projection matrices in Q/K/V order. projection_weight: Tensor, /// Three concatenated coordinate biases in Q/K/V order. projection_bias: Tensor, /// Projection from concatenated attention heads to hidden width. attention_output: Linear, /// Expansion from hidden width to feed-forward width. feedforward_input: Linear, /// Projection from activated feed-forward coordinates to hidden width. feedforward_output: Linear, /// Normalization after the attention residual addition. norm1: LayerNorm, /// Normalization after the feed-forward residual addition. norm2: LayerNorm, /// Validated hidden width, divisible by the number of heads. width: i64, /// Number of disjoint coordinate groups used by attention. heads: i64, /// Shared probability for attention and residual/feed-forward dropout. dropout: f64, } impl EncoderLayer { /// Preserve the original parameter names and MultiheadAttention reset order. pub(crate) fn new(path: &nn::Path<'_>, config: &ModelConfig) -> Result { let width_float = f64::from(u32::try_from(config.width).map_err(|_| ModelError::Dimensions)?); let bound = (1.5 / width_float).sqrt(); let projection_size = config.width.checked_mul(3).ok_or(ModelError::Dimensions)?; let attention = path / "self_attn"; let mut projection_weight = attention.f_zeros("in_proj_weight", &[projection_size, config.width])?; let projection_bias = attention.f_zeros("in_proj_bias", &[projection_size])?; // PyTorch initializes out_proj as Linear before resetting packed QKV. let mut attention_output = Linear::new( &(&attention / "out_proj"), config.width, config.width, false, )?; tch::no_grad(|| -> Result<(), tch::TchError> { let _ = projection_weight.f_uniform_(-bound, bound)?; let _ = attention_output.bias.f_zero_()?; Ok(()) })?; Ok(Self { projection_weight, projection_bias, attention_output, feedforward_input: Linear::new( &(path / "linear1"), config.width, config.feedforward, false, )?, feedforward_output: Linear::new( &(path / "linear2"), config.feedforward, config.width, false, )?, norm1: LayerNorm::new(&(path / "norm1"), config.width)?, norm2: LayerNorm::new(&(path / "norm2"), config.width)?, width: config.width, heads: config.heads, dropout: config.dropout, }) } /// Follow PyTorch's sequence-first packed projection and output layouts. /// /// Matching layout also preserves the order of floating-point gradient /// reductions, which matters for theoretically zero key-bias gradients. fn attention( &self, hidden: &Tensor, mask: &Tensor, batch: i64, length: i64, train: bool, ) -> Result { let projected = hidden .f_transpose(0, 1)? .f_linear(&self.projection_weight, Some(&self.projection_bias))? .f_reshape([length, batch, 3, self.width])? .f_permute([2, 0, 1, 3])? .f_contiguous()?; let head_width = self.width / self.heads; let batch_heads = batch .checked_mul(self.heads) .ok_or(ModelError::Dimensions)?; let project = |component: i64| -> Result { Ok(projected .f_select(0, component)? .f_reshape([length, batch_heads, head_width])? .f_transpose(0, 1)? .f_reshape([batch, self.heads, length, head_width])?) }; let query = project(0)?; let key = project(1)?; let value = project(2)?; let attention_mask = mask .f_to_kind(Kind::Float)? .f_masked_fill(mask, f64::NEG_INFINITY)? .f_reshape([batch, 1, 1, length])? .f_expand([batch, self.heads, 1, length], false)? .f_reshape([batch_heads, 1, length])? .f_reshape([batch, self.heads, 1, length])?; let output = Tensor::f_scaled_dot_product_attention( &query, &key, &value, Some(&attention_mask), if train { self.dropout } else { 0.0 }, false, None, false, )?; let joined = output.f_permute([2, 0, 1, 3])?.f_contiguous()?.f_reshape([ length.checked_mul(batch).ok_or(ModelError::Dimensions)?, self.width, ])?; Ok(self .attention_output .forward(&joined)? .f_reshape([length, batch, self.width])? .f_transpose(0, 1)?) } /// Apply attention/residual/norm followed by ReLU feed-forward/residual/norm. pub(crate) fn forward( &self, hidden: &Tensor, mask: &Tensor, batch: i64, length: i64, train: bool, ) -> Result { let attention = self .attention(hidden, mask, batch, length, train)? .f_dropout(self.dropout, train)?; let normalized = self.norm1.forward(&hidden.f_add(&attention)?)?; let intermediate = self .feedforward_input .forward(&normalized)? .f_relu()? .f_dropout(self.dropout, train)?; let output = self .feedforward_output .forward(&intermediate)? .f_dropout(self.dropout, train)?; self.norm2.forward(&normalized.f_add(&output)?) } } /// Initialize a normal embedding table and zero its optional padding row. pub(crate) fn embedding( path: &nn::Path<'_>, rows: i64, width: i64, padding: bool, ) -> Result { let weight = path.f_var( "weight", &[rows, width], nn::Init::Randn { mean: 0.0, stdev: 1.0, }, )?; if padding { tch::no_grad(|| -> Result<(), tch::TchError> { let _ = weight.f_get(0)?.f_zero_()?; Ok(()) })?; } Ok(weight) } /// The exact post-norm word/subword Transformer, with trainable named tensors. pub struct IntentClassifier { /// Architecture used for encoding and forward execution. pub config: ModelConfig, /// Whole-word table, with row zero excluded from embedding gradients. words: Tensor, /// Hashed character-fragment table, also with a zero padding row. characters: Tensor, /// Trainable absolute positions, including position zero for CLS. positions: Tensor, /// Normalize the sum of the three embedding components. norm: LayerNorm, /// Independently parameterized post-norm encoder layers, in execution order. layers: Vec, /// Affine map from the final CLS state to the fixed ordered labels. output: Linear, /// Upper exclusive bound for whole-word input identifiers. vocabulary_size: i64, } impl IntentClassifier { /// Register newly initialized parameters under the original Python names. pub fn new( path: &nn::Path<'_>, config: &ModelConfig, vocabulary_size: i64, ) -> Result { config.validate()?; if vocabulary_size < 3 { return Err(ConfigError::Vocabulary.into()); } vocabulary_size .checked_mul(config.width) .ok_or(ModelError::Dimensions)?; let mut layers = Vec::with_capacity(config.layers); let words = embedding(&(path / "words"), vocabulary_size, config.width, true)?; let characters = embedding( &(path / "characters"), config.char_buckets, config.width, true, )?; let positions = embedding(&(path / "positions"), config.max_words, config.width, false)?; let norm = LayerNorm::new(&(path / "norm"), config.width)?; for index in 0..config.layers { layers.push(EncoderLayer::new( &(&(path / "layers") / index.to_string()), config, )?); } let labels = i64::try_from(expected_labels().len()).map_err(|_| ModelError::Dimensions)?; Ok(Self { config: config.clone(), words, characters, positions, norm, layers, output: Linear::new(&(path / "output"), config.width, labels, false)?, vocabulary_size, }) } /// Validate tensor ranks, devices, identifiers and an unmasked leading CLS. fn validate_inputs( &self, words: &Tensor, characters: &Tensor, ) -> Result<(i64, i64), ModelError> { let sizes = words.size(); let (batch, length) = match sizes.as_slice() { [batch, length] if *batch > 0 && *length > 1 && *length <= self.config.max_words => { (*batch, *length) } _ => { return Err(ModelError::InputShape( "words must be a nonempty [batch, sequence] tensor", )); } }; if characters.size() != [batch, length, self.config.max_ngrams] { return Err(ModelError::InputShape( "character shape must be [batch, sequence, max_ngrams]", )); } if words.kind() != Kind::Int64 || characters.kind() != Kind::Int64 || words.device() != self.words.device() || characters.device() != self.words.device() { return Err(ModelError::InputShape( "identifiers must be int64 tensors on the model device", )); } for (name, tensor, maximum) in [ ("word", words, self.vocabulary_size), ("character", characters, self.config.char_buckets), ] { if tensor.f_min()?.f_int64_value(&[])? < 0 || tensor.f_max()?.f_int64_value(&[])? >= maximum { return Err(ModelError::InputIdentifiers(name)); } } if words.f_select(1, 0)?.f_eq(2)?.f_all()?.f_int64_value(&[])? != 1 { return Err(ModelError::InputShape( "every row must begin with CLS identifier 2", )); } Ok((batch, length)) } /// Produce 49 logits; `train` enables all original dropout sites and gradients remain available. pub fn forward( &self, word_ids: &Tensor, char_ids: &Tensor, train: bool, ) -> Result { let (batch, length) = self.validate_inputs(word_ids, char_ids)?; let mask = word_ids.f_eq(0)?; let count = char_ids .f_ne(0)? .f_sum_dim_intlist([-1_i64].as_slice(), true, Kind::Int64)? .f_clamp_min(1)?; let character_features = Tensor::f_embedding(&self.characters, char_ids, 0, false, false)? .f_sum_dim_intlist([-2_i64].as_slice(), false, Kind::Float)? .f_div(&count.f_sqrt()?)?; let position_ids = Tensor::f_arange(length, (Kind::Int64, word_ids.device()))?; let positions = Tensor::f_embedding(&self.positions, &position_ids, -1, false, false)?; let words = Tensor::f_embedding(&self.words, word_ids, 0, false, false)?; let mut hidden = self .norm .forward(&words.f_add(&character_features)?.f_add(&positions)?)? .f_dropout(self.config.dropout, train)?; for layer in &self.layers { hidden = layer.forward(&hidden, &mask, batch, length, train)?; } self.output.forward(&hidden.f_select(1, 0)?) } } /// Derive the complete parameter namespace before allocating a loaded model. fn parameter_shapes(config: &ArtifactConfig) -> Result>, ModelError> { let architecture = &config.architecture; let width = architecture.width; let projected = width.checked_mul(3).ok_or(ModelError::Dimensions)?; let vocabulary = i64::try_from(config.vocab.len()).map_err(|_| ModelError::Dimensions)?; let labels = i64::try_from(config.labels.len()).map_err(|_| ModelError::Dimensions)?; let mut shapes: BTreeMap> = [ ("words.weight", vec![vocabulary, width]), ("characters.weight", vec![architecture.char_buckets, width]), ("positions.weight", vec![architecture.max_words, width]), ("norm.weight", vec![width]), ("norm.bias", vec![width]), ("output.weight", vec![labels, width]), ("output.bias", vec![labels]), ] .into_iter() .map(|(name, shape)| (name.to_owned(), shape)) .collect(); for index in 0..architecture.layers { for (name, shape) in [ ("self_attn.in_proj_weight", vec![projected, width]), ("self_attn.in_proj_bias", vec![projected]), ("self_attn.out_proj.weight", vec![width, width]), ("self_attn.out_proj.bias", vec![width]), ("linear1.weight", vec![architecture.feedforward, width]), ("linear1.bias", vec![architecture.feedforward]), ("linear2.weight", vec![width, architecture.feedforward]), ("linear2.bias", vec![width]), ("norm1.weight", vec![width]), ("norm1.bias", vec![width]), ("norm2.weight", vec![width]), ("norm2.bias", vec![width]), ] { shapes.insert(format!("layers.{index}.{name}"), shape); } } Ok(shapes) } /// Admit exactly the architecture's finite, dense CPU float32 parameter set. fn validate_weights( weights: &BTreeMap, config: &ArtifactConfig, ) -> Result<(), ModelError> { let expected = parameter_shapes(config)?; let missing: Vec = expected .keys() .filter(|name| !weights.contains_key(*name)) .cloned() .collect(); let unexpected: Vec = weights .keys() .filter(|name| !expected.contains_key(*name)) .cloned() .collect(); if !missing.is_empty() || !unexpected.is_empty() { return Err(ModelError::ParameterNames { missing, unexpected, }); } for (name, tensor) in weights { let shape = expected.get(name).ok_or(ModelError::Dimensions)?; if &tensor.size() != shape { return Err(ModelError::ParameterShape { name: name.to_owned(), expected: shape.to_owned(), actual: tensor.size(), }); } if tensor.kind() != Kind::Float || tensor.device() != Device::Cpu { return Err(ModelError::ParameterType(name.to_owned())); } if tensor.f_isfinite()?.f_all()?.f_int64_value(&[])? != 1 { return Err(ModelError::NonFinite(name.to_owned())); } } Ok(()) } /// Hash canonical ordered parameter values independently of SafeTensors headers. fn weight_fingerprint(weights: &BTreeMap) -> Result { let mut digest = Sha256::new(); for (name, tensor) in weights { digest.update( u64::try_from(name.len()) .map_err(|_| ModelError::Dimensions)? .to_le_bytes(), ); digest.update(name.as_bytes()); for dimension in tensor.size() { digest.update(dimension.to_le_bytes()); } let mut values = vec![0_f32; tensor.numel()]; tensor.f_copy_data(&mut values, tensor.numel())?; for value in values { digest.update(value.to_le_bytes()); } } Ok(format!("{:x}", digest.finalize())) } /// Registered trainable parameters, their encoder and validated artifact metadata. pub struct ModelBundle { /// Named parameter store used by optimizers and checkpoint snapshots. pub vs: nn::VarStore, /// Trainable classifier sharing the store's registered tensors. pub model: IntentClassifier, /// Complete metadata; training can update provenance before saving. pub metadata: ArtifactConfig, /// Original numerical state, used only to preserve unchanged import provenance. imported_fingerprint: Option, } impl ModelBundle { /// Initialize a fresh CPU model; seed mutation is explicit at this boundary. pub fn new(metadata: ArtifactConfig, seed: i64) -> Result { metadata.validate()?; tch::manual_seed(seed); let vs = nn::VarStore::new(Device::Cpu); let vocabulary = i64::try_from(metadata.vocab.len()).map_err(|_| ModelError::Dimensions)?; let model = IntentClassifier::new(&vs.root(), &metadata.architecture, vocabulary)?; Ok(Self { vs, model, metadata, imported_fingerprint: None, }) } /// Load only `config.json` and exact named finite float32 SafeTensors weights. pub fn load(directory: impl AsRef) -> Result { let directory = directory.as_ref(); let metadata = ArtifactConfig::load(directory.join("config.json"))?; let weight_path = directory.join("model.safetensors"); if metadata .extra .get("source_checkpoint_format") .and_then(Value::as_str) == Some("safetensors") { let actual = format!("{:x}", Sha256::digest(std::fs::read(&weight_path)?)); if metadata .extra .get("source_checkpoint_sha256") .and_then(Value::as_str) != Some(actual.as_str()) { return Err(ModelError::SourceHashMismatch); } } let mut weights = BTreeMap::new(); for (name, tensor) in Tensor::read_safetensors(weight_path)? { if weights.insert(name.to_owned(), tensor).is_some() { return Err(ModelError::DuplicateParameter(name)); } } validate_weights(&weights, &metadata)?; let imported_fingerprint = Some(weight_fingerprint(&weights)?); let vs = nn::VarStore::new(Device::Cpu); let vocabulary = i64::try_from(metadata.vocab.len()).map_err(|_| ModelError::Dimensions)?; let model = IntentClassifier::new(&vs.root(), &metadata.architecture, vocabulary)?; let mut parameters = vs.variables(); tch::no_grad(|| -> Result<(), ModelError> { for (name, weight) in &weights { parameters .get_mut(name) .ok_or(ModelError::Dimensions)? .f_copy_(weight)?; } Ok(()) })?; Ok(Self { vs, model, metadata, imported_fingerprint, }) } /// Save named weights and JSON, retaining unrelated files in the directory. /// /// Unchanged imports preserve historical source provenance. Fresh or modified /// parameters identify their real new SafeTensors bytes as the source artifact. pub fn save(&mut self, directory: impl AsRef) -> Result<(), ModelError> { self.metadata.validate()?; let weights: BTreeMap = self.vs.variables().into_iter().collect(); validate_weights(&weights, &self.metadata)?; let fingerprint = weight_fingerprint(&weights)?; let unchanged = self.imported_fingerprint.as_ref() == Some(&fingerprint); let directory = directory.as_ref(); std::fs::create_dir_all(directory)?; let staged = tempfile::tempdir_in(directory)?; let weight_path = staged.path().join("model.safetensors"); self.vs.save(&weight_path)?; let mut metadata = self.metadata.clone(); metadata .extra .insert("artifact_format_version".into(), Value::from(1)); metadata .extra .entry("training".into()) .or_insert_with(|| Value::Object(serde_json::Map::new())); let native_source = metadata .extra .get("source_checkpoint_format") .and_then(Value::as_str) == Some("safetensors"); if !unchanged || native_source { let hash = format!("{:x}", Sha256::digest(std::fs::read(&weight_path)?)); metadata .extra .insert("source_checkpoint_sha256".into(), Value::String(hash)); metadata.extra.insert( "source_checkpoint_format".into(), Value::String("safetensors".into()), ); } let config_path = staged.path().join("config.json"); metadata.save(&config_path)?; std::fs::rename(weight_path, directory.join("model.safetensors"))?; std::fs::rename(config_path, directory.join("config.json"))?; self.metadata = metadata; Ok(()) } } #[cfg(test)] mod tests { use super::*; use crate::config::Thresholds; /// Small real model retaining the complete output-label and token contracts. fn fixture() -> Result { let architecture = ModelConfig { width: 8, heads: 2, layers: 1, feedforward: 16, char_buckets: 16, max_ngrams: 8, ..ModelConfig::default() }; let metadata = ArtifactConfig { architecture, labels: expected_labels(), vocab: [ ("".into(), 0), ("".into(), 1), ("".into(), 2), ("split".into(), 3), ] .into_iter() .collect(), thresholds: Thresholds { probability: 0.8, margin: 0.1, }, extra: BTreeMap::new(), }; ModelBundle::new(metadata, 7) } #[test] fn missing_and_unexpected_weight_names_are_rejected() -> Result<(), ModelError> { let _test = crate::runtime::test_serial_guard(); let bundle = fixture()?; let mut parameters: BTreeMap<_, _> = bundle.vs.variables().into_iter().collect(); parameters.remove("output.bias"); assert!(matches!(validate_weights(¶meters, &bundle.metadata), Err(ModelError::ParameterNames { missing, .. }) if missing == ["output.bias"])); let mut parameters: BTreeMap<_, _> = bundle.vs.variables().into_iter().collect(); parameters.insert( "unregistered.weight".into(), Tensor::f_zeros([1], (Kind::Float, Device::Cpu))?, ); assert!(matches!(validate_weights(¶meters, &bundle.metadata), Err(ModelError::ParameterNames { unexpected, .. }) if unexpected == ["unregistered.weight"])); Ok(()) } #[test] fn incorrect_shapes_dtypes_and_nonfinite_weights_are_rejected() -> Result<(), ModelError> { let _test = crate::runtime::test_serial_guard(); let bundle = fixture()?; let mut parameters: BTreeMap<_, _> = bundle.vs.variables().into_iter().collect(); parameters.insert( "output.weight".into(), Tensor::f_zeros([48, 8], (Kind::Float, Device::Cpu))?, ); assert!(matches!( validate_weights(¶meters, &bundle.metadata), Err(ModelError::ParameterShape { .. }) )); parameters.insert( "output.weight".into(), Tensor::f_zeros([49, 8], (Kind::Double, Device::Cpu))?, ); assert!(matches!( validate_weights(¶meters, &bundle.metadata), Err(ModelError::ParameterType(_)) )); parameters.insert( "output.weight".into(), Tensor::f_full([49, 8], f64::NAN, (Kind::Float, Device::Cpu))?, ); assert!(matches!( validate_weights(¶meters, &bundle.metadata), Err(ModelError::NonFinite(_)) )); Ok(()) } #[test] fn native_artifacts_bind_the_source_hash_to_the_saved_weights() -> Result<(), ModelError> { let _test = crate::runtime::test_serial_guard(); let mut bundle = fixture()?; let directory = tempfile::tempdir()?; bundle.save(directory.path())?; let loaded = ModelBundle::load(directory.path())?; assert_eq!( loaded .metadata .extra .get("source_checkpoint_format") .and_then(Value::as_str), Some("safetensors") ); std::fs::write( directory.path().join("model.safetensors"), b"changed weights", )?; assert!(matches!( ModelBundle::load(directory.path()), Err(ModelError::SourceHashMismatch) )); Ok(()) } }