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?
- It can: it just wasn't tuned
- One learning rate serves both directions, and the steep one overshoots and diverges above 2 / 50 = 0.04
- The gradient along the valley is zero
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?
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
- Along the gentle direction the gradient \(g\) barely changes from step to step. Call it constant.
- Then \(v\) grows as \(g, (1 + \beta) g, (1 + \beta + \beta^2) g, \dots\), a sum that settles at \(g / (1 - \beta)\).
- With \(\beta = 0.9\) that's \(10 g\): each step moves 10 times as far as plain SGD with the same \(\eta\).
- 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.
- 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?
- About the same: each step is the gradient divided by its own typical size, roughly ±η
- The first steps 10,000 times further
- The second steps 10,000 times further
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?
- A permanently lower learning rate
- A faster decay
- A warmup: ramp the rate up from near zero over the first few hundred steps
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:
- Log scale. Try 1e-4, 3e-4, 1e-3, 3e-3: a factor of 3 apart, not 0.0001 apart. The same for weight decay and for \(1 - \beta\) (0.9, 0.99, 0.999 are 10× apart in \(1 - \beta\)).
- Random beats grid. With two settings of which only one really matters, a 3 × 3 grid tries just 3 values of the important one; 9 random points try 9.
- The learning-rate range test. Train for a few hundred steps while the rate grows exponentially from 1e-7 to 1, plot the loss: pick a rate a bit below where it falls fastest, well below where it blows up.
Search the learning rate first, on a log scale, with random points rather than a grid.
Where it breaks: what optimizers can't fix
- A rate that's simply too high. Adam's per-weight scaling keeps every step near \(\eta\) in size, but if \(\eta\) itself is too big the loss still jumps around or turns into NaN. No optimizer replaces the range test.
- Fast isn't the same as good. On image classifiers, plain SGD with momentum and a good schedule often ends at slightly better test accuracy than Adam, even though Adam gets the training loss down sooner. Which minimum you land in matters, not only how fast you get there.
- Settings tuned at one size. A learning rate tuned with batch size 32 is wrong at 1,024 (the training-in-PyTorch lesson: the rate scales with the batch, up to a limit). Change the batch, re-tune the rate, and keep the warmup.
7. What to carry forward
| Optimizer | The idea | Use it when |
|---|---|---|
| SGD | Step along the gradient; capped by the steepest direction | Rarely alone |
| SGD + momentum | Step along an EWA of gradients (β ≈ 0.9) | Image models with a tuned schedule |
| RMSprop | Divide each step by its weight's typical gradient size | Older RNN work; the idea lives on in Adam |
| Adam / AdamW | Both, with bias correction; AdamW decays weights separately | The default: transformers, most new models |
- EWA: \(v \leftarrow \beta v + (1 - \beta) x\) remembers about \(1/(1 - \beta)\) values; divide by \(1 - \beta^t\) to fix the start.
- Schedule: warm up, then decay (cosine is a common default).
- Tune the learning rate first, on a log scale, with random search or a range test.
All lessons: AI from scratch. Distill's "Why Momentum Really Works" (Gabriel Goh) goes deeper into section 2.
Last updated