File size: 5,498 Bytes
36fe364
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
//! 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<Self, TrainingError> {
        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<Self, TrainingError> {
        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<ModelBundle, TrainingError> {
        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,
    )
}