Optimisers
Last updated
Gradient descent takes a step straight downhill, the same size in every direction. On a real loss surface that’s often a poor plan: steep one way, nearly flat another, and one learning rate can’t suit both. This lesson builds the optimisers that fix it, momentum, RMSProp and Adam, from their update rules, checks a hand-written Adam against PyTorch’s, and races them, so you can choose one and set its learning rate.
By the end of this lesson you can
- Say why plain SGD is slow in a ravine, and how momentum helps
- Write the update rules of RMSProp and Adam, and check Adam against torch.optim.Adam
- Explain what AdamW changes about weight decay
- Choose an optimiser and a starting learning rate for it
SGD again, in a ravine
Take the simplest awkward surface, a ravine:
Across it, in , the slope changes 40 times faster than along it, in . SGD's step is , and in each step multiplies by . That shrinks only while , so must stay below 0.5. In , each step multiplies by : with below 0.5, that's at least 0.95, so creeps.
"""Four optimisers on a ravine: f(x, y) = 0.05 x² + 2 y², 50 steps from (-8, 1).""" import torch def f(p): return 0.05 * p[0] ** 2 + 2 * p[1] ** 2 def race(make): p = torch.tensor([-8.0, 1.0], requires_grad=True) optimizer = make([p]) for _ in range(50): loss = f(p) optimizer.zero_grad() loss.backward() optimizer.step() return p.detach(), f(p).item() runs = { "SGD, lr 0.2": lambda ps: torch.optim.SGD(ps, lr=0.2), "SGD, lr 0.49": lambda ps: torch.optim.SGD(ps, lr=0.49), "SGD, lr 0.51": lambda ps: torch.optim.SGD(ps, lr=0.51), "momentum 0.9, lr 0.05": lambda ps: torch.optim.SGD(ps, lr=0.05, momentum=0.9), "RMSProp, lr 0.1": lambda ps: torch.optim.RMSprop(ps, lr=0.1), "Adam, lr 0.5": lambda ps: torch.optim.Adam(ps, lr=0.5), } for name, make in runs.items(): p, loss = race(make) print(f"{name:22} ends at ({p[0]:7.3f}, {p[1]:9.3f}), f = {loss:.4g}")
(.venv) $ python ravine.py SGD, lr 0.2 ends at ( -2.913, 0.000), f = 0.4244 SGD, lr 0.49 ends at ( -0.649, 0.130), f = 0.05479 SGD, lr 0.51 ends at ( -0.584, 7.107), f = 101 momentum 0.9, lr 0.05 ends at ( 0.113, -0.030), f = 0.002504 RMSProp, lr 0.1 ends at ( -0.377, 0.000), f = 0.00712 Adam, lr 0.5 ends at ( -0.278, -0.055), f = 0.009853
Look at the first three lines. At 0.2, SGD is still at after 50 steps. At 0.49 it gets further but zigzags across the ravine. At 0.51, just over the limit, it's thrown out: , from a start of 5.2. The steep direction sets the largest safe learning rate, and the gentle direction pays for it. Real loss surfaces have millions of directions, and this mismatch is the rule, not the exception. Watch it:
Step 0 of 50. At 0.2, SGD is stable across the ravine but crawls along it. Momentum builds up speed along the floor; RMSProp and Adam divide each direction's step by its own typical gradient, so the gentle direction gets big steps.
Momentum
A ball rolling down the ravine doesn't stop and restart at every step: it keeps its speed. Momentum keeps a running velocity , and steps along it:
Along the floor of the ravine, the gradients all point the same way, so grows: with , up to 10 times one gradient. Across it, they flip sign every step and mostly cancel. So momentum speeds up the gentle direction and damps the steep one. In the script, with a learning rate 4 times smaller than SGD's first run, it ends at , 170 times lower.
In PyTorch it's an argument to SGD: torch.optim.SGD(params, lr=0.01, momentum=0.9). is the usual choice.
RMSProp
Momentum still uses one learning rate for every direction. RMSProp gives each parameter its own, by dividing its step by the size of its recent gradients:
is squared element by element, so is each parameter's typical gradient size, its root mean square: hence the name. A steep direction gets divided by a big number and a gentle one by a small one, so both take steps of about . , about , only stops a division by zero. Hinton introduced it in a lecture in 2012, never in a paper; the slides are in the sources. PyTorch's default is 0.99.
Adam
Adam (Kingma and Ba, 2015) does both: a momentum-like average of the gradients, , divided by an RMSProp-like average of their squares, :
The middle two are the bias correction. and start at zero, so for the first few steps they're too small: after one step, . Dividing by puts it right, and as grows the divisor goes to 1 and stops mattering. The defaults are , , .
Write it out and check it against PyTorch's:
"""Adam written out by hand, checked against torch.optim.Adam.""" import torch torch.manual_seed(0) w_mine = torch.randn(5, requires_grad=True) w_torch = w_mine.detach().clone().requires_grad_(True) target = torch.randn(5) lr, beta1, beta2, eps = 0.1, 0.9, 0.999, 1e-8 m = torch.zeros(5) v = torch.zeros(5) optimizer = torch.optim.Adam([w_torch], lr=lr, betas=(beta1, beta2), eps=eps) for t in range(1, 101): for w in (w_mine, w_torch): w.grad = None ((w - target) ** 4).sum().backward() g = w_mine.grad with torch.no_grad(): m = beta1 * m + (1 - beta1) * g # momentum: an average of gradients v = beta2 * v + (1 - beta2) * g ** 2 # an average of squared gradients m_hat = m / (1 - beta1 ** t) # bias correction: m and v start at 0 v_hat = v / (1 - beta2 ** t) w_mine -= lr * m_hat / (v_hat.sqrt() + eps) optimizer.step() print("biggest difference from torch.optim.Adam after 100 steps:", f"{(w_mine - w_torch).abs().max().item():.1e}")
(.venv) $ python adam.py biggest difference from torch.optim.Adam after 100 steps: 2.4e-07
Agreement to , the rounding of 32-bit floats over 100 steps: those five lines are Adam.
AdamW, and choosing one
Weight decay pulls every weight a little towards zero each step, a regulariser like lesson 3.8's ridge. With SGD, adding to the gradient does exactly that. With Adam it doesn't: the added gets divided by like the rest of the gradient, so weights with big gradients are hardly decayed at all. AdamW (Loshchilov and Hutter, 2019) decouples it: it takes Adam's step, then separately subtracts . It's the usual choice for large models, transformers included.
Now the four on lesson 7.2's digits network, from the same start, with the same batches:
"""The four optimisers on lesson 7.2's digits network: the loss after 3 and after 10 epochs.""" import torch from sklearn.datasets import load_digits from torch import nn from torch.utils.data import DataLoader, TensorDataset X, y = load_digits(return_X_y=True) data = TensorDataset(torch.tensor(X / 16, dtype=torch.float32), torch.tensor(y)) def run(make, epochs=10): torch.manual_seed(0) # the same start and batches for each model = nn.Sequential(nn.Linear(64, 32), nn.ReLU(), nn.Linear(32, 10)) optimizer = make(model.parameters()) loader = DataLoader(data, batch_size=32, shuffle=True) losses = [] for epoch in range(epochs): total = 0.0 for xb, yb in loader: loss = nn.functional.cross_entropy(model(xb), yb) optimizer.zero_grad() loss.backward() optimizer.step() total += loss.item() * len(xb) losses.append(total / len(data)) return losses runs = { "SGD, lr 0.01": lambda ps: torch.optim.SGD(ps, lr=0.01), "SGD, lr 0.1": lambda ps: torch.optim.SGD(ps, lr=0.1), "momentum 0.9, lr 0.01": lambda ps: torch.optim.SGD(ps, lr=0.01, momentum=0.9), "RMSProp, lr 0.001": lambda ps: torch.optim.RMSprop(ps, lr=0.001), "Adam, lr 0.001": lambda ps: torch.optim.Adam(ps, lr=0.001), "Adam, lr 0.01": lambda ps: torch.optim.Adam(ps, lr=0.01), "AdamW, lr 0.001": lambda ps: torch.optim.AdamW(ps, lr=0.001, weight_decay=0.01), } print(f"{'':22} loss after 3 epochs after 10") for name, make in runs.items(): losses = run(make) print(f"{name:22} {losses[2]:18.3f} {losses[9]:8.3f}")
(.venv) $ python digits.py loss after 3 epochs after 10 SGD, lr 0.01 2.256 1.986 SGD, lr 0.1 0.890 0.198 momentum 0.9, lr 0.01 1.082 0.197 RMSProp, lr 0.001 0.825 0.261 Adam, lr 0.001 1.400 0.304 Adam, lr 0.01 0.186 0.060 AdamW, lr 0.001 1.401 0.306
Read it carefully, because it isn't the ravine's story:
- The learning rate matters more than the optimiser. SGD at 0.01 has barely started (1.986); SGD at 0.1 is at 0.198.
- Adam at its default, 0.001, is slower than tuned SGD here (0.304). At 0.01 it's the best of all, 0.060.
- Momentum lets SGD use a smaller learning rate: at 0.01 it matches plain SGD at 0.1.
- AdamW and Adam are almost the same on a model this small trained this briefly; decoupled decay matters over long runs.
So, a rule of thumb: start with Adam or AdamW at 0.001, because it's usually good without tuning, then try 3 or 10 times larger. If you use SGD, use momentum 0.9 and tune the learning rate (lesson 7.4 shows how to find it).
Wrong way: Adam with a learning rate of 1
Adam divides by the gradient's size, so its steps are about per parameter, whatever the gradient. That's what makes it forgiving, and also what makes a large so destructive: with , every weight moves by about 1 on the first step.
"""The wrong way: Adam with a learning rate of 1.""" import torch from sklearn.datasets import load_digits from torch import nn from torch.utils.data import DataLoader, TensorDataset X, y = load_digits(return_X_y=True) data = TensorDataset(torch.tensor(X / 16, dtype=torch.float32), torch.tensor(y)) torch.manual_seed(0) model = nn.Sequential(nn.Linear(64, 32), nn.ReLU(), nn.Linear(32, 10)) optimizer = torch.optim.Adam(model.parameters(), lr=1.0) # the default is 0.001 loader = DataLoader(data, batch_size=32, shuffle=True) for epoch in range(1, 6): total, right = 0.0, 0 for xb, yb in loader: out = model(xb) loss = nn.functional.cross_entropy(out, yb) optimizer.zero_grad() loss.backward() optimizer.step() total += loss.item() * len(xb) right += (out.argmax(dim=1) == yb).sum().item() print(f"epoch {epoch}: loss {total / len(data):10.1f}, accuracy {right / len(data):.3f}") with torch.no_grad(): X_all = data.tensors[0] hidden = torch.relu(model[0](X_all)) # the 32 hidden units, for every image print("hidden units on for at least one image:", (hidden > 0).any(dim=0).sum().item(), "of 32") print("different answers given:", model(X_all).argmax(dim=1).unique().tolist())
(.venv) $ python adam_lr1.py epoch 1: loss 8.2, accuracy 0.086 epoch 2: loss 2.4, accuracy 0.095 epoch 3: loss 2.4, accuracy 0.099 epoch 4: loss 2.4, accuracy 0.107 epoch 5: loss 2.4, accuracy 0.096 hidden units on for at least one image: 0 of 32 different answers given: [6]
The first epoch's loss is 8.2, worse than a uniform guess (); then it sticks at 2.4 and the accuracy at chance. The last two lines say why. The first steps threw the weights so far that every hidden ReLU went dead (lesson 6.2): 0 of the 32 units is on for any image, so no gradient flows back through them, and only the output layer's biases can still change. The network says 6 for every digit. Adam's isn't SGD's: values from 0.0001 to 0.01 are normal, and 1 never is.
Check what you learned
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- Kingma and Ba, Adam: A Method for Stochastic Optimization, 2015: Adam, its bias correction, and its default settings
- Loshchilov and Hutter, Decoupled Weight Decay Regularization, 2019: AdamW
- Tieleman and Hinton, Neural Networks for Machine Learning, lecture 6.5: RMSProp, 2012: RMSProp, introduced in lecture slides rather than a paper
- PyTorch: torch.optim: SGD, RMSprop, Adam and AdamW, and the exact update each one does
- Goodfellow, Bengio and Courville, Deep Learning, chapter 8: momentum and adaptive learning rates