Skip to main content

Training

Struct Training 

Source
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<'_, '_>

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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>

Source

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.

Source

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.

Source

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.

Source

pub fn add_metric(&mut self, metric: &'hooks mut dyn TrainingMetric)

Source

pub fn add_callback(&mut self, callback: &'hooks mut dyn TrainingCallback)

Source

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.

Source

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.

Source

pub fn zero_grad(&self)

Source

pub fn request_stop(&mut self)

Source

pub const fn stop_requested(&self) -> bool

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

pub const fn training_program(&self) -> Option<&TrainingProgram>

Return the automatically owned program after its capture step.

Source

pub const fn program_capture_fallback_count(&self) -> u64

Return how many whole-program capture rejections continued eagerly.

Source

pub fn last_program_capture_fallback(&self) -> Option<&str>

Return the most recent whole-program capture rejection message.

Source

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.

Source

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.

Source

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.

Source

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.

Source

pub fn record_source_units(&mut self, units: u64)

Source

pub fn exclude_wall_time(&mut self, duration: Duration)

Exclude application work such as validation from wall-rate denominators.

Source

pub fn snapshot(&self) -> TrainingSnapshot

Source

pub fn gpu_timing_stats(&self) -> GpuTimingStats

Return aggregate device timing without submitting or synchronizing work.

Source

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.

Source

pub fn finish(self) -> Result<TrainingSnapshot>

Trait Implementations§

Source§

impl Drop for Training<'_, '_>

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more

Auto Trait Implementations§

§

impl<'runtime, 'hooks> !Freeze for Training<'runtime, 'hooks>

§

impl<'runtime, 'hooks> !RefUnwindSafe for Training<'runtime, 'hooks>

§

impl<'runtime, 'hooks> !Send for Training<'runtime, 'hooks>

§

impl<'runtime, 'hooks> !Sync for Training<'runtime, 'hooks>

§

impl<'runtime, 'hooks> !UnwindSafe for Training<'runtime, 'hooks>

§

impl<'runtime, 'hooks> Forget for Training<'runtime, 'hooks>

§

impl<'runtime, 'hooks> Move for Training<'runtime, 'hooks>

§

impl<'runtime, 'hooks> Unpin for Training<'runtime, 'hooks>
where &'runtime Runtime: Unpin, &'runtime mut AdamW: Unpin, &'runtime mut dyn Optimizer: Unpin, &'runtime mut dyn CheckpointOptimizer: Unpin, *const u8 is !null: Unpin, &'hooks mut dyn TrainingMetric: Unpin, &'hooks mut dyn TrainingCallback: Unpin, Arc<Shared>: Unpin, Box<dyn FnMut() -> Result<(), Error> + 'hooks>: Unpin, Box<dyn FnMut(&TrainingCommand) -> Result<(), Error> + 'hooks>: Unpin, Box<dyn Fn() -> TrainingValue + 'hooks>: Unpin, Box<dyn FnMut(&TrainingValue) -> Result<(), Error> + 'hooks>: Unpin, Rc<RefCell<RuntimeState>>: Unpin, &'static str: Unpin, Arc<BufferInner>: Unpin, Arc<DecodedPlaneCopy>: Unpin, Arc<RetainedDecode>: Unpin, Arc<EncodePlaneCopy>: Unpin, Arc<RetainedEncode>: Unpin, Rc<StorageInner>: Unpin, Arc<Device>: Unpin, Arc<RetirementCompletion>: Unpin, Arc<WorkerControl>: Unpin, Arc<TimestampPairInner>: Unpin, Arc<Mutex<Vec<Arc<DecodeStatus>>>>: Unpin, Arc<Mutex<Vec<Arc<EncodeReceipt>>>>: Unpin, Arc<ReusableCommandBufferInner>: Unpin, Rc<MatrixSemantic>: Unpin, Rc<()>: Unpin,

§

impl<'runtime, 'hooks> UnsafeUnpin for Training<'runtime, 'hooks>
where &'runtime Runtime: UnsafeUnpin, &'runtime mut AdamW: UnsafeUnpin, &'runtime mut dyn Optimizer: UnsafeUnpin, &'runtime mut dyn CheckpointOptimizer: UnsafeUnpin, *const u8 is !null: UnsafeUnpin, PhantomData<u64>: UnsafeUnpin, PhantomData<u8>: UnsafeUnpin, PhantomData<&'hooks mut dyn TrainingMetric>: UnsafeUnpin, PhantomData<&'hooks mut dyn TrainingCallback>: UnsafeUnpin, *const ArcInner<Shared> is !null: UnsafeUnpin, PhantomData<ArcInner<Shared>>: UnsafeUnpin, *const dyn FnMut() -> Result<(), Error> + 'hooks is !null: UnsafeUnpin, PhantomData<dyn FnMut() -> Result<(), Error> + 'hooks>: UnsafeUnpin, *const dyn FnMut(&TrainingCommand) -> Result<(), Error> + 'hooks is !null: UnsafeUnpin, PhantomData<dyn FnMut(&TrainingCommand) -> Result<(), Error> + 'hooks>: UnsafeUnpin, PhantomData<TrainingParameterDesc<'hooks>>: UnsafeUnpin, *const RcInner<RefCell<RuntimeState>> is !null: UnsafeUnpin, PhantomData<RcInner<RefCell<RuntimeState>>>: UnsafeUnpin, PhantomData<GraphNode>: UnsafeUnpin, PhantomData<Vec<BufferHazard>>: UnsafeUnpin, PhantomData<u32>: UnsafeUnpin, PhantomData<Storage>: UnsafeUnpin, PhantomData<SemanticValueDesc>: UnsafeUnpin, PhantomData<SemanticOpDesc>: UnsafeUnpin, PhantomData<SemanticAutogradDesc>: UnsafeUnpin, PhantomData<DnnValueDesc>: UnsafeUnpin, PhantomData<DnnOpDesc>: UnsafeUnpin, PhantomData<DnnPartition>: UnsafeUnpin, PhantomData<MatrixInputBinding>: UnsafeUnpin, PhantomData<ExecutionBindingDesc>: UnsafeUnpin, PhantomData<CapturedResourceDesc>: UnsafeUnpin, PhantomData<SemanticStorageBinding>: UnsafeUnpin, PhantomData<(Vec<u32>, Vec<ReusableCommandBuffer>)>: UnsafeUnpin, *const ArcInner<Device> is !null: UnsafeUnpin, PhantomData<ArcInner<Device>>: UnsafeUnpin, *const ArcInner<RetirementCompletion> is !null: UnsafeUnpin, PhantomData<ArcInner<RetirementCompletion>>: UnsafeUnpin, *const ArcInner<WorkerControl> is !null: UnsafeUnpin, PhantomData<ArcInner<WorkerControl>>: UnsafeUnpin, *const ArcInner<TimestampPairInner> is !null: UnsafeUnpin, PhantomData<ArcInner<TimestampPairInner>>: UnsafeUnpin, *const ArcInner<Mutex<Vec<Arc<DecodeStatus>>>> is !null: UnsafeUnpin, PhantomData<ArcInner<Mutex<Vec<Arc<DecodeStatus>>>>>: UnsafeUnpin, *const ArcInner<Mutex<Vec<Arc<EncodeReceipt>>>> is !null: UnsafeUnpin, PhantomData<ArcInner<Mutex<Vec<Arc<EncodeReceipt>>>>>: UnsafeUnpin, *const RcInner<StorageInner> is !null: UnsafeUnpin, PhantomData<RcInner<StorageInner>>: UnsafeUnpin, PhantomData<usize>: UnsafeUnpin, *const RcInner<MatrixSemantic> is !null: UnsafeUnpin, PhantomData<RcInner<MatrixSemantic>>: UnsafeUnpin, PhantomData<Rc<()>>: UnsafeUnpin, PhantomData<(u64, u64)>: UnsafeUnpin, PhantomData<Duration>: UnsafeUnpin, PhantomData<CommittedMetric>: UnsafeUnpin,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<S, T> Duplex<S> for T
where T: FromSample<S> + ToSample<S>,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<S> FromSample<S> for S

Source§

fn from_sample_(s: S) -> S

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<F, T> IntoSample<T> for F
where T: FromSample<F>,

Source§

fn into_sample(self) -> T

Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> ToSample<U> for T
where U: FromSample<T>,

Source§

fn to_sample_(self) -> U

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.