pub struct Training<'runtime, 'hooks> { /* private fields */ }Expand description
Exact eager or captured training-step lifecycle.
The loop borrows the runtime, optimizer, metrics, and callbacks. Call
Training::begin_step before authoring each body, then finish it with
Training::complete_step or Training::complete_program_step.
Training::finish is the explicit fallible terminal boundary.
Implementations§
Source§impl Training<'_, '_>
impl Training<'_, '_>
Sourcepub fn fit(
self,
model: &dyn Module,
loader: &mut DataLoader<'_>,
epochs: u64,
loss: impl FnMut(&Matrix, &Matrix) -> Result<Matrix>,
) -> Result<TrainingHistory>
pub fn fit( self, model: &dyn Module, loader: &mut DataLoader<'_>, epochs: u64, loss: impl FnMut(&Matrix, &Matrix) -> Result<Matrix>, ) -> Result<TrainingHistory>
Train a supervised model over a finite loader using a sample-mean loss.
The loader is reset for every epoch. This consumes the training run, sets the model to training mode, and fires the ordinary lifecycle hooks. For a caller-defined batch source or objective, use Self::fit_with.
§Errors
Returns schedule, loader, model, loss, optimizer, or callback errors.
Sourcepub fn fit_with_options(
self,
model: &dyn Module,
loader: &mut DataLoader<'_>,
epochs: u64,
loss: impl FnMut(&Matrix, &Matrix) -> Result<Matrix>,
options: TrainingFitOptions<'_, '_>,
) -> Result<TrainingHistory>
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>
Fit a supervised model with optional metrics, validation and checkpointing.
Validation runs after registered epoch hooks. Checkpoint selection uses validation loss and restores the best epoch at the end of the run.
§Errors
Returns errors from the supervised fit, validation, or checkpoint policy.
Sourcepub 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>
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>
Fit supervised batches supplied by a caller-defined source.
The source receives zero-based epoch and batch indices. The forward function uses training mode. Validation functions select their own mode.
§Errors
Returns errors from the supervised fit, validation, or checkpoint policy.
Sourcepub fn fit_supervised_batches_with_parameters(
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>,
parameters: &[Parameter],
options: TrainingFitOptions<'_, '_>,
) -> Result<TrainingHistory>
pub fn fit_supervised_batches_with_parameters( 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>, parameters: &[Parameter], options: TrainingFitOptions<'_, '_>, ) -> Result<TrainingHistory>
Fit supervised batches supplied by a caller-defined source with an explicit parameter set for gradient accumulation or dynamic loss scaling.
§Errors
Returns errors from the supervised fit, validation, precision scope, gradient scaling, or checkpoint policy.
Sourcepub fn fit_with(
self,
epochs: u64,
batches_per_epoch: u64,
batch_at: impl FnMut(u64, u64) -> Result<Batch>,
step: impl FnMut(&Batch) -> Result<Matrix>,
) -> Result<TrainingHistory>
pub fn fit_with( self, epochs: u64, batches_per_epoch: u64, batch_at: impl FnMut(u64, u64) -> Result<Batch>, step: impl FnMut(&Batch) -> Result<Matrix>, ) -> Result<TrainingHistory>
Train from a caller-defined batch source and a custom forward/loss step.
The batch source receives zero-based epoch and batch indices. The step
returns a scalar FP32 sample-mean loss. Training owns the tape, backward,
optimizer update, completion, and callbacks. Use step or manual
completion when the caller needs to own backward. The batch source and
objective run on the training Runtime’s thread.
§Errors
Requires a fresh run with no configured manual step schedule or active tape, and a nonempty finite schedule. Reports source, step, and callback failures through the training lifecycle.
Sourcepub fn evaluate(
model: &dyn Module,
loader: &mut DataLoader<'_>,
loss: impl FnMut(&Matrix, &Matrix) -> Result<Matrix>,
) -> Result<ValidationResult>
pub fn evaluate( model: &dyn Module, loader: &mut DataLoader<'_>, loss: impl FnMut(&Matrix, &Matrix) -> Result<Matrix>, ) -> Result<ValidationResult>
Evaluate a supervised model and return sample-weighted mean loss.
Resets the loader and restores the model’s prior modes, even on error. An empty split returns ValidationResult::default.
§Errors
Returns loader, model, loss, and observation errors. Evaluation requires no active gradient tape.
Sourcepub fn evaluate_supervised(
model: &dyn Module,
loader: &mut DataLoader<'_>,
loss: impl FnMut(&Matrix, &Matrix) -> Result<Matrix>,
categorical_accuracy: bool,
) -> Result<EvaluationReport>
pub fn evaluate_supervised( model: &dyn Module, loader: &mut DataLoader<'_>, loss: impl FnMut(&Matrix, &Matrix) -> Result<Matrix>, categorical_accuracy: bool, ) -> Result<EvaluationReport>
Evaluate a model with optional categorical accuracy.
Resets the loader and restores all prior module modes.
§Errors
Returns loader, model, loss, and metric errors.
Sourcepub 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>
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>
Evaluate a prediction function on a reset loader.
§Errors
Returns loader, model, loss, and metric errors.
Sourcepub fn evaluate_predictions(
batches: impl IntoIterator<Item = Result<Batch>>,
forward: impl FnMut(&Matrix) -> Result<Matrix>,
loss: impl FnMut(&Matrix, &Matrix) -> Result<Matrix>,
categorical_accuracy: bool,
) -> Result<EvaluationReport>
pub fn evaluate_predictions( batches: impl IntoIterator<Item = Result<Batch>>, forward: impl FnMut(&Matrix) -> Result<Matrix>, loss: impl FnMut(&Matrix, &Matrix) -> Result<Matrix>, categorical_accuracy: bool, ) -> Result<EvaluationReport>
Evaluate a supervised prediction function in caller-selected inference mode.
§Errors
Returns source, loss, prediction, and observation errors.
Sourcepub fn evaluate_with(
batches: impl IntoIterator<Item = Result<Batch>>,
step: impl FnMut(&Batch) -> Result<Matrix>,
) -> Result<ValidationResult>
pub fn evaluate_with( batches: impl IntoIterator<Item = Result<Batch>>, step: impl FnMut(&Batch) -> Result<Matrix>, ) -> Result<ValidationResult>
Evaluate a caller-defined objective on a stream of batches.
The caller selects inference mode for any model used in step. Losses
must be scalar FP32 batch means. Reading each scalar waits for its work.
§Errors
Returns source, step, validation, or observation errors.
Source§impl<'runtime, 'hooks> Training<'runtime, 'hooks>
impl<'runtime, 'hooks> Training<'runtime, 'hooks>
Sourcepub fn new(
runtime: &'runtime Runtime,
optimizer: &'runtime mut AdamW,
config: TrainingConfig,
) -> Result<Self>
pub fn new( runtime: &'runtime Runtime, optimizer: &'runtime mut AdamW, config: TrainingConfig, ) -> Result<Self>
Construct a training lifecycle around one runtime and optimizer.
§Errors
Returns an error when source-unit accounting is non-finite or overflows, or the variable epoch schedule overflows.
Sourcepub fn new_eager(
runtime: &'runtime Runtime,
optimizer: &'runtime mut dyn Optimizer,
config: TrainingConfig,
) -> Result<Self>
pub fn new_eager( runtime: &'runtime Runtime, optimizer: &'runtime mut dyn Optimizer, config: TrainingConfig, ) -> Result<Self>
Construct an eager-only training lifecycle around any optimizer.
This route provides the ordinary step, metric, and callback lifecycle.
Whole-program capture remains optimizer-specific and currently admits
AdamW through Training::new.
§Errors
Returns an error when the optimizer does not belong to runtime, source-unit
accounting is non-finite or overflows, or the epoch schedule overflows.
Sourcepub fn new_eager_checkpointable(
runtime: &'runtime Runtime,
optimizer: &'runtime mut dyn CheckpointOptimizer,
config: TrainingConfig,
) -> Result<Self>
pub fn new_eager_checkpointable( runtime: &'runtime Runtime, optimizer: &'runtime mut dyn CheckpointOptimizer, config: TrainingConfig, ) -> Result<Self>
Construct an eager lifecycle with native checkpoint capability.
Built-in checkpoint callbacks can borrow this optimizer through their
restricted callback context. Whole-program capture remains exclusive to
the AdamW Training::new route.
§Errors
Returns the same configuration or ownership errors as Training::new_eager.
pub fn add_metric(&mut self, metric: &'hooks mut dyn TrainingMetric)
pub fn add_callback(&mut self, callback: &'hooks mut dyn TrainingCallback)
Sourcepub fn attach_session(
&mut self,
session: &TrainingSession,
handlers: TrainingSessionHandlers<'hooks>,
) -> Result<()>
pub fn attach_session( &mut self, session: &TrainingSession, handlers: TrainingSessionHandlers<'hooks>, ) -> Result<()>
Attach one thread-safe live-control session before training starts.
Handler closures remain on this iterator’s runtime thread. Clones of
session contain only bounded commands and immutable observation data.
§Errors
Returns an error after training has started, while a step is pending, or when the session is already attached.
Sourcepub fn register_session_parameter(
&mut self,
desc: TrainingParameterDesc<'hooks>,
) -> Result<()>
pub fn register_session_parameter( &mut self, desc: TrainingParameterDesc<'hooks>, ) -> Result<()>
Register an application-owned parameter on the attached control session.
§Errors
Returns an error without an attached session, during a pending step, or for an invalid or duplicate descriptor.
pub fn zero_grad(&self)
pub fn request_stop(&mut self)
pub const fn stop_requested(&self) -> bool
Sourcepub fn begin_step(&mut self) -> Result<bool>
pub fn begin_step(&mut self) -> Result<bool>
Begin the next step, firing lazy train/epoch begin hooks.
Returns false after the configured budget or a callback stop decision.
§Errors
Returns a callback failure or counter exhaustion.
Sourcepub fn wait_begin_step(&mut self) -> Result<bool>
pub fn wait_begin_step(&mut self) -> Result<bool>
Block at the next safe point while an attached session is paused.
A session clone may enqueue resume or stop from another thread. Without an
attached session this is equivalent to Training::begin_step.
§Errors
Returns the same lifecycle or callback errors as Training::begin_step.
Sourcepub fn complete_step(&mut self, loss: &Matrix) -> Result<()>
pub fn complete_step(&mut self, loss: &Matrix) -> Result<()>
Complete one eagerly authored forward/backward step.
This records AdamW, submits the complete eager batch, waits for its exact event, reads the scalar loss, updates metrics, and fires end hooks.
§Errors
Returns an error for an unmatched begin, invalid loss, optimizer/runtime failure, timestamp failure, metric accounting overflow, or callback failure.
Sourcepub fn complete_step_scaled(
&mut self,
loss: &Matrix,
check: &Matrix,
scaler: &mut GradScaler,
) -> Result<bool>
pub fn complete_step_scaled( &mut self, loss: &Matrix, check: &Matrix, scaler: &mut GradScaler, ) -> Result<bool>
Complete one eagerly authored scaled-loss step under a GradScaler.
The caller runs forward and backward against scaler.scale_loss(&loss)
and unscales parameter gradients through
GradScaler::unscale_gradients, then hands the unscaled loss and the
scaler’s finite check to this method. The optimizer step applies only
when every unscaled gradient is finite; scaler.update() adjusts the
scale either way. Returns whether the optimizer step ran.
This is the eager AMP contract: the finite gate reads one scalar back
at the step boundary, where torch performs the equivalent CPU-side
check. The automatically captured step path instead replays the
device-resident gate produced by GradScaler::record_finite_gate
through Optimizer::set_finite_gate, freezing the update inside the
program when gradients are not finite.
§Errors
Returns an error for an unmatched begin, invalid loss, scaler or optimizer failure, timestamp failure, metric accounting overflow, or callback failure.
Sourcepub fn step<P>(
&mut self,
prepare: impl FnOnce() -> Result<P>,
record: impl FnOnce(P) -> Result<Matrix>,
) -> Result<bool>
pub fn step<P>( &mut self, prepare: impl FnOnce() -> Result<P>, record: impl FnOnce(P) -> Result<Matrix>, ) -> Result<bool>
Execute one automatically captured fixed-shape training step.
prepare runs on every admitted step and should allocate or refresh the
fixed-shape input batch. record runs for the eager warm-up and once more
to capture forward, backward, and AdamW work; later steps replay the owned
program without rebuilding that graph. The returned boolean is false
after the configured budget or a cooperative stop decision.
§Errors
Returns lifecycle, preparation, recording, capture, replay, completion, metric-accounting, timestamp, or callback errors. A whole-program compile rejection is an observable optimization fallback: the recorded source step runs eagerly and later steps remain eager until recapture is requested.
Sourcepub const fn training_program(&self) -> Option<&TrainingProgram>
pub const fn training_program(&self) -> Option<&TrainingProgram>
Return the automatically owned program after its capture step.
Sourcepub const fn program_capture_fallback_count(&self) -> u64
pub const fn program_capture_fallback_count(&self) -> u64
Return how many whole-program capture rejections continued eagerly.
Sourcepub fn last_program_capture_fallback(&self) -> Option<&str>
pub fn last_program_capture_fallback(&self) -> Option<&str>
Return the most recent whole-program capture rejection message.
Sourcepub fn capture_eligibility(&self) -> CaptureEligibility
pub fn capture_eligibility(&self) -> CaptureEligibility
Report whether whole-program capture is eligible, active, or ineligible for this training run, together with the restriction or fallback reason.
Sourcepub fn request_program_recapture(&mut self) -> Result<()>
pub fn request_program_recapture(&mut self) -> Result<()>
Discard the automatically captured program, or re-enable capture after a prior rejection, so the next step records a new fixed-shape program after preparation.
§Errors
Returns an error while a step body is pending or when this loop does not use
Training::step.
Sourcepub fn seal_replay_inputs(&mut self) -> Result<()>
pub fn seal_replay_inputs(&mut self) -> Result<()>
Seal allocations authored during preparation as stable replay inputs.
On eager steps after the first warm-up, Matrix storage allocated after
begin_step and before this call forms the externally retained input
prefix. Later allocations in the same step are classified as stable
capture-local temporaries with exact executable-graph lifetimes. Calling
this on the warm-up step is a no-op so one loop body can be used unchanged.
If this boundary is omitted, complete_step conservatively classifies every
allocation in the frame as external.
§Errors
Returns an error without a pending step or when the boundary is repeated.
Sourcepub fn complete_program_step(
&mut self,
program: &mut TrainingProgram,
) -> Result<()>
pub fn complete_program_step( &mut self, program: &mut TrainingProgram, ) -> Result<()>
Complete one replay of an already captured fixed-shape training program.
§Errors
Returns an unmatched-begin, replay, completion, accounting, or callback error.
pub fn record_source_units(&mut self, units: u64)
Sourcepub fn exclude_wall_time(&mut self, duration: Duration)
pub fn exclude_wall_time(&mut self, duration: Duration)
Exclude application work such as validation from wall-rate denominators.
pub fn snapshot(&self) -> TrainingSnapshot
Sourcepub fn gpu_timing_stats(&self) -> GpuTimingStats
pub fn gpu_timing_stats(&self) -> GpuTimingStats
Return aggregate device timing without submitting or synchronizing work.
Sourcepub fn committed_metrics(&self) -> &[CommittedMetric]
pub fn committed_metrics(&self) -> &[CommittedMetric]
Close the lifecycle and fire on_train_end exactly once.
§Errors
Returns an error when a begun body was not completed or a callback fails. Return every metric committed to the shared history, in commit order.
Training epoch metrics are committed by the lifecycle itself before epoch-end callbacks; validation, caller metrics, and callback-committed values follow in registration order at each boundary.