Skip to content
class

SGD

extendsOptimizer
SGD

Stochastic gradient descent with optional momentum, Nesterov acceleration, and L2 weight decay.

Plain SGD takes the parameter θ\theta down the negative gradient direction at fixed learning rate η\eta:

θt+1=θt−η gt. \theta_{t+1} = \theta_t - \eta\, g_t.

With momentum coefficient μ>0\mu > 0, a per-parameter velocity buffer vv accumulates a low-pass-filtered gradient (Polyak's heavy ball):

vt+1=μ vt+(1−τ) gt,θt+1=θt−η vt+1, v_{t+1} = \mu\, v_t + (1 - \tau)\, g_t, \qquad \theta_{t+1} = \theta_t - \eta\, v_{t+1},

where the dampening coefficient τ\tau scales the current gradient when accumulating into vv. dampening = 0 recovers classical Polyak momentum.

With Nesterov acceleration (Sutskever et al. 2013 reformulation), the lookahead form is used:

vt+1=μ vt+gt,θt+1=θt−η (μ vt+1+gt), v_{t+1} = \mu\, v_t + g_t, \qquad \theta_{t+1} = \theta_t - \eta\, (\mu\, v_{t+1} + g_t),

which requires dampening = 0 and momentum > 0.

L2 weight decay with coefficient λ\lambda is applied to the gradient before the momentum update (coupled weight decay, as in the reference framework):

gt←gt+λ θt. g_t \leftarrow g_t + \lambda\, \theta_t.

This is the standard L2 regularisation form; AdamW-style decoupled weight decay is not used here — use AdamW for that variant.

Math

Full update (momentum branch, no Nesterov):

gt←gt+λ θt,vt+1=μ vt+(1−τ) gt,θt+1=θt−η vt+1. g_t \leftarrow g_t + \lambda\, \theta_t, \qquad v_{t+1} = \mu\, v_t + (1 - \tau)\, g_t, \qquad \theta_{t+1} = \theta_t - \eta\, v_{t+1}.

Plain SGD is the μ=0\mu = 0 special case where the velocity buffer is never allocated. A parameter's first momentum step starts the buffer at its gradient, undamped, as the reference framework does:

v1=g1. v_1 = g_1.

The same holds when momentum is switched on part-way through training.

References

Polyak, "Some methods of speeding up the convergence of iteration methods" (1964). Sutskever, Martens, Dahl, Hinton, "On the importance of initialization and momentum in deep learning" (ICML 2013).

See Also

ASGD : averaged SGD with running parameter mean. Adam, AdamW : adaptive moment optimisers.

Attributes

lr_double
Learning rate η\eta. Must be non-negative. Updated by schedulers via set_lr.
momentum_double
Momentum coefficient μ\mu. Zero disables momentum and skips velocity-buffer allocation.
dampening_double
Dampening coefficient τ\tau. Must be zero when nesterov_ is true.
weight_decay_double
L2 penalty coefficient λ\lambda.
nesterov_bool
Enables the Nesterov lookahead form. Requires momentum_ > 0 and dampening_ == 0.
moment_std::vector<Storage>
Per-parameter velocity buffers. Entry ii is allocated by init_state_slot on the first step seen by slot ii only when momentum_ != 0; otherwise it remains empty.

Notes

CPU and GPU update paths are dispatched inside update_one based on the parameter's device. The CPU path is a flat scalar loop over the raw byte buffer; the GPU path expresses the update as a few MLX array ops, which compose with the surrounding lazy graph.

Examples

Typical training-loop usage from Python:
>>> opt = lucid.optim.SGD(model.parameters(), lr=0.01,
...                       momentum=0.9, weight_decay=1e-4)
>>> opt.zero_grad()
>>> loss.backward()
>>> opt.step()

Constructors

1
ctor

SGD

void SGD(int)

Construct an SGD optimizer with optional momentum and Nesterov.

Parameters

paramsstd::vector<std::shared_ptr<TensorImpl>>
Parameters to optimise. Forwarded to Optimizer.
lrdouble
Learning rate η\eta. Must be non-negative.
momentumdouble= None
Momentum coefficient μ\mu (default 0.0). Zero disables momentum.
dampeningdouble= None
Dampening coefficient τ\tau on the current gradient when accumulating into the velocity buffer (default 0.0). Must be 0 when nesterov is true.
weight_decaydouble= None
L2 regularisation coefficient λ\lambda (default 0.0).
nesterovbool= None
If true, use the Nesterov lookahead form (default false). Requires momentum > 0 and dampening == 0.

Raises

:runtime_error
If nesterov is requested without positive momentum, or with a non-zero dampening.

Static methods

1
static

check_hyperparams

void check_hyperparams(double lr, double momentum, double dampening, double weight_decay, bool nesterov)

Check SGD's hyper-parameters against its rules.

The single statement of the rules: the constructor and set_hyperparams both run it, and the Python wrapper runs it on every parameter group it is given. They are the reference framework's constructor checks.

Raises

InvalidArgument
If lr, momentum or weight_decay is negative, or nesterov is set without positive momentum and zero dampening.

Virtual methods

2
virtconst

lr

double lr()

Current learning rate η\eta.

virt

set_lr

void set_lr(double lr)

Update the learning rate from a scheduler.

Parameters

lrdouble
New learning rate.

Methods

7
fn

init_state_slot

void init_state_slot(int slot_idx, const int & param)

Make room for one slot's velocity buffer without allocating it.

Parameters

slot_idxstd::size_t
Index into params_ and moment_.
paramconst std::shared_ptr<TensorImpl>&
Parameter occupying the slot (unused).

Notes

The buffer is made by the slot's first momentum step, from that step's gradient, so plain SGD allocates no extra memory.

fnconst

momentum

double momentum()

Current momentum coefficient μ\mu.

fn

set_hyperparams

void set_hyperparams(double lr, double momentum, double dampening, double weight_decay, bool nesterov)

Replace the hyper-parameters between steps.

The whole set is checked by check_hyperparams before any of it is applied, so a rejected call changes nothing. Momentum switched on mid-run starts each parameter's buffer at its next gradient, as the first momentum step always does (see update_one).

fnconst

state_dict_id

int state_dict_id()

Checkpoint identifier ("sgd_v1").

fn

update_one

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

Apply the SGD update for one parameter slot.

Dispatches to either the CPU scalar loop or the MLX GPU path based on the parameter's device. Implements the plain-SGD, momentum, Nesterov, and weight-decay branches according to the constructor flags. See the class-level math block for the precise update rule.

Parameters

slot_idxstd::size_t
Index into params_ and moment_.
paramstd::shared_ptr<TensorImpl>&
Parameter to update in place.
gradconst Storage&
Accumulated gradient for this step.
fnconst

weight_decay

double weight_decay()

Current L2 weight-decay coefficient λ\lambda.