lispm-llm / src /training.rs
Ryan.K
Publish semantic retraining candidates and blind benchmarks
36fe364 unverified
Raw History Blame Contribute Delete
33 kB
//! Native CPU training with immutable data and calibration-only model selection.
//!
//! Sampling uses ChaCha8, not Python's Mersenne Twister. Matching a seed therefore
//! promises repeatability within this backend, not identical Python parameters.
use std::collections::{BTreeMap, HashMap};
use std::fs;
use std::io::Cursor;
use std::path::{Path, PathBuf};
use std::time::Instant;
use rand::{Rng, SeedableRng};
use rand_chacha::ChaCha8Rng;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use tch::{COptimizer, Device, Kind, Reduction, Tensor};
use thiserror::Error;
use crate::actions::{Action, ActionKind, parse_command};
use crate::config::{ArtifactConfig, ModelConfig, Thresholds, expected_labels};
use crate::metrics::{
CalibrationBatch, CoverageReference, MetricsError, SelectionRank, SelectionReport,
ThresholdSelection, select_thresholds, top_prediction,
};
use crate::model::{ModelBundle, ModelError};
use crate::runtime::{self, RuntimeError};
use crate::tokenizer::{Encoded, TokenizerError, collate, encode, make_vocab, tokenize};
#[path = "training/control.rs"]
mod control;
#[path = "training/data.rs"]
mod data;
#[path = "training/initialization.rs"]
mod initialization;
use control::{StderrControl, checkpoint};
pub use control::{TrainingControl, TrainingProgress};
use data::ValidatedData;
pub use data::{
TrainingDataSummary, rows_sha256, validate_training_data, validate_training_data_bytes,
};
pub use initialization::WarmStartOptions;
use initialization::{InitialModelSnapshot, LearningRates};
/// Training inputs and immutable destination, independent of Python tooling.
#[derive(Debug)]
pub struct TrainOptions {
/// Portable training/calibration data; evaluation files are never read.
pub data_path: PathBuf,
/// A new directory; existing files or directories are never replaced.
pub output_dir: PathBuf,
/// Number of optimizer updates; defaults to 3,200.
pub steps: u32,
/// Native sampling and LibTorch seed; must fit a signed 64-bit integer.
pub seed: u64,
/// CPU worker count; defaults to two.
pub threads: i32,
/// Optional immutable starting weights; absence preserves from-scratch training.
pub warm_start: Option<WarmStartOptions>,
}
impl Default for TrainOptions {
fn default() -> Self {
Self {
data_path: PathBuf::from("data/training.json"),
output_dir: PathBuf::from("artifacts/rust-trained"),
steps: 3200,
seed: 42,
threads: 2,
warm_start: None,
}
}
}
/// Recoverable failures of training, validation, selection or publication.
#[derive(Debug, Error)]
pub enum TrainingError {
/// A caller cancelled before the publication commit boundary.
#[error("training cancelled; no artifact was published")]
Cancelled,
/// Process-wide seed/thread coordination prevented this operation.
#[error(transparent)]
Runtime(#[from] RuntimeError),
/// Training options or the portable data contract are invalid.
#[error("invalid training input: {0}")]
InvalidData(&'static str),
/// A corpus row names an unknown label.
#[error("unknown training label: {0}")]
UnknownLabel(String),
/// Training cannot write over any existing path.
#[error("training output already exists: {0}")]
OutputExists(PathBuf),
/// An immutable data input changed during the run.
#[error("training data changed during the run; no artifact was published")]
DataChanged,
/// Warm-start optimizer rates must be finite, positive and below scratch training.
#[error(
"warm-start learning rate must be finite, positive, below 0.002, and retain a positive final rate"
)]
InvalidWarmStartRate,
/// Source configuration or weights changed after their immutable snapshot.
#[error("initial model changed during the run; no artifact was published")]
InitialModelChanged,
/// No inspected checkpoint met every original-prefix bound.
#[error(
"no checkpoint met all original calibration coverage/error constraints; no artifact was published"
)]
NoEligibleCheckpoint,
/// Loss or gradients became nonfinite.
#[error("nonfinite training value: {0}")]
Nonfinite(&'static str),
/// File or progress-stream IO failed.
#[error(transparent)]
Io(#[from] std::io::Error),
/// A data or report JSON value is invalid.
#[error(transparent)]
Json(#[from] serde_json::Error),
/// Encoding failed.
#[error(transparent)]
Tokenizer(#[from] TokenizerError),
/// Tensor computation or optimizer execution failed.
#[error(transparent)]
Tensor(#[from] tch::TchError),
/// Model initialization, snapshot restoration or publication failed.
#[error(transparent)]
Model(#[from] ModelError),
/// Calibration or incumbent eligibility validation failed.
#[error(transparent)]
Metrics(#[from] MetricsError),
}
/// Selected model evidence and all reproducibility settings.
#[derive(Debug, Serialize, Deserialize)]
pub struct TrainingReport {
/// Shared seed for native sampling and initial LibTorch state.
pub seed: u64,
/// Total optimizer steps run, including after the selected checkpoint.
pub steps: u32,
/// Eligible checkpoint selected using calibration only.
pub selected_step: u32,
/// Number of trainable scalar parameters.
pub parameters: usize,
/// Number of distinct training rows.
pub train_unique: usize,
/// Number of distinct calibration rows.
pub calibration_unique: usize,
/// Ordered training text/label digest, matching the Python serialization.
pub training_sha256: String,
/// Ordered calibration text/label digest.
pub calibration_sha256: String,
/// Original calibration prefix length.
pub original_calibration_unique: usize,
/// Added calibration suffix length.
pub added_calibration_unique: usize,
/// Full frozen incumbent reference, including its historical checkpoint.
pub selection_reference: Value,
/// Digest of the exact reference source JSON bytes.
pub selection_reference_sha256: String,
/// Selected runtime gates, bounded by the original reference.
pub thresholds: Thresholds,
/// Exact checkpoint ordering description.
pub weight_selection: String,
/// Selected checkpoint's disjoint outcomes and eligibility evidence.
pub calibration: SelectionReport,
/// Explicit backend, optimizer, sampling and duration details.
#[serde(flatten)]
pub runtime: BTreeMap<String, Value>,
}
/// Class-specific row pools preserve concise commands during augmentation.
struct SamplingPools {
/// All available training row indices for each class.
general: Vec<Vec<usize>>,
/// Indices containing at most four tokens, partitioned by class.
short: Vec<Vec<usize>>,
/// Supported examples eligible for additional hard-example sampling.
hard_supported: Vec<usize>,
/// Unsupported examples eligible for additional hard-example sampling.
hard_rejected: Vec<usize>,
/// Class receiving sixty-four ordinary rejection samples per batch.
reject_index: usize,
}
/// An eligible immutable weight snapshot; optimizer state is never published.
struct SelectedCheckpoint {
/// Calibration-only ordering measured for these exact stored weights.
rank: SelectionRank,
/// Independent LibTorch parameter snapshot, excluding optimizer state.
weights: Vec<u8>,
/// Optimizer update after which this checkpoint was measured.
step: u32,
}
/// Calibration measurements used for deterministic selection and progress.
struct CalibrationResult {
/// Selected bounded thresholds with complete incumbent-eligibility evidence.
selection: ThresholdSelection,
/// Mean unsmoothed negative log likelihood on the calibration corpus.
loss: f64,
/// Raw top-class accuracy before confidence and typed admission gates.
accuracy: f64,
}
/// Borrowed immutable inputs shared by selection, evidence and publication.
struct RunContext<'a> {
/// Validated caller settings, including optional warm-start configuration.
options: &'a TrainOptions,
/// Frozen training and calibration bytes with their selection reference.
data: &'a ValidatedData,
/// Class-balanced training-only sampling pools.
pools: &'a SamplingPools,
/// Exact source snapshot for warm starts, absent for fresh initialization.
initial_model: Option<&'a InitialModelSnapshot>,
/// Start time used only for the reported elapsed wall-clock duration.
started: Instant,
}
impl SamplingPools {
/// Partition training indices once; every class and hard subset must exist.
fn build(data: &ValidatedData) -> Result<Self, TrainingError> {
let count = data
.reject_index
.checked_add(1)
.ok_or(TrainingError::InvalidData("class count overflow"))?;
let mut pools = Self {
general: vec![Vec::new(); count],
short: vec![Vec::new(); count],
hard_supported: Vec::new(),
hard_rejected: Vec::new(),
reject_index: data.reject_index,
};
for (index, ((phrase, _), &label)) in data
.source
.training_rows
.iter()
.zip(&data.training_labels)
.enumerate()
{
pools
.general
.get_mut(label)
.ok_or(TrainingError::InvalidData("unknown class"))?
.push(index);
if tokenize(phrase)?.len() <= 4 {
pools
.short
.get_mut(label)
.ok_or(TrainingError::InvalidData("unknown class"))?
.push(index);
}
}
if pools.general.iter().any(Vec::is_empty) {
return Err(TrainingError::InvalidData(
"every action and reject require training examples",
));
}
for &index in &data.source.hard_training_indices {
let &label = data
.training_labels
.get(index)
.ok_or(TrainingError::InvalidData(
"hard example is not in training",
))?;
if label == data.reject_index {
pools.hard_rejected.push(index);
} else {
pools.hard_supported.push(index);
}
}
if pools.hard_supported.is_empty() || pools.hard_rejected.is_empty() {
return Err(TrainingError::InvalidData(
"hard sampling requires both positive and reject rows",
));
}
Ok(pools)
}
/// Draw with replacement using only native training pools.
fn sample(&self, rng: &mut ChaCha8Rng) -> Result<Vec<usize>, TrainingError> {
let mut rows = Vec::new();
for (label, (general, short)) in self.general.iter().zip(&self.short).enumerate() {
if label == self.reject_index {
sample_rows(general, 64, rng, &mut rows)?;
} else {
sample_rows(
if short.is_empty() { general } else { short },
2,
rng,
&mut rows,
)?;
sample_rows(general, 4, rng, &mut rows)?;
}
}
sample_rows(&self.hard_supported, 32, rng, &mut rows)?;
sample_rows(&self.hard_rejected, 32, rng, &mut rows)?;
Ok(rows)
}
}
/// Add independent samples, rejecting an empty domain before invoking the RNG.
fn sample_rows(
pool: &[usize],
count: usize,
rng: &mut ChaCha8Rng,
rows: &mut Vec<usize>,
) -> Result<(), TrainingError> {
if pool.is_empty() {
return Err(TrainingError::InvalidData("empty sampling pool"));
}
for _ in 0..count {
rows.push(
*pool
.get(rng.gen_range(0..pool.len()))
.ok_or(TrainingError::InvalidData("sampling index"))?,
);
}
Ok(())
}
/// Drop whole words while preserving reserved tokens, NAME and character input.
fn drop_words(words: &Tensor, vocab: &HashMap<String, i64>) -> Result<Tensor, TrainingError> {
let unknown = *vocab
.get("<unk>")
.ok_or(TrainingError::InvalidData("missing unknown token"))?;
let mut mask = Tensor::f_rand(words.size(), (Kind::Float, Device::Cpu))?
.f_lt(0.1)?
.f_logical_and(&words.f_gt(2)?)?;
if let Some(&name) = vocab.get("NAME") {
mask = mask.f_logical_and(&words.f_ne(name)?)?;
}
Ok(words.f_masked_fill(&mask, unknown)?)
}
/// Clip the joint Euclidean gradient norm without infallible optimizer wrappers.
fn clip_gradients(parameters: &[Tensor]) -> Result<(), TrainingError> {
tch::no_grad(|| {
let mut gradients = Vec::new();
let mut squared_norm = 0.0;
for parameter in parameters {
let gradient = parameter.f_grad()?;
if gradient.defined() {
let norm = gradient.f_norm()?.f_double_value(&[])?;
squared_norm += norm * norm;
gradients.push(gradient);
}
}
if !squared_norm.is_finite() {
return Err(TrainingError::Nonfinite("gradient norm"));
}
let scale = (1.0 / (squared_norm.sqrt() + 1e-6)).min(1.0);
for mut gradient in gradients {
let _ = gradient.f_mul_scalar_(scale)?;
}
Ok(())
})
}
/// The cosine schedule is evaluated after each optimizer update, as in Python.
fn learning_rate(step: u32, steps: u32, rates: LearningRates) -> Result<f64, TrainingError> {
if steps == 0 || step > steps {
return Err(TrainingError::InvalidData("invalid scheduler step"));
}
let phase = std::f64::consts::PI * f64::from(step) / f64::from(steps);
Ok(rates.minimum + (rates.initial - rates.minimum) * (1.0 + phase.cos()) / 2.0)
}
/// Perform one label-smoothed AdamW update over a balanced sampled batch.
fn optimize_batch(
bundle: &ModelBundle,
encoded: &[Encoded],
labels: &[usize],
indices: &[usize],
parameters: &[Tensor],
optimizer: &COptimizer,
) -> Result<f64, TrainingError> {
// Encoded values are immutable examples; cloning forms an independent batch.
let batch: Vec<Encoded> = indices
.iter()
.map(|&index| {
encoded
.get(index)
.cloned()
.ok_or(TrainingError::InvalidData("encoded training index"))
})
.collect::<Result<_, _>>()?;
let targets: Vec<i64> = indices
.iter()
.map(|&index| {
labels
.get(index)
.and_then(|&label| i64::try_from(label).ok())
.ok_or(TrainingError::InvalidData("training target index"))
})
.collect::<Result<_, _>>()?;
let (words, characters) = collate(&batch, &bundle.metadata.architecture)?;
let words = drop_words(&words, &bundle.metadata.vocab)?;
let logits = bundle.model.forward(&words, &characters, true)?;
let loss = logits.f_cross_entropy_loss::<&Tensor>(
&Tensor::f_from_slice(&targets)?,
None,
Reduction::Mean,
-100,
0.05,
)?;
let value = loss.f_double_value(&[])?;
if !value.is_finite() {
return Err(TrainingError::Nonfinite("training loss"));
}
optimizer.zero_grad()?;
loss.f_backward()?;
clip_gradients(parameters)?;
optimizer.step()?;
Ok(value)
}
/// Score bounded batches without dropout or gradient recording.
fn probabilities(
bundle: &ModelBundle,
encoded: &[Encoded],
control: &(impl TrainingControl + ?Sized),
) -> Result<Vec<Vec<f64>>, TrainingError> {
tch::no_grad(|| {
let mut values = Vec::with_capacity(encoded.len());
for batch in encoded.chunks(64) {
checkpoint(control)?;
let (words, characters) = collate(batch, &bundle.metadata.architecture)?;
let probabilities = bundle
.model
.forward(&words, &characters, false)?
.f_softmax(-1, Kind::Float)?;
values.extend(Vec::<Vec<f64>>::try_from(&probabilities)?);
}
checkpoint(control)?;
Ok(values)
})
}
/// Apply the same parser and typed argument boundary as runtime inference.
fn admissible(command: &str, label: &str) -> bool {
let Ok(kind) = ActionKind::from_label(label) else {
return false;
};
let Ok(clauses) = parse_command(command) else {
return false;
};
if clauses.len() != 1 {
return false;
}
clauses
.into_iter()
.next()
.is_some_and(|clause| Action::new(kind, clause.name).is_ok())
}
/// Compute unsmoothed calibration loss and bounded, eligible-first thresholds.
fn calibrate(
bundle: &ModelBundle,
encoded: &[Encoded],
data: &ValidatedData,
control: &(impl TrainingControl + ?Sized),
) -> Result<CalibrationResult, TrainingError> {
let probabilities = probabilities(bundle, encoded, control)?;
let mut allowed = Vec::with_capacity(probabilities.len());
let mut loss = 0.0;
let mut correct = 0_u32;
for ((row, &expected), command) in probabilities
.iter()
.zip(&data.calibration_labels)
.zip(&data.source.calibration_commands)
{
checkpoint(control)?;
let prediction = top_prediction(row)?;
let label = bundle
.metadata
.labels
.get(prediction.label)
.ok_or(TrainingError::InvalidData("prediction label index"))?;
allowed.push(admissible(command, label));
let probability = row
.get(expected)
.ok_or(TrainingError::InvalidData("calibration target index"))?;
loss -= probability.max(1e-12).ln();
correct += u32::from(prediction.label == expected);
}
let total = u32::try_from(probabilities.len())
.map_err(|_| TrainingError::InvalidData("too many calibration rows"))?;
if total == 0 {
return Err(TrainingError::InvalidData("empty calibration"));
}
let batch = CalibrationBatch::new(
&probabilities,
&data.calibration_labels,
&allowed,
data.reject_index,
)?;
let reference = CoverageReference {
row_count: data.source.reference.calibration_size,
metrics: &data.source.reference.metrics,
};
checkpoint(control)?;
let selection = select_thresholds(&batch, Some(reference), &data.source.reference.thresholds)?;
checkpoint(control)?;
Ok(CalibrationResult {
selection,
loss: loss / f64::from(total),
accuracy: f64::from(correct) / f64::from(total),
})
}
/// Emit an immutable calibration evidence snapshot through the caller adapter.
fn progress(
step: u32,
steps: u32,
loss: f64,
calibration: &CalibrationResult,
control: &mut (impl TrainingControl + ?Sized),
) -> Result<(), TrainingError> {
let report = &calibration.selection.report;
// A progress snapshot owns copies of immutable counts, never model state.
control.progress(&TrainingProgress::Calibration {
step,
steps,
train_loss: loss,
calibration_loss: calibration.loss,
calibration_accuracy: calibration.accuracy,
decision_utility: report.metrics.utility,
eligible: report.eligible,
original: report.original.clone(),
added: report.added.clone(),
})
}
/// Preserve a weight snapshot only if all bounds hold and its rank improves.
fn consider_checkpoint(
bundle: &ModelBundle,
step: u32,
calibration: &CalibrationResult,
best: &mut Option<SelectedCheckpoint>,
) -> Result<(), TrainingError> {
if !calibration.selection.report.eligible {
return Ok(());
}
let rank = calibration.selection.rank(calibration.loss)?;
if best
.as_ref()
.is_some_and(|previous| !rank.compare(&previous.rank).is_gt())
{
return Ok(());
}
let mut weights = Vec::new();
bundle.vs.save_to_stream(&mut weights)?;
*best = Some(SelectedCheckpoint {
rank,
weights,
step,
});
Ok(())
}
/// Collect backend settings explicitly; these do not claim Python seed parity.
fn runtime_metadata(
options: &TrainOptions,
pools: &SamplingPools,
elapsed: f64,
source_sha256: &str,
rates: LearningRates,
initial_model: Option<&InitialModelSnapshot>,
selected_step: u32,
) -> BTreeMap<String, Value> {
BTreeMap::from([
("training_data_sha256".into(), json!(source_sha256)),
(
"initialization".into(),
initialization::provenance(initial_model),
),
(
"selected_checkpoint_has_updates".into(),
json!(selected_step > 0),
),
("backend".into(), json!("rust-tch")),
("tch_version".into(), json!("0.22.0")),
("torch_version".into(), json!("2.9.0")),
("device".into(), json!("cpu")),
("threads".into(), json!(options.threads)),
("action_count".into(), json!(pools.reject_index)),
("label_smoothing".into(), json!(0.05)),
("word_dropout".into(), json!(0.1)),
(
"learning_rate_schedule".into(),
json!(format!("cosine {} to {}", rates.initial, rates.minimum)),
),
("learning_rate_initial".into(), json!(rates.initial)),
("learning_rate_minimum".into(), json!(rates.minimum)),
(
"optimizer".into(),
json!({"name":"AdamW", "weight_decay":0.01, "beta1":0.9, "beta2":0.999, "epsilon":1e-8, "clip_gradient_norm":1.0}),
),
(
"sampling_rng".into(),
json!("rand_chacha 0.3 ChaCha8Rng; differs from Python Mersenne Twister"),
),
(
"sampling".into(),
json!(
"per action: 2 short (<=4 words) + 4 general; 64 rejects; 32 hard supported + 32 hard rejects"
),
),
(
"hard_supported_rows".into(),
json!(pools.hard_supported.len()),
),
("hard_reject_rows".into(), json!(pools.hard_rejected.len())),
("training_elapsed_seconds".into(), json!(elapsed)),
])
}
/// Build an auditable report from the re-evaluated selected weights.
fn build_report(
context: &RunContext<'_>,
bundle: &ModelBundle,
selected: u32,
calibration: ThresholdSelection,
) -> Result<TrainingReport, TrainingError> {
let options = context.options;
let data = context.data;
let rates = LearningRates::for_options(options)?;
let parameters = bundle
.vs
.trainable_variables()
.iter()
.try_fold(0_usize, |sum, tensor| {
sum.checked_add(tensor.numel())
.ok_or(TrainingError::InvalidData("parameter count overflow"))
})?;
Ok(TrainingReport {
seed: options.seed, steps: options.steps, selected_step: selected, parameters,
train_unique: data.source.training_rows.len(), calibration_unique: data.source.calibration_rows.len(),
training_sha256: data.source.training_sha256.to_owned(), calibration_sha256: data.source.calibration_sha256.to_owned(),
original_calibration_unique: data.source.reference.calibration_size,
added_calibration_unique: data.source.calibration_rows.len().checked_sub(data.source.reference.calibration_size)
.ok_or(TrainingError::InvalidData("reference length"))?,
selection_reference: serde_json::to_value(&data.source.reference)?,
selection_reference_sha256: data.source.selection_reference_sha256.to_owned(),
thresholds: calibration.thresholds, calibration: calibration.report,
weight_selection: "eligible original coverage/error bounds; utility, fewer errors, more correct, lower thresholds, then loss".into(),
runtime: runtime_metadata(options, context.pools, context.started.elapsed().as_secs_f64(), &data.source_sha256, rates, context.initial_model, selected),
})
}
/// Publish into a directory claimed atomically with create_dir, never replacing.
fn publish(
bundle: &mut ModelBundle,
report: &TrainingReport,
output: &Path,
) -> Result<(), TrainingError> {
if let Some(parent) = output
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
{
fs::create_dir_all(parent)?;
}
match fs::create_dir(output) {
Ok(()) => {}
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
return Err(TrainingError::OutputExists(output.to_path_buf()));
}
Err(error) => return Err(error.into()),
}
let mut training = serde_json::to_value(report)?;
let fields = training
.as_object_mut()
.ok_or(TrainingError::InvalidData("training metadata object"))?;
fields.insert("trained_steps".into(), json!(report.steps));
fields.insert("format_version".into(), json!(3));
bundle.metadata.extra.insert("training".into(), training);
bundle.save(output)?;
let mut bytes = serde_json::to_vec_pretty(report)?;
bytes.push(b'\n');
fs::write(output.join("training-report.json"), bytes)?;
Ok(())
}
/// Train from fresh or explicitly supplied weights; publish only an eligible checkpoint.
///
/// CLI progress remains newline-delimited JSON on stderr. Native callers use
/// `train_with_control` to supply cancellation and their own progress transport.
pub fn train(options: &TrainOptions) -> Result<TrainingReport, TrainingError> {
train_with_control(options, &mut StderrControl)
}
/// Train with cooperative cancellation and typed progress, without stderr IO.
///
/// Holds the shared runtime capability until publication is complete. Other
/// training/model-loading operations receive `RuntimeError::Busy`; inference
/// using an already-loaded model may continue. Checks cancellation between
/// optimizer kernels, calibration batches and immediately before publication.
/// Once publication begins, completion wins over a late cancellation request.
/// Failed publication IO may leave a partial new directory, never replace one.
pub fn train_with_control(
options: &TrainOptions,
control: &mut (impl TrainingControl + ?Sized),
) -> Result<TrainingReport, TrainingError> {
let started = Instant::now();
checkpoint(control)?;
if options.steps == 0 || options.threads <= 0 {
return Err(TrainingError::InvalidData(
"steps and threads must be positive",
));
}
LearningRates::for_options(options)?;
let seed = i64::try_from(options.seed)
.map_err(|_| TrainingError::InvalidData("seed exceeds signed 64-bit range"))?;
if options.output_dir.try_exists()? {
return Err(TrainingError::OutputExists(options.output_dir.to_owned()));
}
control.progress(&TrainingProgress::Validating {
steps: options.steps,
})?;
checkpoint(control)?;
let data = ValidatedData::load(&options.data_path)?;
let pools = SamplingPools::build(&data)?;
checkpoint(control)?;
let initial_model = options
.warm_start
.as_ref()
.map(InitialModelSnapshot::capture)
.transpose()?;
let _runtime = runtime::try_acquire()?;
runtime::configure_threads(options.threads)?;
control.progress(&TrainingProgress::Started {
steps: options.steps,
train_unique: data.source.training_rows.len(),
calibration_unique: data.source.calibration_rows.len(),
})?;
checkpoint(control)?;
let mut bundle = match &initial_model {
Some(source) => source.load(seed)?,
None => ModelBundle::new(
ArtifactConfig {
architecture: ModelConfig::default(),
labels: expected_labels(),
vocab: make_vocab(&data.source.training_rows)?,
thresholds: data.source.reference.thresholds,
extra: BTreeMap::new(),
},
seed,
)?,
};
let training = encode_rows(&bundle, &data.source.training_rows, control)?;
let calibration = encode_rows(&bundle, &data.source.calibration_rows, control)?;
let selected = optimize(
&bundle,
&training,
&calibration,
&data,
&pools,
options,
control,
)?;
let context = RunContext {
options,
data: &data,
pools: &pools,
initial_model: initial_model.as_ref(),
started,
};
complete_training(&context, &mut bundle, selected, &calibration, control)
}
/// Restore selected weights, verify immutable inputs, then publish at one boundary.
fn complete_training(
context: &RunContext<'_>,
bundle: &mut ModelBundle,
selected: SelectedCheckpoint,
calibration: &[Encoded],
control: &mut (impl TrainingControl + ?Sized),
) -> Result<TrainingReport, TrainingError> {
let options = context.options;
let data = context.data;
control.progress(&TrainingProgress::Selecting {
selected_step: selected.step,
})?;
checkpoint(control)?;
data.ensure_unchanged(&options.data_path)?;
if let Some(source) = context.initial_model {
source.ensure_unchanged()?;
}
bundle.vs.load_from_stream(Cursor::new(selected.weights))?;
let result = calibrate(bundle, calibration, data, control)?;
if !result.selection.report.eligible {
return Err(TrainingError::NoEligibleCheckpoint);
}
bundle.metadata.thresholds = result.selection.thresholds;
let report = build_report(context, bundle, selected.step, result.selection)?;
data.ensure_unchanged(&options.data_path)?;
control.progress(&TrainingProgress::Publishing {
selected_step: selected.step,
})?;
checkpoint(control)?;
if let Some(source) = context.initial_model {
source.ensure_unchanged()?;
}
publish(bundle, &report, &options.output_dir)?;
// Publication is the commit point. A late cancellation or reporting failure
// must not claim that no artifact exists after a successful commit.
let _ = control.progress(&TrainingProgress::Completed {
selected_step: selected.step,
output_dir: options.output_dir.to_owned(),
});
Ok(report)
}
/// Encode immutable examples while allowing cancellation before model kernels.
fn encode_rows(
bundle: &ModelBundle,
rows: &[(String, String)],
control: &(impl TrainingControl + ?Sized),
) -> Result<Vec<Encoded>, TrainingError> {
rows.iter()
.map(|(phrase, _)| {
checkpoint(control)?;
Ok(encode(
phrase,
&bundle.metadata.vocab,
&bundle.metadata.architecture,
)?)
})
.collect()
}
/// Run optimizer updates and calibration-only checkpoint selection under control.
fn optimize(
bundle: &ModelBundle,
training: &[Encoded],
calibration: &[Encoded],
data: &ValidatedData,
pools: &SamplingPools,
options: &TrainOptions,
control: &mut (impl TrainingControl + ?Sized),
) -> Result<SelectedCheckpoint, TrainingError> {
let rates = LearningRates::for_options(options)?;
let parameters = bundle.vs.trainable_variables();
let mut optimizer = COptimizer::adamw(rates.initial, 0.9, 0.999, 0.01, 1e-8, false)?;
for parameter in &parameters {
optimizer.add_parameters(parameter, 0)?;
}
let mut rng = ChaCha8Rng::seed_from_u64(options.seed);
let mut best = None;
if options.warm_start.is_some() {
let initial = calibrate(bundle, calibration, data, control)?;
consider_checkpoint(bundle, 0, &initial, &mut best)?;
}
for step in 1..=options.steps {
checkpoint(control)?;
let indices = pools.sample(&mut rng)?;
let loss = optimize_batch(
bundle,
training,
&data.training_labels,
&indices,
&parameters,
&optimizer,
)?;
checkpoint(control)?;
optimizer.set_learning_rate(learning_rate(step, options.steps, rates)?)?;
if step == 1 || step % 25 == 0 || step == options.steps {
control.progress(&TrainingProgress::Step {
step,
steps: options.steps,
train_loss: loss,
})?;
checkpoint(control)?;
}
if step % 100 == 0 || step == options.steps {
let result = calibrate(bundle, calibration, data, control)?;
progress(step, options.steps, loss, &result, control)?;
checkpoint(control)?;
consider_checkpoint(bundle, step, &result, &mut best)?;
}
}
checkpoint(control)?;
best.ok_or(TrainingError::NoEligibleCheckpoint)
}
#[cfg(test)]
#[path = "training/tests.rs"]
mod tests;