use crate::{
DType, Error, Matrix, Result,
data::{Batch, DataLoader},
ml::{
CheckpointManager, GradientTape, Module, autograd::recording_active, matrix::detach, metric,
},
};
use super::{ExecutionMode, Training, TrainingOptimizer, TrainingSnapshot};
use crate::ml::types::ValidationResult;
#[derive(Clone, Copy, Debug)]
pub struct EvaluationReport {
pub summary: ValidationResult,
pub correct: Option<u64>,
}
impl EvaluationReport {
#[must_use]
pub fn accuracy(self) -> Option<f64> {
self
.correct
.filter(|_| self.summary.samples != 0)
.map(|correct| correct as f64 / self.summary.samples as f64)
}
}
#[derive(Clone, Debug)]
pub struct TrainingEpoch {
pub epoch: u64,
pub batches: u64,
pub samples: u64,
pub loss: f64,
pub metrics: Vec<(String, f64)>,
pub validation: Option<EvaluationReport>,
}
#[derive(Clone, Debug)]
pub struct TrainingHistory {
pub epochs: Vec<TrainingEpoch>,
pub snapshot: TrainingSnapshot,
pub best_epoch: Option<u64>,
}
#[derive(Default)]
pub struct TrainingFitOptions<'fit, 'runtime> {
pub categorical_accuracy: bool,
pub validation: Option<&'fit mut dyn FnMut() -> Result<EvaluationReport>>,
pub checkpoint: Option<(&'fit mut CheckpointManager<'runtime>, &'fit dyn Module)>,
pub accumulation_steps: u64,
pub resume: Option<crate::ml::RunState>,
}
impl TrainingFitOptions<'_, '_> {
#[inline]
#[must_use]
pub fn new() -> Self {
Self::default()
}
}
struct ManagedStep {
loss: Matrix,
correct: Option<Matrix>,
prediction: Option<Matrix>,
}
impl Training<'_, '_> {
pub fn fit(
self,
model: &dyn Module,
loader: &mut DataLoader<'_>,
epochs: u64,
mut loss: impl FnMut(&Matrix, &Matrix) -> Result<Matrix>,
) -> Result<TrainingHistory> {
self.fit_with_options(model, loader, epochs, &mut loss, TrainingFitOptions::new())
}
pub fn fit_with_options(
self,
model: &dyn Module,
loader: &mut DataLoader<'_>,
epochs: u64,
loss: impl FnMut(&Matrix, &Matrix) -> Result<Matrix>,
options: TrainingFitOptions<'_, '_>,
) -> Result<TrainingHistory> {
model.train(true);
if let Some(resume) = &options.resume {
loader.seek(resume.epoch, resume.loader_cursor)?;
}
let accumulation_parameters = if options.accumulation_steps > 1 {
Some(model.all_parameters()?)
} else {
None
};
self.fit_supervised_batches_inner(
epochs,
loader.num_batches() as u64,
|epoch, index| {
if index == 0 {
loader.reset_epoch(epoch)?;
}
loader
.next_batch()?
.ok_or_else(|| Error::failed_precondition("training loader ran out of batches"))
},
|x| model.forward(x),
loss,
options,
accumulation_parameters,
)
}
pub fn fit_supervised_batches(
self,
epochs: u64,
batches_per_epoch: u64,
batch_at: impl FnMut(u64, u64) -> Result<Batch>,
forward: impl FnMut(&Matrix) -> Result<Matrix>,
loss: impl FnMut(&Matrix, &Matrix) -> Result<Matrix>,
options: TrainingFitOptions<'_, '_>,
) -> Result<TrainingHistory> {
self.fit_supervised_batches_inner(
epochs,
batches_per_epoch,
batch_at,
forward,
loss,
options,
None,
)
}
#[allow(clippy::too_many_arguments)]
fn fit_supervised_batches_inner(
self,
epochs: u64,
batches_per_epoch: u64,
batch_at: impl FnMut(u64, u64) -> Result<Batch>,
mut forward: impl FnMut(&Matrix) -> Result<Matrix>,
mut loss: impl FnMut(&Matrix, &Matrix) -> Result<Matrix>,
options: TrainingFitOptions<'_, '_>,
accumulation_parameters: Option<Vec<crate::ml::Parameter>>,
) -> Result<TrainingHistory> {
let accuracy = options.categorical_accuracy;
self.fit_batches(
epochs,
batches_per_epoch,
batch_at,
|batch| supervised_step(batch, &mut forward, &mut loss, accuracy),
options,
accumulation_parameters,
)
}
pub fn fit_with(
self,
epochs: u64,
batches_per_epoch: u64,
batch_at: impl FnMut(u64, u64) -> Result<Batch>,
mut step: impl FnMut(&Batch) -> Result<Matrix>,
) -> Result<TrainingHistory> {
self.fit_batches(
epochs,
batches_per_epoch,
batch_at,
|batch| {
Ok(ManagedStep {
loss: step(batch)?,
correct: None,
prediction: None,
})
},
TrainingFitOptions::new(),
None,
)
}
fn fit_batches(
mut self,
epochs: u64,
batches_per_epoch: u64,
mut batch_at: impl FnMut(u64, u64) -> Result<Batch>,
mut step: impl FnMut(&Batch) -> Result<ManagedStep>,
mut options: TrainingFitOptions<'_, '_>,
accumulation_parameters: Option<Vec<crate::ml::Parameter>>,
) -> Result<TrainingHistory> {
if let Some((manager, _)) = &options.checkpoint {
if options.validation.is_none() {
return Err(Error::invalid_argument(
"fit checkpoint selection requires validation",
));
}
if !manager.saves_best_loss() {
return Err(Error::invalid_argument(
"fit checkpointing requires a manager that saves the lowest validation loss",
));
}
checkpoint_optimizer(&mut self.optimizer)?;
}
if self.started
|| self.config.initial_step != 0
|| self.config.total_steps != 0
|| self.config.steps_per_epoch != 0
|| !self.config.epoch_steps.is_empty()
{
return Err(Error::failed_precondition(
"fit requires a fresh training run without a manual step schedule",
));
}
if epochs == 0 || batches_per_epoch == 0 {
return Err(Error::invalid_argument(
"fit requires at least one epoch and batch",
));
}
let start_epoch = options.resume.as_ref().map_or(0, |resume| resume.epoch);
let start_cursor = options
.resume
.as_ref()
.map_or(0, |resume| resume.loader_cursor);
if start_epoch >= epochs {
return Err(Error::invalid_argument(
"fit resume epoch is outside the total epoch budget",
));
}
if start_cursor < 0 || start_cursor as u64 >= batches_per_epoch {
return Err(Error::invalid_argument(
"fit resume cursor is outside the epoch",
));
}
let window = options.accumulation_steps.max(1);
if window > 1 && accumulation_parameters.is_none() {
return Err(Error::invalid_argument(
"gradient accumulation requires the managed model fit — caller-driven batch sources do not expose the parameter set",
));
}
without_active_tape()?;
let updates_per_epoch = batches_per_epoch.div_ceil(window);
self.config.total_steps = epochs
.checked_mul(updates_per_epoch)
.ok_or_else(|| Error::resource_exhausted("fit step budget overflows u64"))?;
self.config.steps_per_epoch = updates_per_epoch;
self.sample_weighted_loss = true;
self.disable_eager_resource_reuse();
self.select_execution_mode(ExecutionMode::Eager)?;
if self.runtime.has_pending_work() {
self.runtime.checkpoint()?.wait()?;
}
let mut history = Vec::new();
let mut best_epoch = None;
for epoch in start_epoch..epochs {
let before = self.snapshot();
let mut counts = Vec::new();
let first_index = if epoch == start_epoch {
start_cursor as u64
} else {
0
};
let mut index = first_index;
while index < batches_per_epoch {
let window_end = index.saturating_add(window).min(batches_per_epoch);
let previous_step = self.step_count;
if !self.wait_begin_step()? {
self.step_count = previous_step;
break;
}
let result = (|| {
self.zero_grad();
let mut total_samples = 0_u64;
let mut window_loss: Option<Matrix> = None;
let mut completion_loss: Option<Matrix> = None;
for microbatch in index..window_end {
let batch = batch_at(epoch, microbatch)?;
let samples = batch_samples(&batch)?;
if !self.runtime.owns_matrix(&batch.x) {
return Err(Error::invalid_argument("batch belongs to another Runtime"));
}
self.config.batch_size = self.config.batch_size.max(samples);
let tape = GradientTape::new();
let step = step(&batch)?;
validate_loss(&batch, &step.loss)?;
let backward_loss = if window > 1 {
let factor = Matrix::new_from_slice_on(self.runtime, vec![], &[samples as f32])?;
step.loss.mul(&factor)?
} else {
step.loss.clone()
};
tape.backward(&backward_loss)?;
if let (Some(prediction), Some(target)) = (&step.prediction, batch.y.as_ref()) {
for metric in &mut self.metrics {
metric.observe_batch(prediction, target)?;
}
}
total_samples = total_samples
.checked_add(samples)
.ok_or_else(|| Error::resource_exhausted("accumulated samples overflow u64"))?;
if window > 1 {
let detached = detach(&backward_loss)?;
window_loss = Some(match window_loss {
None => detached,
Some(acc) => acc.add(&detached)?,
});
} else {
completion_loss = Some(step.loss.clone());
}
counts.extend(step.correct);
}
self.pending_step_samples = Some(total_samples);
let completion_loss = if window > 1 {
#[allow(clippy::cast_precision_loss)]
let inverse = Matrix::new_from_slice_on(self.runtime, vec![], &[1.0 / total_samples as f32])?;
for parameter in accumulation_parameters.as_deref().unwrap_or(&[]) {
if let Some(gradient) = parameter.gradient() {
parameter.set_gradient(detach(&gradient.mul(&inverse)?)?);
}
}
window_loss
.expect("a window runs at least one microbatch")
.mul(&inverse)?
} else {
completion_loss.expect("a window runs at least one microbatch")
};
self.complete_step(&completion_loss)?;
Ok(())
})();
if let Err(error) = result {
self.runtime.abort_pending_work();
return self.fail(error);
}
index = window_end;
}
let after = self.snapshot();
let batches = after.step_count() - before.step_count();
let samples = after.total_samples() - before.total_samples();
if batches > 0 {
let start = std::time::Instant::now();
let observation = (|| {
let mut metrics: Vec<_> = self
.metrics
.iter()
.map(|metric| (metric.name().to_owned(), metric.result()))
.collect();
if options.categorical_accuracy {
metrics.push((
"accuracy".to_owned(),
count_correct(&counts)? as f64 / samples as f64,
));
}
let expected_updates = (batches_per_epoch - first_index).div_ceil(window);
let validation = if batches == expected_updates {
options
.validation
.as_mut()
.map(|evaluate| evaluate())
.transpose()?
} else {
None
};
if let (Some(validation), Some((manager, model))) =
(validation, options.checkpoint.as_mut())
{
let optimizer = checkpoint_optimizer(&mut self.optimizer)?;
let run_state = crate::ml::RunState {
epoch: epoch + 1,
loader_cursor: 0,
scaler: None,
};
if manager.maybe_save_with_run_state(
*model,
optimizer,
after.step_count(),
validation.summary.loss,
false,
&run_state,
)? {
best_epoch = Some(epoch + 1);
}
}
Ok((metrics, validation))
})();
self.exclude_wall_time(start.elapsed());
let (metrics, validation) = match observation {
Ok(observation) => observation,
Err(error) => return self.fail(error),
};
history.push(TrainingEpoch {
epoch: epoch + 1,
batches,
samples,
loss: after.epoch_mean_loss(),
metrics,
validation,
});
}
if batches < (batches_per_epoch - first_index).div_ceil(window) || self.stop_requested() {
break;
}
}
if let (Some(best), Some((manager, model))) = (best_epoch, options.checkpoint)
&& history.last().is_some_and(|epoch| epoch.epoch != best)
{
let start = std::time::Instant::now();
let restore = checkpoint_optimizer(&mut self.optimizer)
.and_then(|optimizer| manager.load_best_into(model, optimizer));
self.exclude_wall_time(start.elapsed());
if let Err(error) = restore {
return self.fail(error);
}
}
Ok(TrainingHistory {
epochs: history,
snapshot: self.finish()?,
best_epoch,
})
}
pub fn evaluate(
model: &dyn Module,
loader: &mut DataLoader<'_>,
mut loss: impl FnMut(&Matrix, &Matrix) -> Result<Matrix>,
) -> Result<ValidationResult> {
Self::evaluate_supervised(model, loader, &mut loss, false).map(|report| report.summary)
}
pub fn evaluate_supervised(
model: &dyn Module,
loader: &mut DataLoader<'_>,
loss: impl FnMut(&Matrix, &Matrix) -> Result<Matrix>,
categorical_accuracy: bool,
) -> Result<EvaluationReport> {
let _mode = model.scoped_eval();
Self::evaluate_prediction_batches(loader, |x| model.forward(x), loss, categorical_accuracy)
}
pub fn evaluate_prediction_batches(
loader: &mut DataLoader<'_>,
forward: impl FnMut(&Matrix) -> Result<Matrix>,
loss: impl FnMut(&Matrix, &Matrix) -> Result<Matrix>,
categorical_accuracy: bool,
) -> Result<EvaluationReport> {
loader.reset()?;
Self::evaluate_predictions(
std::iter::from_fn(|| loader.next_batch().transpose()),
forward,
loss,
categorical_accuracy,
)
}
pub fn evaluate_predictions(
batches: impl IntoIterator<Item = Result<Batch>>,
mut forward: impl FnMut(&Matrix) -> Result<Matrix>,
mut loss: impl FnMut(&Matrix, &Matrix) -> Result<Matrix>,
categorical_accuracy: bool,
) -> Result<EvaluationReport> {
Self::evaluate_batches(
batches,
|batch| supervised_step(batch, &mut forward, &mut loss, categorical_accuracy),
categorical_accuracy,
)
}
pub fn evaluate_with(
batches: impl IntoIterator<Item = Result<Batch>>,
mut step: impl FnMut(&Batch) -> Result<Matrix>,
) -> Result<ValidationResult> {
Self::evaluate_batches(
batches,
|batch| {
Ok(ManagedStep {
loss: step(batch)?,
correct: None,
prediction: None,
})
},
false,
)
.map(|report| report.summary)
}
fn evaluate_batches(
batches: impl IntoIterator<Item = Result<Batch>>,
mut step: impl FnMut(&Batch) -> Result<ManagedStep>,
categorical_accuracy: bool,
) -> Result<EvaluationReport> {
without_active_tape()?;
let mut result = ValidationResult::new();
let mut weighted_loss = 0.0;
let mut counts = Vec::new();
for batch in batches {
let batch = batch?;
let count = batch_samples(&batch)?;
let step = step(&batch)?;
validate_loss(&batch, &step.loss)?;
weighted_loss += f64::from(metric::scalar_loss(&step.loss)?) * count as f64;
counts.extend(step.correct);
result.batches += 1;
result.samples = result
.samples
.checked_add(count)
.ok_or_else(|| Error::resource_exhausted("evaluation sample count overflows u64"))?;
}
if result.samples > 0 {
result.loss = weighted_loss / result.samples as f64;
}
let correct = if categorical_accuracy {
Some(count_correct(&counts)?)
} else {
None
};
Ok(EvaluationReport {
summary: result,
correct,
})
}
}
fn checkpoint_optimizer<'a>(
optimizer: &'a mut TrainingOptimizer<'_>,
) -> Result<&'a mut dyn crate::ml::CheckpointOptimizer> {
match optimizer {
TrainingOptimizer::AdamW(optimizer) => Ok(*optimizer),
TrainingOptimizer::Checkpointable(optimizer) => Ok(*optimizer),
TrainingOptimizer::Eager(_) => Err(Error::failed_precondition(
"fit requires a checkpointable optimizer when checkpointing is configured",
)),
}
}
fn count_correct(counts: &[Matrix]) -> Result<u64> {
let mut total = 0;
for group in counts.chunks(128) {
let values = crate::matrix::concat(group, 0)?.read::<u32>()?;
total += values.into_iter().map(u64::from).sum::<u64>();
}
Ok(total)
}
fn supervised_step(
batch: &Batch,
forward: impl FnOnce(&Matrix) -> Result<Matrix>,
loss: impl FnOnce(&Matrix, &Matrix) -> Result<Matrix>,
categorical_accuracy: bool,
) -> Result<ManagedStep> {
let target = batch
.y
.as_ref()
.ok_or_else(|| Error::invalid_argument("supervised training and evaluation require labels"))?;
let prediction = forward(&batch.x)?;
let loss = loss(&prediction, target)?;
let correct = if categorical_accuracy {
if target.shape().len() != 1 {
return Err(Error::invalid_argument(
"categorical accuracy requires one target per sample",
));
}
Some(prediction.categorical_accuracy_count(target)?)
} else {
None
};
Ok(ManagedStep {
loss,
correct,
prediction: Some(prediction),
})
}
fn batch_samples(batch: &Batch) -> Result<u64> {
let count = batch.x.shape().first().copied().unwrap_or(0);
if count == 0 {
return Err(Error::invalid_argument(
"a batch requires a nonempty leading sample axis",
));
}
if let Some(target) = &batch.y
&& (target.shape().first() != Some(&count) || !target.runtime().same_as(batch.x.runtime()))
{
return Err(Error::invalid_argument(
"batch targets must match input samples and Runtime",
));
}
Ok(count as u64)
}
fn validate_loss(batch: &Batch, loss: &Matrix) -> Result<()> {
if loss.dtype() != DType::F32 || !loss.shape().is_empty() {
return Err(Error::invalid_argument("batch loss must be an FP32 scalar"));
}
if !loss.runtime().same_as(batch.x.runtime()) {
return Err(Error::invalid_argument(
"batch loss and inputs must share a Runtime",
));
}
Ok(())
}
fn without_active_tape() -> Result<()> {
if recording_active() {
return Err(Error::failed_precondition(
"managed training and evaluation require no active GradientTape",
));
}
Ok(())
}