Deep learning in practice · lesson 3 of 13
Parts in this lesson
Atorch.optim.SGD(params, lr=0.01, momentum=0.9)SGD with momentum
Btorch.optim.Adam(params, lr=0.001)Adam, with its default learning rate
Ctorch.optim.AdamW(params, lr=0.001, weight_decay=0.01)Adam with decoupled weight decay
Dm_hat = m / (1 - beta1 ** t)bias correction: the averages start at zero

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:

f(x,y)=0.05x2+2y2.

Across it, in y, the slope changes 40 times faster than along it, in x. SGD's step is θ←θ−η∇f, and in y each step multiplies y by 1−4η. That shrinks y only while |1−4η|<1, so η must stay below 0.5. In x, each step multiplies x by 1−0.1η: with η below 0.5, that's at least 0.95, so x 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}")
Terminal, in ml-local/7-3
(.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 x=−2.9 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: f=101, 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:

Optimiser racea ravine: f(x, y) = 0.05x² + 2y², 40 times steeper across than along
SGD, lr 0.2: f = 5.2momentum 0.9, lr 0.05: f = 5.2RMSProp, lr 0.1: f = 5.2Adam, lr 0.5: f = 5.2

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 v, and steps along it:

vt=βvt−1+∇θL,θ←θ−ηvt.

Along the floor of the ravine, the gradients all point the same way, so v grows: with β=0.9, 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 f=0.0025, 170 times lower.

In PyTorch it's an argument to SGD: torch.optim.SGD(params, lr=0.01, momentum=0.9). β=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:

st=ρst−1+(1−ρ)gt2,θ←θ−ηst+ε⊙gt.

gt2 is squared element by element, so st 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 10−8, 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, m, divided by an RMSProp-like average of their squares, v:

mt=β1mt−1+(1−β1)gt,vt=β2vt−1+(1−β2)gt2,mˆt=mt1−β1t,vˆt=vt1−β2t,θ←θ−ηmˆtvˆt+ε.

The middle two are the bias correction. m and v start at zero, so for the first few steps they're too small: after one step, m1=0.1g1. Dividing by 1−0.91=0.1 puts it right, and as t grows the divisor goes to 1 and stops mattering. The defaults are β1=0.9, β2=0.999, η=0.001.

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}")
Terminal, in ml-local/7-3
(.venv) $ python adam.py
biggest difference from torch.optim.Adam after 100 steps: 2.4e-07

Agreement to 2×10−7, 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 vˆ 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}")
Terminal, in ml-local/7-3
(.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 η=1, 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())
Terminal, in ml-local/7-3
(.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 (ln⁡10≈2.3); 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

On the ravine, why can’t SGD just use a bigger learning rate to go faster along the floor?
What is Adam’s bias correction for?
In the digits table, Adam at lr 0.001 ends at 0.304 and SGD at lr 0.1 at 0.198. What should you conclude?

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.

All sources for Simple Machine Learning