Skip to main content

GradScaler

Struct GradScaler 

Source
pub struct GradScaler { /* private fields */ }

Implementations§

Source§

impl GradScaler

Source

pub fn new() -> Self

Create a scaler with the PyTorch default configuration (init_scale=65536, growth 2.0, backoff 0.5, interval 2000).

Source

pub fn with_config( init_scale: f32, growth_factor: f32, backoff_factor: f32, growth_interval: u64, ) -> Result<Self>

Create a scaler with an explicit dynamic-scaling configuration.

§Errors

Returns an error when init_scale, growth_factor, or backoff_factor is not positive and finite, or growth_interval is zero.

Source

pub fn scale(&self) -> f32

Return the current scale.

Source

pub fn capture_state(&self) -> Result<GradScalerState>

Capture the resume-relevant scaler state.

In host mode this reads the struct fields; after prepare_captured the device owns scale bookkeeping, so capture reads the device scale and counter back (one scalar synchronization each — checkpoints are infrequent). found_inf is transient within a step and deliberately absent: a checkpoint commits at completed updates.

§Errors

Returns an error when device readback fails.

Source

pub fn restore_state(&mut self, state: GradScalerState) -> Result<()>

Restore scaler state captured by GradScaler::capture_state.

Host fields always update; when device state exists the scale and counter upload into the live device matrices rather than replacing them, because the optimizer’s finite-gate binding references those exact buffers.

§Errors

Returns an error when the scale is not positive and finite or the device upload fails.

Source

pub fn prepare_captured(&mut self, runtime: &Runtime) -> Result<()>

Allocate device-resident scaler state on runtime for captured replay.

After this call, scale_loss, unscale_gradients, and record_finite_gate all reference the device buffers instead of the host scale, so a captured program replays scale adaptation and the optimizer gate without a mid-step host decision. Bind GradScaler::finite_flag to the optimizer once through Optimizer::set_finite_gate.

§Errors

Returns an error when buffer allocation or upload fails.

Source

pub fn finite_flag(&self) -> Result<Matrix>

Return the device-resident finite flag for optimizer binding.

The flag is a single-element F32 matrix written by GradScaler::record_finite_gate; bind it once with Optimizer::set_finite_gate before the first captured step.

§Errors

Returns an error when prepare_captured has not run.

Source

pub fn record_finite_gate(&mut self, check: &Matrix) -> Result<()>

Record the device-side finite gate update for the current step.

Dispatches MlGradScalerAdvanceF32: check decides the flag (finite iff every unscaled gradient element is finite), the scale backs off on overflow or grows after growth_interval finite steps, and the growth counter advances — all in device buffers, so the record replays the full dynamic-scaling contract inside a captured training program. Must follow unscale_gradients in record order.

§Errors

Returns an error when prepare_captured has not run, check is not a same-runtime single-element F32 matrix, or recording fails.

Source

pub fn scale_loss(&self, loss: &Matrix) -> Result<Matrix>

Multiply loss by the current scale as a recorded device operation.

Under prepare_captured the multiplier is the device scale buffer, so replayed steps apply the scale the device-side advance produced for that step rather than the value baked at capture time.

§Errors

Returns an error when runtime recording fails.

Source

pub fn unscale_gradients(&self, parameters: &[Parameter]) -> Result<Matrix>

Divide every nonempty parameter gradient by the scale in place and return a [1] accumulator that is finite iff every unscaled gradient element is finite.

The unscale and the check are device-resident: each gradient is rescaled into detached replacement storage and its full sum is folded into the accumulator, so NaN or Inf propagates into the check value.

§Errors

Returns an error when runtime recording or allocation fails.

Source

pub fn step_optimizer( &mut self, optimizer: &mut dyn Optimizer, check: &Matrix, ) -> Result<bool>

Apply optimizer.step() when check is finite; skip the update and flag the scale for backoff when it is not.

This is the one host boundary of the scaler contract: the check value is read back once per step, matching the CPU-side gate in torch.

§Errors

Returns an error when the check matrix is empty, readback fails, or optimizer.step() fails.

Source

pub fn update(&mut self)

Adjust the scale after step_optimizer: halve it on a skipped step, otherwise double it after growth_interval consecutive finite steps.

This is the eager-path companion. Under prepare_captured the device-side advance owns scale bookkeeping during replay and this is a no-op; device_scale reads the current value back when needed.

Source

pub fn device_scale(&self) -> Result<f32>

Read the current device-resident scale back to the host.

Costs one scalar synchronization; intended for diagnostics and logging, not per-step control flow.

§Errors

Returns an error when prepare_captured has not run or the readback fails.

Trait Implementations§

Source§

impl Clone for GradScaler

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Default for GradScaler

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl !RefUnwindSafe for GradScaler

§

impl !Send for GradScaler

§

impl !Sync for GradScaler

§

impl !UnwindSafe for GradScaler

§

impl Forget for GradScaler

§

impl Freeze for GradScaler
where *const RcInner<RefCell<RuntimeState>> is !null: Freeze, PhantomData<RcInner<RefCell<RuntimeState>>>: Freeze, *const RcInner<StorageInner> is !null: Freeze, PhantomData<RcInner<StorageInner>>: Freeze, *const u8 is !null: Freeze, PhantomData<usize>: Freeze, *const RcInner<MatrixSemantic> is !null: Freeze, PhantomData<RcInner<MatrixSemantic>>: Freeze, PhantomData<Rc<()>>: Freeze,

§

impl Move for GradScaler

§

impl Unpin for GradScaler
where Rc<RefCell<RuntimeState>>: Unpin, Rc<StorageInner>: Unpin, *const u8 is !null: Unpin, Rc<MatrixSemantic>: Unpin, Rc<()>: Unpin,

§

impl UnsafeUnpin for GradScaler
where *const RcInner<RefCell<RuntimeState>> is !null: UnsafeUnpin, PhantomData<RcInner<RefCell<RuntimeState>>>: UnsafeUnpin, *const RcInner<StorageInner> is !null: UnsafeUnpin, PhantomData<RcInner<StorageInner>>: UnsafeUnpin, *const u8 is !null: UnsafeUnpin, PhantomData<usize>: UnsafeUnpin, *const RcInner<MatrixSemantic> is !null: UnsafeUnpin, PhantomData<RcInner<MatrixSemantic>>: UnsafeUnpin, PhantomData<Rc<()>>: 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<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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.