Lesson 5.2: Optimisers: SGD, Adam and weight decay
Turn gradients into steps. Build SGD, momentum and Adam with weight decay, see why Adam ignores gradient scale, and measure what each does to the model.
By the end of this lesson you will be able to write plain gradient descent, momentum and Adam with decoupled weight decay, explain what each does to a step, choose between them and tune the step size, and use weight decay against overfitting. You will show that on a bowl that is steep one way and shallow the other, SGD needs 163 steps at its best step size, momentum 62 and Adam 32; that Adam's first update is 0.003 whatever the gradient's scale from 1e-6 to 1e3; that on the GPT of Lesson 4.3, SGD reaches 1.0121 after 1,000 steps at its best step size and diverges at the next one up, momentum reaches 1.0127, and Adam reaches 1.0039 and stays between 1.0039 and 1.0054 over a tenfold range of step sizes; and that on a model trained with only 1,500 tokens, weight decay cuts the validation loss from 2.8087 to 1.0779. You need Python and NumPy, and helpers.py, gpt.py and train.py from earlier lessons.
Lesson 5.1 told us what the loss is. The backward pass gives us its gradient: for every number in the model, the direction in which the loss rises. An optimiser is the rule that turns that gradient into a change of the numbers. Until now we have used one called Adam without opening it. This lesson builds three optimisers, from the simplest, and measures them.
The simplest rule: gradient descent
Step each number a little against its gradient:
w becomes w minus (step size) times (gradient of w)
The step size, called the learning rate, is a number you choose. With the true gradient over all the data this is gradient descent. With the gradient of a random batch, as we use, it is stochastic gradient descent, or SGD. The batch gradient is the full gradient plus noise, and Lesson 5.3 measures that noise.
SGD has one setting and it is delicate. Too small, and training crawls. Too large, and the steps overshoot and the loss explodes. The best value depends on how curved the loss is, which differs from one direction to another, and from one model to another.
Here is a bowl whose floor is much steeper in one direction than the other: the loss is 0.5 × (100 x² + y²). The steep direction is x, with curvature 100, and the shallow direction is y, with curvature 1. We start at (1, 1) and count the steps to a loss below 0.001, for the best step size we can find.
python
import numpy as np
from optim import
A bowl that is steep one way and shallow the other: loss = 0.5 (100 x^2 + y^2)
def run(optname, lr, steps=2000):
p = {"w": np.array([1.0, 1.0])}
opt = {"sgd": SGD, "momentum": Momentum, "adam": AdamW}[optname](p, lr)
for step in range(1, steps + 1):
w = p["w"]
loss = 0.5 (100 w[0] 2 + w[1] 2)
if loss < 1e-3:
return step
opt.step({"w": np.array([100 w[0], w[1]])})
return None # did not get there
print("SGD, best step size: ", min((run("sgd", lr), lr) for lr in (0.005, 0.01, 0.015, 0.019, 0.0199) if run("sgd", lr)))
print("SGD, step size 0.021: ", run("sgd", 0.021)) # too big for the steep direction
print("momentum, best step size:", min((run("momentum", lr), lr) for lr in (0.001, 0.003, 0.005, 0.01, 0.015) if run("momentum", lr)))
print("Adam, best step size: ", min((run("adam", lr), lr) for lr in (0.03, 0.1, 0.2, 0.3, 0.5) if run("adam", lr)))
The code uses optim.py, which is listed under "The three optimisers in code" further down. Save that file first. The output:
SGD, best step size: (163, 0.019)
SGD, step size 0.021: None
momentum, best step size: (62, 0.005)
Adam, best step size: (32, 0.2)
SGD's best step size is 0.019, and it needs 163 steps. A step size of 0.021 never converges, because it overshoots in the steep direction by more each time. The ceiling on the step size is set by the steepest direction, 2 divided by 100 = 0.02. But in the shallow direction, a step of 0.019 moves y by only 1.9% of the gradient 1 per step, so y shrinks by 0.981 per step. That is the trap of SGD on a bowl like this: the step size is limited by the steepest direction and the progress is limited by the shallowest. The ratio of the two curvatures, here 100, is the condition number, and the steps needed scale in proportion to it.
Momentum
Momentum keeps a running velocity, a sum of recent gradients, and steps along it:
velocity becomes (0.9 × velocity) plus gradient, then w becomes w minus (step size) times velocity
A direction in which the gradient keeps the same sign builds up speed: the shallow direction, where every gradient points the same way. A direction in which the gradient flips sign, like the steep direction where SGD zig-zags across the valley, cancels itself out. On the bowl, momentum converges in 62 steps, against 163.
Adam
Adam (Kingma and Ba, 2014) adds a second idea. Each number gets its own step size, scaled by how large its gradients have been. It keeps two running averages for every parameter:
m, the average of the gradient (the same idea as momentum),
v, the average of the square of the gradient.
The update is m divided by the square root of v. A parameter whose gradients are always large has a large v, so its step is divided down. One whose gradients are tiny has a small v, so its step is scaled up. The effect is to rescale every direction to a similar size, which is what the bowl needs. Adam reaches the bowl's floor in 32 steps, at a step size of 0.2.
Two details. The averages start at zero, which would make the first steps too small, so Adam divides them by one minus beta to the power t, a bias correction that is large at the start and fades. And a tiny constant eps (1e-8) is added to the denominator so that a parameter with a zero gradient does not divide by zero.
Here is a consequence worth seeing. On the first step, m equals 0.1 times g, and v equals 0.001 times g squared. After correction they are g and g squared, so the update is g divided by the absolute value of g: plus or minus 1, times the learning rate. The first update does not depend on the size of the gradient at all.
python
import numpy as np
from optim import
for scale in (1e-6, 1e-3, 1.0, 1e3):
p = {"w": np.zeros(3)}
opt = AdamW(p, lr=0.003)
opt.step({"w": np.array([1.0, -2.0, 0.5]) scale})
print(f"gradient scale {scale:8.0e} -> first update {np.round(-p['w'], 5)}")
gradient scale 1e-06 -> first update [ 0.00297 -0.00299 0.00294]
gradient scale 1e-03 -> first update [ 0.003 -0.003 0.003]
gradient scale 1e+00 -> first update [ 0.003 -0.003 0.003]
gradient scale 1e+03 -> first update [ 0.003 -0.003 0.003]
Whether the gradient is a millionth or a thousand, each number moves by almost exactly the learning rate, 0.003, in the direction of its sign. (The first row is a hair smaller because eps is not negligible next to a gradient of 1e-6.) Later steps are not quite as even, since m averages over time, but the lesson stands: with Adam, the learning rate is a distance, in the units of the weights, and not a multiple of the gradient. That makes one learning rate work across layers whose gradients differ by orders of magnitude.
The three optimisers in code
Here are the three, with weight decay, which comes next. Save this as optim.py. All three take a dictionary of weights and, at each step, a dictionary of gradients, and change the weights in place. AdamW accepts a learning rate for each step, which Lesson 5.3 uses for schedules.
python
# optim.py
import numpy as np
class SGD:
"""Plain gradient descent: move each number against its gradient."""
def init(self, params, lr):
self.p, self.lr = params, lr
def step(self, grads):
for k, w in self.p.items():
w -= self.lr grads[k]
class Momentum:
"""Keep a running velocity, so steady directions speed up and zig-zags cancel."""
def init(self, params, lr, beta=0.9):
self.p, self.lr, self.beta = params, lr, beta
self.v = {k: np.zeroslike(w) for k, w in params.items()}
def step(self, grads):
for k, w in self.p.items():
self.v[k] = self.beta self.v[k] + grads[k]
w -= self.lr self.v[k]
class AdamW:
"""Adam with decoupled weight decay. With weightdecay=0 this is plain Adam."""
def init(self, params, lr, betas=(0.9, 0.999), eps=1e-8, weightdecay=0.0):
self.p, self.lr, self.b1, self.b2, self.eps, self.wd, self.t = params, lr, betas[0], betas[1], eps, weightdecay, 0
self.m = {k: np.zeroslike(w) for k, w in params.items()}
self.v = {k: np.zeroslike(w) for k, w in params.items()}
def step(self, grads, lr=None):
lr = self.lr if lr is None else lr
self.t += 1
for k, w in self.p.items():
g = grads[k]
self.m[k] = self.b1 self.m[k] + (1 - self.b1) g # running mean of the gradient
self.v[k] = self.b2 self.v[k] + (1 - self.b2) g g # running mean of its square
mhat = self.m[k] / (1 - self.b1 self.t) # correct the start-up bias
vhat = self.v[k] / (1 - self.b2 self.t)
w -= lr mhat / (np.sqrt(vhat) + self.eps)
if self.wd and w.ndim >= 2: # shrink the weight matrices, not biases or norms
w -= lr self.wd w
Weight decay
A model with many numbers and little data can overfit: fit the training examples, noise included, and fail on new ones. One cure is to keep the weights small, since large weights make a model that bends sharply to fit every point. Weight decay shrinks every weight a little at every step:
w becomes w times (1 minus learning rate times decay)
For a decay of 0.1 and a learning rate of 0.003, each step shrinks every weight by 0.03%, which is nothing in one step and a lot over thousands: after 3,000 steps the weights would shrink to 41% of their size if the gradients did nothing to counter it. The training pushes weights up where they help the loss, and the decay pushes them down everywhere, and the balance is a smaller model.
The older way to do this, adding a penalty to the loss (the "L2" penalty), interacts badly with Adam. The penalty's gradient is rescaled by the division by the square root of v, so heavily-updated weights are penalised less. Decoupled weight decay (Loshchilov and Hutter, 2019), which our AdamW uses, shrinks the weights directly, after the Adam step, and so treats all weights alike. Our code decays only the weight matrices (arrays with two dimensions) and leaves the biases and the norm gains alone, as most implementations do.
We test it by making overfitting easy: a wider model (width 64) trained on only 1,500 tokens, and validated on the full validation set.
python
from train import
from optim import
Overfitting on purpose: a wider model and only 1,500 tokens to learn from
small = trainids[:1500]
d, L, h = 64, 2, 2
Pos = sinusoidal(T, d)
def fit(wd, steps=2500, seed=0):
p = initgpt(V, d, L, seed=seed)
opt = AdamW(p, 0.003, weightdecay=wd)
rng = np.random.defaultrng(seed)
for step in range(steps):
x, y = getbatch(small, 32, T, rng)
loss, g = lossandgrads(p, x, y, L, h, Pos)
opt.step(g)
xt, yt = getbatch(small, 400, T, np.random.defaultrng(5))
trainloss = -np.log(softmax(gptfwd(p, xt, L, h, Pos)[0])[np.arange(400)[:, None], np.arange(T)[None, :], yt]).mean()
return trainloss, validation(p, d=d, L=L, h=h), np.sqrt(sum((w 2).sum() for w in p.values()))
for wd in (0.0, 0.1, 1.0, 3.0):
tl, vl, norm = fit(wd)
print(f"weight decay {wd:<4} train loss {tl:.4f} validation loss {vl:.4f} gap {vl - tl:.4f} weight norm {norm:.1f}", flush=True)
weight decay 0.0 train loss 0.3491 validation loss 2.8087 gap 2.4595 weight norm 51.6
weight decay 0.1 train loss 0.3677 validation loss 2.5795 gap 2.2118 weight norm 43.2
weight decay 1.0 train loss 0.4647 validation loss 1.9077 gap 1.4430 weight norm 41.5
weight decay 3.0 train loss 1.0008 validation loss 1.0779 gap 0.0771 weight norm 34.3
With no decay, the model memorises: training loss 0.3491, validation loss 2.8087, a gap of 2.46. As the decay grows, the training loss rises (it can no longer memorise) and the validation loss falls: 2.5795, 1.9077, and at a decay of 3.0, 1.0779, with a gap of only 0.077. The weight norm falls from 51.6 to 34.3. A decay of 3.0 is far above the 0.1 or so that large models use, and that is the point: this model has far too much freedom for its data, so it needs strong regularisation. The best decay depends on how much data there is compared with the model.
Which one on a real model?
We compare them on the GPT of Lesson 4.3, with a grid of step sizes for each, 1,000 steps, same data and seed.
python
from train import
from optim import
def fit(makeopt, steps=1000, d=32, L=2, h=2, seed=0):
Pos = sinusoidal(T, d)
p = initgpt(V, d, L, seed=seed)
opt = makeopt(p)
rng = np.random.defaultrng(seed)
for step in range(steps):
x, y = getbatch(trainids, 32, T, rng)
loss, g = lossandgrads(p, x, y, L, h, Pos)
if not np.isfinite(loss):
return float("inf")
opt.step(g)
return validation(p)
grid = {"SGD": (SGD, (0.1, 0.3, 1.0)), "momentum": (Momentum, (0.03, 0.1, 0.3)), "Adam": (AdamW, (0.001, 0.003, 0.01))}
for name, (cls, lrs) in grid.items():
for lr in lrs:
with np.errstate(all="ignore"):
v = fit(lambda p: cls(p, lr))
print(f"{name:9s} step size {lr:<6} validation after 1,000 steps: {v:.4f}", flush=True)
SGD step size 0.1 validation after 1,000 steps: 1.1689
SGD step size 0.3 validation after 1,000 steps: 1.0121
SGD step size 1.0 validation after 1,000 steps: inf
momentum step size 0.03 validation after 1,000 steps: 1.1266
momentum step size 0.1 validation after 1,000 steps: 1.0127
momentum step size 0.3 validation after 1,000 steps: 2.6410
Adam step size 0.001 validation after 1,000 steps: 1.0053
Adam step size 0.003 validation after 1,000 steps: 1.0039
Adam step size 0.01 validation after 1,000 steps: 1.0054
Three observations.
Adam reaches the lowest loss (1.0039 against 1.0121 for SGD and 1.0127 for momentum), though all three get close in 1,000 steps on this easy problem.
Adam is forgiving. Across a tenfold range of step sizes, from 0.001 to 0.01, it stays between 1.0039 and 1.0054. SGD has a window: 0.1 is too slow (1.1689), 0.3 is right and 1.0 diverges (infinite loss). Momentum is even narrower: 0.03 too slow, 0.1 right and 0.3 gives 2.6410. Finding SGD's right setting takes a search, and the right setting changes with the model.
The step sizes mean different things. SGD's step size multiplies the gradient. Adam's is a distance. Do not carry one over to the other.
Adam is the default for language models, and has been since the transformer. Its cost is memory: two extra numbers per weight, as Lesson 4.4 counted. Its usual settings are betas of 0.9 and 0.999, an eps of 1e-8 and a small weight decay, 0.01 to 0.1 for large models. The learning rate depends on the model: 0.003 suits our tiny model, and models with hundreds of millions of parameters and more use smaller rates, often a few times 1e-4. Lesson 5.3 turns to how to vary the rate during a run.
Key takeaways
An optimiser turns the gradient into a change of the weights. SGD steps against the gradient: w becomes w minus (rate) times (gradient).
SGD's step size is limited by the steepest direction and its progress by the shallowest. On a bowl with a curvature ratio of 100, it needs 163 steps, and a step size of 0.021 against a ceiling of 0.02 diverges.
Momentum keeps a velocity: steady directions speed up and zig-zags cancel. It took 62 steps.
Adam keeps an average of the gradient and of its square and divides one by the root of the other, so each weight takes a step of about the learning rate in the direction of its sign. It took 32 steps. Its first update was 0.003 for gradients from 1e-6 to 1e3.
With noisy gradients, Adam's step shrinks to about the learning rate times mean over root mean square.
Weight decay shrinks the weights each step. Decoupled decay (AdamW) shrinks them directly, and it is applied to matrices and not to biases or norm gains.
On a model trained with 1,500 tokens, decay of 0, 0.1, 1.0 and 3.0 gave validation losses of 2.8087, 2.5795, 1.9077 and 1.0779.
On the GPT, Adam reached 1.0039 and tolerated a tenfold range of step sizes. SGD (1.0121) and momentum (1.0127) each worked only near one setting.
Common mistakes
Using SGD's step size with Adam, or the reverse. They are different quantities.
Adding an L2 penalty to the loss with Adam. It interacts with the rescaling. Use decoupled decay.
Decaying the biases and norm gains. They are few and they are not the source of overfitting.
Forgetting the bias correction. The first steps of Adam are far too small without it.
Comparing optimisers at one step size. Each has its own best value. Compare at the best of a grid.
Using a decay tuned for a huge model on a tiny one, or the reverse. The right amount depends on the ratio of data to parameters.
Reading a diverged run as a bad optimiser. An infinite loss at a step size just above the limit is the step size, not the algorithm.
Ignoring optimiser memory. Adam holds two extra copies of the weights.
Check yourself
1. A parameter's gradient is 5 on every step. What is the size of Adam's update, with a learning rate of 0.001?
About 0.001: m divided by the root of v is 5 over 5, which is 1, times the learning rate.
2. Why does SGD need many steps on a bowl with a curvature ratio of 100?
Its step size must stay below 2 over the steepest curvature, and then progress in the shallow direction per step is only a hundredth as fast. The steps needed grow with the ratio.
3. With weight decay 0.1 and learning rate 0.01, by what factor do the weights shrink per step, if the gradient were zero?
1 minus 0.01 × 0.1 = 0.999 per step.
4. A gradient has a steady part of 0.2 and noise of 1.0. About what share of the learning rate does Adam step?
0.2 ÷ √(0.04 + 1) = 0.2 ÷ 1.02 = 0.196, about 20%.
5. Why is the first update of Adam about equal to the learning rate?
After bias correction, m is the gradient g and v is g squared, so the update is g over the absolute value of g, which is plus or minus one, times the learning rate.
6. A model's training loss is 0.3 and its validation loss 2.5. What might you try, and why?
It is overfitting. Try weight decay, more data, a smaller model or earlier stopping.
Try this
Set aside two hours. You need Python, NumPy, optim.py and the earlier files.
1. Run the bowl comparison. Change the curvature of the steep direction from 100 to 10 and to 1,000. How do the steps for SGD, momentum and Adam change?
2. Run the first-update test with eps set to 1e-3. What happens to the smallest gradient?
3. Train the GPT with Adam at step sizes of 0.0003, 0.03 and 0.1. Find where it fails.
4. Add the L2 penalty to the loss in place of decoupled decay and compare the validation loss at the same strength.
5. Run the weight-decay experiment with decay applied to the biases as well. Does it change anything?
6. Change Adam's second beta from 0.999 to 0.95 and to 0.9999. How does the 1,000-step loss change?
A good result is three working optimisers, a table of losses by step size and a weight-decay experiment that closes the gap between training and validation. The next lesson varies the learning rate during the run, controls the noise of a batch and caps a runaway gradient.
Read more
Diederik Kingma and Jimmy Ba, "Adam: A Method for Stochastic Optimization" (2014), defines the algorithm. Ilya Loshchilov and Frank Hutter, "Decoupled Weight Decay Regularization" (2019), introduces AdamW. Boris Polyak, "Some methods of speeding up the convergence of iteration methods" (1964), is the source of momentum. Gabriel Goh, "Why Momentum Really Works" (Distill, 2017), has interactive pictures of the bowl.
Tags: Build an LLM Optimiser Adam Weight decay Gradient descent