//! Optional warm starts bind trainable state to immutable source byte snapshots. use std::fs; use std::path::PathBuf; use serde_json::{Value, json}; use super::data::sha256; use super::{TrainOptions, TrainingError}; use crate::model::ModelBundle; /// Explicit source weights and conservative optimizer rate for native fine-tuning. #[derive(Debug)] pub struct WarmStartOptions { /// Existing directory containing the fixed-vocabulary model to initialize from. pub model_dir: PathBuf, /// Finite positive initial rate, strictly below the from-scratch rate of 0.002. pub learning_rate: f64, } impl WarmStartOptions { /// Reject invalid rates before reading model files or claiming the runtime. pub(super) fn validate(&self) -> Result<(), TrainingError> { if !self.learning_rate.is_finite() || self.learning_rate <= 0.0 || self.learning_rate >= 0.002 || self.learning_rate / 20.0 == 0.0 { return Err(TrainingError::InvalidWarmStartRate); } Ok(()) } } /// Validated endpoints preserve the original schedule for from-scratch callers. #[derive(Clone, Copy)] pub(super) struct LearningRates { /// Rate used by the first optimizer update. pub(super) initial: f64, /// Positive rate reached after the final optimizer update. pub(super) minimum: f64, } impl LearningRates { /// Derive rates without changing any from-scratch arithmetic constants. pub(super) fn for_options(options: &TrainOptions) -> Result { match &options.warm_start { Some(source) => { source.validate()?; Ok(Self { initial: source.learning_rate, minimum: source.learning_rate / 20.0, }) } None => Ok(Self { initial: 0.002, minimum: 0.0001, }), } } } /// Private model files and identities bind hashing, validation and loading. pub(super) struct InitialModelSnapshot { /// Canonical source directory, rechecked before artifact publication. source_dir: PathBuf, /// Digest of the exact source configuration bytes loaded by the model. config_sha256: String, /// Digest of the exact source SafeTensors bytes loaded by the model. weights_sha256: String, /// Privately owned copied files; dropping the snapshot removes only this copy. snapshot: tempfile::TempDir, } impl InitialModelSnapshot { /// Copy each source exactly once, then hash and load only those owned bytes. pub(super) fn capture(options: &WarmStartOptions) -> Result { options.validate()?; let source_dir = fs::canonicalize(&options.model_dir)?; let config = fs::read(source_dir.join("config.json"))?; let weights = fs::read(source_dir.join("model.safetensors"))?; let snapshot = tempfile::tempdir()?; fs::write(snapshot.path().join("config.json"), &config)?; fs::write(snapshot.path().join("model.safetensors"), &weights)?; let source = Self { source_dir, config_sha256: sha256(&config), weights_sha256: sha256(&weights), snapshot, }; source.ensure_unchanged()?; Ok(source) } /// Retain vocabulary and character architecture, then reset training RNG. pub(super) fn load(&self, seed: i64) -> Result { let mut bundle = ModelBundle::load(self.snapshot.path())?; // Loading constructs temporary randomized tensors. Reseeding afterwards // makes dropout independent of the caller's earlier LibTorch RNG state. tch::manual_seed(seed); // Even a selected step-zero copy is a native SafeTensors artifact. Its // immutable parent identity lives separately in training.initialization. bundle.metadata.extra.insert( "source_checkpoint_format".into(), Value::String("safetensors".into()), ); bundle.metadata.extra.insert( "source_checkpoint_sha256".into(), Value::String(self.weights_sha256.to_owned()), ); Ok(bundle) } /// Abort publication if either original model file changed during training. pub(super) fn ensure_unchanged(&self) -> Result<(), TrainingError> { let config = fs::read(self.source_dir.join("config.json"))?; let weights = fs::read(self.source_dir.join("model.safetensors"))?; if sha256(&config) != self.config_sha256 || sha256(&weights) != self.weights_sha256 { return Err(TrainingError::InitialModelChanged); } Ok(()) } /// Report source identity independently of the newly saved artifact's hash. pub(super) fn provenance(&self) -> Value { json!({ "mode": "warm_start", "config_sha256": self.config_sha256, "weights_sha256": self.weights_sha256, "vocabulary": "retained", "character_features": "retained", "optimizer_state": "fresh" }) } } /// Describe initialization without treating an output artifact as its own parent. pub(super) fn provenance(source: Option<&InitialModelSnapshot>) -> Value { source.map_or_else( || json!({"mode": "from_scratch", "vocabulary": "training_rows", "optimizer_state": "fresh"}), InitialModelSnapshot::provenance, ) }