Skip to content

3.3 Optimizers

ready≈ 11.5 hoursNeeds: 3.2, 1.6Unlocks: 3.5, 4.3
  1. 1 Learn
  2. 2 Bridge & derive
  3. 3 Explore (Optimizer race, LR schedule viewer)
  4. 4 Do
  5. 5 Check

SGD’s noise is a feature and a cost. A mini-batch gradient is an unbiased but noisy estimate of the full gradient. The noise lets SGD wander out of poor regions and costs almost nothing per step, but with a fixed step size the loss stalls at a noise floor whose height grows with the step (UDL §6.2). Shrinking the step later lowers the floor. That is the first reason for schedules.

Momentum keeps a running velocity v←βv+g\mathbf{v} \leftarrow \beta\mathbf{v} + \mathbf{g} and steps along it. In a ravine, the steep components flip sign each step and cancel, while the gentle slope along the valley floor adds up, so progress along the valley speeds up by up to 1/(1−β)1/(1-\beta). UDL writes m←βm+(1−β)g\mathbf{m} \leftarrow \beta\mathbf{m} + (1-\beta)\mathbf{g} instead: the same method with the learning rate scaled by 1−β1-\beta. Nesterov momentum evaluates the correction one step ahead; the formula in the task is PyTorch’s rearrangement of that look-ahead (UDL §6.3; Goh 2017).

Adam keeps two running averages: m\mathbf{m} of the gradient and v\mathbf{v} of its square. It divides each coordinate’s step by v\sqrt{v} (doing only that, with no m\mathbf{m}, is RMSProp), so every parameter moves at a similar pace whatever its gradient’s scale, and the first step is about η\eta in every coordinate. Both averages start at zero, which biases them towards zero early on, and the bias correction below removes that (Kingma and Ba 2015; UDL §6.4).

AdamW fixes weight decay. Adding λw\lambda\mathbf{w} to the gradient sends it through Adam’s per-coordinate scaling, so weights with large gradients are barely regularised. Decoupled decay shrinks the weights directly, w←w−ηλw\mathbf{w} \leftarrow \mathbf{w} - \eta\lambda\mathbf{w}, outside m\mathbf{m} and v\mathbf{v} (Loshchilov and Hutter 2019). Most modern transformers are trained with AdamW, linear warmup and cosine decay (Loshchilov and Hutter 2017; Goyal et al. 2017).

Adam’s bias correction: E[m̂ₜ] = E[g] for stationary gradientsstep 1 of 5
  1. m0=0,mt=β1mt−1+(1−β1) gtm_0 = 0,\qquad m_t = \beta_1 m_{t-1} + (1-\beta_1)\,g_t

Optimizer race

SGD vs momentum vs RMSProp vs Adam

Static view on small screens. Open this page on a laptop to interact.

1e21e01e-21e-41e-61e-8step → (loss − minimum, log)
SGD: 0.26440momentum: 0.07822RMSProp: 0.00000Adam: 0.13286

Click the plot to move the start. SGD's step is lr × gradient, so on the ravine it must stay below 2/25 or the steep direction blows up, and then the shallow direction crawls. Momentum builds speed along the valley floor. RMSProp and Adam divide each coordinate by its own recent gradient size, so both directions move at a similar pace. That works best when the ravine lines up with the axes: rotate it and compare.

Contours of a 2-D loss surface with the paths of SGD, momentum, RMSProp and Adam from the same start, and their loss curves on a log scale. Surfaces: an axis-aligned ravine, the same ravine rotated, the Rosenbrock function and a badly scaled bowl. Sliders set the learning rates (one for SGD and momentum, one for the adaptive methods), β₁, β₂ and the number of steps. Keyboard: Tab through the controls; arrow keys adjust sliders; the buttons toggle each optimizer.

LR schedule viewer

How schedules shape the loss curve

Static view on small screens. Open this page on a laptop to interact.

0.400learning rate 1e11e01e-11e-21e-31e-4expected loss (dashed: constant peak rate)step
final loss 0.00826 constant-rate final loss 0.37500 noise floor at the peak rate ≈ 0.3750

The model is SGD on f(x) = x² with noisy gradients, where the expected loss can be computed exactly. A large step makes fast progress but stalls at a noise floor proportional to the step size; shrinking the step lowers the floor. Warmup matters less here than in real networks, where early gradients are large and Adam's second-moment estimates are still unreliable, so a few small steps first prevent an early blow-up.

Top: the learning rate over 400 steps for a constant, step-decay, cosine or warmup-plus-cosine schedule. Bottom: the exact expected loss of SGD on a noisy quadratic under that schedule, with the constant-rate curve dashed for comparison, on a log scale. Keyboard: Tab through the buttons and sliders; arrow keys adjust sliders.

Implement the optimizers as classes that update a dictionary of NumPy arrays in place, the way PyTorch’s optimizers do. The tests check the first two steps against hand calculations, Adam’s scale invariance, and that AdamW’s decay never touches the gradient.

Optimizers stubs/m3_3_optimizers.py

Loading starter file…

Prefer your own editor? Edit exercises/stubs/m3_3_optimizers.py and run mlc check 3.3. The tests are identical; import the results on the progress page.

Hints · Adam.step 0/3 revealed
Hints · AdamW.step 0/3 revealed
Hints · in place 0/3 revealed

Locally: mlc check 3.3.

1. What problem does momentum mainly fix?
2. You multiply one parameter’s gradients by 1000 throughout training. How does Adam’s update for that parameter change (ignoring ε)?
3. Why does Adam need bias correction?
4. What is the difference between Adam with L2 regularisation and AdamW?
5. Your loss falls quickly, then flattens and bounces at a level well above zero. What is the first thing to try?
  • not yet: All tests pass (0/?)
  • not yet: Checkpoint quiz ≥ 80%
Finish the items above first.
Learner log: time spent and points of confusion

Every confusion you note becomes a fix before the module is marked stable. Export it from the progress page and attach it to an issue.