Skip to main content

OptimizerState

Struct OptimizerState 

Source
pub struct OptimizerState {
    pub step: usize,
    pub momentum: HashMap<String, Vec<f32>>,
    pub variance: HashMap<String, Vec<f32>>,
    pub third_moment: HashMap<String, Vec<f32>>,
    pub param_steps: HashMap<String, usize>,
    pub velocity: HashMap<String, Vec<f32>>,
    pub params: ParamRegistry,
}
Expand description

Unified state management for optimizer parameters.

This struct provides a consistent interface for tracking optimizer state across different algorithms, reducing code duplication and memory overhead.

Fields§

§step: usize

Current step counter for bias correction and scheduling

§momentum: HashMap<String, Vec<f32>>

First moment estimates (momentum buffers)

§variance: HashMap<String, Vec<f32>>

Second moment estimates (squared gradient buffers)

§third_moment: HashMap<String, Vec<f32>>

Optional third moment estimates (for higher-order methods)

§param_steps: HashMap<String, usize>

Per-parameter step counts (for adaptive methods)

§velocity: HashMap<String, Vec<f32>>

Velocity buffers for optimization methods like SGD with momentum

§params: ParamRegistry

Stable parameter identity registry.

Every buffer map above is keyed by the canonical keys handed out by this registry. It is deliberately not serialised: identity is reconstructed on load from the checkpointed keys themselves (see crate::param_id), which keeps the on-disk state format unchanged.

Implementations§

Source§

impl OptimizerState

Source

pub fn new() -> Self

Creates a new optimizer state with empty buffers.

Source

pub fn param_key_for_tensor(&mut self, tensor: &Tensor) -> Result<String>

Resolves the stable state key for an anonymous parameter tensor.

This is the supported replacement for the old format!("{:p}", …) idiom: the returned key survives checkpoint save/load, whereas a heap address does not.

§Errors

Returns an error when the tensor dtype has no addressable buffer, or when the parameter ordering does not match a restored checkpoint.

Source

pub fn param_key(&mut self, addr: usize, numel: usize) -> Result<String>

Resolves the stable state key for an anonymous parameter given its buffer address and element count.

§Errors

See OptimizerState::param_key_for_tensor.

Source

pub fn param_key_named( &mut self, name: &str, addr: usize, numel: usize, ) -> String

Resolves the stable state key for a parameter that has a caller-supplied name.

Named keys make checkpoint resume independent of parameter visit order and should be preferred wherever the surrounding API carries names.

Source

pub fn restore_param_key(&mut self, key: &str, numel: usize) -> Result<ParamId>

Rebuilds one registry slot from a checkpointed state key.

§Errors

Returns an error when key carries no recognised identity prefix.

Source

pub fn get_or_create_momentum( &mut self, param_id: String, size: usize, ) -> &mut Vec<f32>

Gets or creates momentum buffer for a parameter.

Source

pub fn get_or_create_variance( &mut self, param_id: String, size: usize, ) -> &mut Vec<f32>

Gets or creates variance buffer for a parameter.

Source

pub fn get_or_create_third_moment( &mut self, param_id: String, size: usize, ) -> &mut Vec<f32>

Gets or creates third moment buffer for a parameter.

Source

pub fn step(&mut self)

Increments the global step counter.

Source

pub fn step_param(&mut self, param_id: String)

Increments the step counter for a specific parameter.

Source

pub fn get_param_step(&self, param_id: &str) -> usize

Gets the step count for a specific parameter.

Source

pub fn clear(&mut self)

Clears all state buffers to free memory.

The parameter identity registry is cleared alongside the buffers: leaving registrations behind while dropping their state would keep params.len() reporting parameters whose buffers no longer exist, and would leave the registry’s bind cursor advanced past slots that are ready to be reused.

Source

pub fn memory_usage(&self) -> StateMemoryStats

Gets memory usage statistics.

Trait Implementations§

Source§

impl Clone for OptimizerState

Source§

fn clone(&self) -> OptimizerState

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 Debug for OptimizerState

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for OptimizerState

Source§

fn default() -> Self

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

impl<'de> Deserialize<'de> for OptimizerState

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Serialize for OptimizerState

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

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<T> ConfigSerializable for T
where T: Serialize + for<'de> Deserialize<'de>,

Source§

fn to_json(&self) -> Result<String, TrustformersError>

Serialize to JSON string
Source§

fn from_json(json: &str) -> Result<T, TrustformersError>

Deserialize from JSON string
Source§

fn save_to_file(&self, path: &Path) -> Result<(), TrustformersError>

Save to file
Source§

fn load_from_file(path: &Path) -> Result<Self, TrustformersError>
where Self: Sized,

Load from file
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
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> 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, <T as TryFrom<U>>::Error>

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.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more