Skip to content
class

Optimizer

Optimizer

Abstract base class owning trainable parameters and the training step.

Optimizer keeps a flat list of TensorImpl parameters and runs one update per training iteration. Derived classes inject their specific update mathematics via update_one and lazily allocate per-parameter state (momentum buffers, moment estimates, parameter averages, ...) via init_state_slot. The base class handles the cross-cutting bookkeeping: skipping parameters without gradients, allocating state exactly once per slot, and bumping each parameter's version counter so autograd notices the in-place mutation.

State storage layout

Per-parameter state is keyed by an integer slot_idx that equals the position of the parameter in params_. Derived classes hold one std::vector<Storage> (or several) parallel to params_; entry i is allocated on the first call to update_one for slot i. The parallel state_initialized_ vector tracks allocation so state is allocated exactly once.

Step contract

step() is called by the Python wrapper once per training iteration, after the backward pass has populated param->grad_storage(). It performs three actions per slot:

  1. Skip the slot if the parameter pointer is null or its gradient is absent (matching the reference framework's "no grad = no update" convention).
  2. Lazily allocate state via init_state_slot if this is the slot's first observed gradient.
  3. Advance the slot's step counter steps_[i], apply the update via update_one and bump the parameter's version counter via TensorImpl::bump_version so any autograd node that captured the parameter before the update sees the change.

Step counters

Each slot counts its own updates, as the reference framework keeps state["step"] per parameter. A slot skipped for want of a gradient does not advance, so a parameter unfrozen part-way through training starts its bias correction at step 1, and a frozen first parameter cannot hold every other slot at step 0. update_one reads steps_[slot_idx], already advanced for the current update.

zero_grad() clears every parameter's gradient storage so the next backward pass starts from a fresh zero buffer.

Copy semantics

Copy is deleted because optimizer state owns raw heap buffers (CPU) and MLX arrays (GPU) whose semantics under shallow copy would be ambiguous. Optimizers are owned by the Python wrapper through a std::shared_ptr and accessed via pybind11 reference bindings.

Serialisation

state_dict_id() returns a short version-tagged identifier (e.g. "sgd_v1") baked into checkpoints so the Python loader can refuse mismatched versions. state_buffers() / load_state_buffers() expose the per-parameter mutable state as named TensorImpl lists for lucid.save-style checkpointing — entries are clones, so the caller is free to keep them after the optimizer is destroyed.

Subclass responsibilities

Concrete optimizers must override update_one, init_state_slot, set_lr / lr, and state_dict_id. Optimizers with Python-visible per-parameter state override state_slots to return a declarative list of StateSlot descriptors; the base class state_buffers and load_state_buffers use that table to snapshot and atomically restore state (validating every slot and parameter before mutating any live buffer).

See Also

SGD, ASGD : plain and averaged stochastic gradient descent. Adam, AdamW, NAdam, RAdam, Adamax, Adafactor : adaptive moment family. Adagrad, Adadelta, RMSProp : adaptive learning-rate family.

Attributes

params_std::vector<std::shared_ptr<TensorImpl>>
Flat list of trainable parameters. Indexed by slot_idx in the protected hooks. May contain null entries; nulls are silently skipped by step().
state_initialized_std::vector<bool>
Parallel to params_. Marks whether init_state_slot has run for each slot; grown lazily by step() to match params_.size() on first use.
steps_std::vector<std::int64_t>
Parallel to params_. Number of updates each slot has received; see Step counters.

Constructors

1
ctor

Optimizer

void Optimizer(int)

Construct an optimizer from a flat list of trainable parameters.

Parameters

paramsstd::vector<std::shared_ptr<TensorImpl>>
Parameters to optimise. May be empty (a no-op optimizer) and may contain null entries (silently skipped by step). The caller's vector is moved into the optimizer; subsequent mutations of the caller's copy do not affect this optimizer.

Notes

state_initialized_ is sized lazily on the first step() rather than here, which lets the Python wrapper extend params_ post-construction in the rare param-group reconfiguration case.

Destructor

1
dtor

~Optimizer

void ~Optimizer()

Virtual destructor — ensures derived Adam / SGD / RMSProp destructors run when held by a base-class pointer. Defaulted; the per-parameter state buffers are released by their own std::vector members in the derived classes, and params_ releases its shared_ptr refs automatically.

Operators

1
op

operator=

Optimizer & operator=(const Optimizer &)

Virtual methods

5
= 0

init_state_slot

void init_state_slot(int slot_idx, const int & param)

Allocate and zero-initialise per-parameter state for one slot.

Parameters

slot_idxstd::size_t
Position in params_ whose state should be materialised.
paramconst std::shared_ptr<TensorImpl>&
The parameter occupying that slot; provides the shape, dtype, and device for the state buffer(s).

Notes

Called exactly once per slot — on the first step() for which that slot has a gradient. Implementations should size their std::vector<Storage> state members lazily here rather than in the constructor so that disabled features (e.g. momentum == 0 in SGD) skip the allocation entirely.

= 0const

lr

→double
double lr()

Current learning rate.

Returns

double

The value last passed to set_lr (or the constructor).

= 0

set_lr

void set_lr(double lr)

Set the learning rate (called by LR schedulers between steps).

Parameters

lrdouble
New learning rate. Must be non-negative.
virt

set_step_count

void set_step_count(int count)

Give every slot that holds state the same step count.

The fallback for a checkpoint loader that carries one counter per parameter group rather than one per parameter: run it after load_state_buffers, which allocates the slots the checkpoint holds state for. Slots without state stay at 0. A loader that passes the per-slot "step" entry to load_state_buffers must not call this afterwards — it would overwrite those counts.

Parameters

countstd::int64_t
Step count to give every slot that holds state.
= 0

update_one

void update_one(int slot_idx, int & param, const int & grad)

Apply the optimizer's update rule for a single parameter.

Parameters

slot_idxstd::size_t
Stable index of the parameter in params_. Used to look up the pre-allocated state buffers (momentum, second moment, parameter average, ...).
paramstd::shared_ptr<TensorImpl>&
Parameter tensor to update in place. Guaranteed non-null and guaranteed to have an accumulated gradient.
gradconst Storage&
The parameter's gradient storage for the current step.

Notes

Implementations must mutate param's storage in place — the base step() is responsible for bumping the version counter after this returns. Both CPU and GPU paths are typically dispatched from inside this method based on param->device().

Methods

18
fn

ensure_buffers

void ensure_buffers(int & bufs)

Give each slot that holds state a zero buffer in bufs if it has none.

A hyper-parameter edit can switch on a feature whose buffer the slots were initialised without, such as AMSGrad's running maximum or RMSprop's grad_avg. Each such slot then starts from zero, as it would in a fresh optimizer built with the feature on and given the same state. A buffer the slot already holds is kept, so switching a feature off and on again resumes it.

Parameters

bufsstd::vector<Storage>&
A state vector parallel to params_; grown to its length.
fn

ensure_state_slot

void ensure_state_slot(int i)

Allocate slot i's state the way step() would, if it has none.

Called by the load_* helpers before they overwrite a slot, so a checkpoint can be restored into an optimizer that has never stepped. A null parameter is left alone.

fn

load_scalar_slots

void load_scalar_slots(int & scalars, const int)

Restore one per-slot scalar vector from 0-d tensors.

fn

load_state_buffers

void load_state_buffers(const int & bufs)

Restore the per-parameter state in place from a snapshot.

See Also

state_buffers : the inverse operation.

Parameters

bufsconst std::vector<NamedBuffers>&
Must match the layout returned by state_buffers for this optimizer: recognized buffer names must have per-slot shapes, dtypes, and devices matching params_. Unknown buffer names are ignored.

Raises

:runtime_error
If any saved tensor's shape, dtype, device, or scalar element count does not match the live parameter slot.

Notes

Restoration is two-phase (validate then commit): every recognized slot and every parameter entry in bufs is validated before any state slot is initialised or any live buffer / scalar is mutated. If validation fails, the optimizer's existing state is left unchanged.

fn

load_state_slots

void load_state_slots(int & bufs, const int)

Restore one per-slot state vector from a state_buffers snapshot.

Parameters

bufsstd::vector<Storage>&
The live state vector to overwrite in place. A slot that holds no buffer in it yet is given one first.
savedconst std::vector<std::shared_ptr<TensorImpl>>&
Saved tensors parallel to params_; null entries are skipped.

Raises

:runtime_error
If a saved tensor's shape or dtype differs from its parameter's, or it is on the other device.
fn

load_step_slots

void load_step_slots(const int)

Restore the per-slot step counters from a "step" entry.

fnconst

num_params

→std::size_t
int num_params()

Number of parameter slots managed by this optimizer.

Returns

std::size_t

params_.size() — includes null entries.

fnconst

refuse_phantom_step

void refuse_phantom_step()

Refuse a step under phantom mode, or of a phantom parameter or gradient, before any state moves (see Optimizer.cpp).

fnconst

slot_has_state

bool slot_has_state(int i)

Whether slot i holds state (it has received at least one gradient, or a checkpoint restored it).

fnconst

state_buffers

→std::vector<NamedBuffers>
int state_buffers()

Snapshot the per-parameter mutable state for checkpointing.

See Also

load_state_buffers : the inverse operation.

Returns

std::vector<NamedBuffers>

A list of (name, tensors) pairs driven by state_slots(). name identifies the buffer kind (e.g. "momentum_buffer"); tensors runs parallel to params_ with one entry per parameter slot (or a null entry if no state was allocated for that slot). Entries are clones — callers may keep them after the optimizer is destroyed. Optimizers with no Python-visible state return an empty vector.

fnconst

state_dict_id

→std::string
int state_dict_id()

Short version-tagged identifier baked into checkpoints.

Returns

std::string

A stable short tag like "sgd_v1" or "adam_v1" used by the Python loader to detect mismatched optimizer versions in load_state_dict.

fn

state_slots

int state_slots()

Declarative table of per-parameter state entries for checkpointing.

fn

step

void step()

Run one optimizer update over all registered parameters.

For each non-null parameter that has an accumulated gradient, step() lazily initialises its state slot, invokes the derived class's update_one to apply the update rule, then bumps the parameter's autograd version counter. Parameters without a gradient are skipped — this matches the reference framework's "no grad = no update" semantics and lets a single optimizer safely cover partially active sub-modules (e.g. frozen layers).

Notes

Called once per training iteration, after loss.backward(). The accompanying Python wrapper takes care of forcing the resulting MLX graph to eval() only when requested via AUTO_EVAL_AFTER_STEP; by default step() is itself lazy so that forward → backward → step can fuse into one MLX submission.

fnconst

step_count

→std::int64_t
int step_count()

Global step counter — always 0, since steps are counted per slot.

Returns

std::int64_t

0. The per-slot counters (see Step counters) travel through state_buffers as the "step" entry instead, so a checkpoint keeps each parameter's own count, as the reference framework's does.

Notes

Keep this 0: the Python checkpoint writer (Optimizer._save_engine_state) stamps a non-zero step_count over every parameter's "step" entry.

fn

sync_slot_vectors

void sync_slot_vectors()

Size state_initialized_ and steps_ to params_.

fnconst

validate_scalar_slots

void validate_scalar_slots(const int)

Validate all non-null scalar entries in saved without mutating any state slot.

fnconst

validate_state_slots

void validate_state_slots(const int)

Validate all non-null entries in saved against params_ without mutating any state slot.

fn

zero_grad

void zero_grad()

Zero every parameter's gradient storage.

Calls TensorImpl::zero_grad on each non-null parameter. Should be called before each forward/backward pass so that the next backward accumulates into a clean buffer rather than into the previous step's gradient.