AI from scratch · Toolkit 3 · Stage 4: the engineer's toolkit

Optimizers and schedules

Chapter 2's gradient descent takes a step straight downhill. Real training almost never uses it plain. It uses Adam, or SGD with momentum, and a learning-rate schedule that warms up and then cools down. These are small changes to one line of code, and they're often the difference between a model that trains in an hour and one that never does. This lesson races them on the same valley, builds each one from a single idea, and ends with how to choose the settings.

1. The race

The loss here is a long, narrow valley, 50 times steeper across than along: \(L = \tfrac12 (x^2 + 50\, y^2)\). Real losses are full of valleys like this (calculus 3's curvature, linear algebra 2's stretched directions). All four optimizers start at the same point; each has its own learning rate, tuned for it. Press play, then push the learning rate up.

SGD momentum RMSprop Adam

Plain SGD has a problem it can't escape: the steep direction limits its step size. Any learning rate above \(2 / 50 = 0.04\) makes it overshoot across the valley a little more each time and fly off (its rate here is 0.039, so push the slider just past ×1). Below that limit, steps along the gentle direction are tiny, so it crawls: 118 steps to get the loss under 0.001. Momentum gets there in 61, RMSprop in 31, Adam in 71. Each fixes the crawl in its own way.

Why can't SGD just use a bigger learning rate to go faster along the valley?

Chapter 2's step is \(w \leftarrow w - \eta g\). Across the valley, each step multiplies the distance from the bottom by \(1 - 50\eta\); above \(\eta = 0.04\) that's below −1, and it grows. Along it, the factor is \(1 - \eta\): close to 1, so progress is slow. The ratio of the two curvatures, 50, is the problem.

In a narrow valley one learning rate can't suit both directions: the steep one caps it, and the gentle one crawls.

2. Momentum: a ball that remembers

Instead of stepping along today's gradient, step along a running average of recent gradients. Across the valley the gradients flip sign every step (left wall, right wall), so they cancel in the average. Along the valley they all point the same way, so they add up.

\[ v \leftarrow \beta\, v + g, \qquad w \leftarrow w - \eta\, v \qquad (\beta \approx 0.9) \]

That running average has a name you'll see everywhere, the exponentially weighted average (EWA): \(v \leftarrow \beta v + (1 - \beta) x\). Each old value's weight shrinks by \(\beta\) per step, so it remembers roughly the last \(1/(1 - \beta)\) values: 10 for \(\beta = 0.9\), 1,000 for 0.999. (Momentum as written above leaves out the \(1 - \beta\); that just rescales \(\eta\).)

The plain average starts at 0 and takes about 10 steps to catch up: after one reading of 5 it says 0.5. Dividing by \(1 - \beta^t\) fixes the start exactly, and fades out as \(\beta^t\) goes to 0. Adam uses this bias correction.

About how many recent values does an EWA with \(\beta = 0.99\) remember?

\(1 / (1 - 0.99) = 100\). Higher \(\beta\) is smoother but slower to react.

Momentum steps along a running average of gradients: zig-zags cancel, steady directions add up.

Why momentum goes about 10 times faster along the valley
  1. Along the gentle direction the gradient \(g\) barely changes from step to step. Call it constant.
  2. Then \(v\) grows as \(g, (1 + \beta) g, (1 + \beta + \beta^2) g, \dots\), a sum that settles at \(g / (1 - \beta)\).
  3. With \(\beta = 0.9\) that's \(10 g\): each step moves 10 times as far as plain SGD with the same \(\eta\).
  4. Across the valley the gradient flips sign each step, so \(v\) is a sum like \(g - \beta g + \beta^2 g - \dots = g / (1 + \beta)\): about half a step, which damps the zig-zag instead of growing it.
  5. So momentum multiplies the useful direction by 10 and the useless one by 0.5: the valley looks 20 times less narrow to it.

3. RMSprop and Adam: a step size per weight

Momentum still uses one learning rate for everything. RMSprop gives each weight its own: keep an EWA of each weight's squared gradient, and divide that weight's step by its square root. A weight whose gradients are big (the steep direction) gets small steps; one whose gradients are small gets big ones. In the race, that's why RMSprop heads almost straight for the bottom.

\[ s \leftarrow \beta_2\, s + (1 - \beta_2)\, g^2, \qquad w \leftarrow w - \eta\, \frac{g}{\sqrt{s} + \epsilon} \]

(Everything is per weight: \(g^2\) squares each entry. \(\epsilon \approx 10^{-8}\) keeps it from dividing by zero.) Adam is momentum and RMSprop together, with bias correction on both averages:

\[ m \leftarrow \beta_1 m + (1 - \beta_1) g, \quad s \leftarrow \beta_2 s + (1 - \beta_2) g^2, \quad w \leftarrow w - \eta\, \frac{m / (1 - \beta_1^t)}{\sqrt{s / (1 - \beta_2^t)} + \epsilon} \]

The defaults \(\beta_1 = 0.9,\ \beta_2 = 0.999,\ \eta = 10^{-3}\) work for a surprising range of models, which is why Adam is the default almost everywhere. In the race it's not the fastest: on one clean valley its momentum overshoots a little. Its strength is that it rarely needs much tuning.

In RMSprop, one weight's gradients have been around 100 and another's around 0.01. How do their step sizes compare?

\(g / \sqrt{s}\) is about \(\pm 1\) when \(g\) stays near its typical size. That's the whole trick: every weight moves at about the same speed, whatever the units of its gradient.

RMSprop divides each weight's step by its own typical gradient size; Adam adds momentum and bias correction on top.

4. Weight decay, done right: AdamW

Chapter 11's L2 penalty adds \(\lambda w\) to every gradient, pulling weights toward zero. With SGD that's the same as shrinking every weight by a fixed fraction each step, called weight decay. With Adam it isn't: the \(\lambda w\) term goes through the division by \(\sqrt{s}\), so weights with big gradients barely get pulled, and the penalty does something nobody intended. AdamW applies the shrink separately, outside the division:

\[ w \leftarrow w - \eta \left( \frac{\hat m}{\sqrt{\hat s} + \epsilon} + \lambda\, w \right) \]

In PyTorch that's torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0.01), and it's what nearly every transformer is trained with.

With Adam, an L2 penalty gets rescaled per weight; AdamW keeps the shrink separate so every weight decays at the same rate.

5. Schedules: warm up, then cool down

The best learning rate changes during training. Early on, the weights are random and Adam's averages are based on a handful of steps: a big step can throw the model somewhere it never recovers from. Late in training, the model is near a good spot and big steps bounce around it. So the rate is scheduled: a short linear warmup from near zero, then a slow decay.

A transformer's loss spikes to NaN in the first 50 steps at learning rate 3e-4, but trains fine if you start at 3e-4 after 500 steps of training at 1e-5. What does it need?

Early updates are the riskiest: random weights, large gradients, and Adam's \(s\) estimated from very few steps (so \(\sqrt{s}\) can be tiny and the steps huge). Warmup gives the averages time to settle.

Training starts with a short warmup so early, unreliable steps stay small, then decays so late steps settle instead of bouncing.

6. Choosing the settings

The learning rate matters most, then the batch size and weight decay, then everything else. Three habits:

Search the learning rate first, on a log scale, with random points rather than a grid.

Where it breaks: what optimizers can't fix

7. What to carry forward

OptimizerThe ideaUse it when
SGDStep along the gradient; capped by the steepest directionRarely alone
SGD + momentumStep along an EWA of gradients (β ≈ 0.9)Image models with a tuned schedule
RMSpropDivide each step by its weight's typical gradient sizeOlder RNN work; the idea lives on in Adam
Adam / AdamWBoth, with bias correction; AdamW decays weights separatelyThe default: transformers, most new models

All lessons: AI from scratch. Distill's "Why Momentum Really Works" (Gabriel Goh) goes deeper into section 2.

Last updated