Neural-net foundations5 / 15

Lesson 5 · Building networks

Better steps: momentum and Adam

The problem

Every network so far has trained with AdamW. The training loop only ever asked it one thing: given every weight's gradient, move the weights. This lesson opens that box.

The simplest way to move is gradient descent: step against the gradient, scaled by the learning rate α\alpha:

w←w−α ∇L(w)\mathbf{w} \leftarrow \mathbf{w} - \alpha \, \nabla L(\mathbf{w})

With a random batch for each step, this is stochastic gradient descent (SGD). It works, but it has two weak spots:

  • It's slow in long, narrow valleys. The gradient points mostly across the valley, not along it. So the path bounces from wall to wall and creeps along the floor.
  • One learning rate has to suit every weight. A weight with big gradients needs small steps, or it overshoots. A weight with small gradients then barely moves.

Two fixes answer these: momentum for the first, and Adam for the second. A third idea, changing α\alpha as training goes on, finishes the lesson.

The valley again

Here is a valley you have met before. In the Gradients lesson, two weights w1w_1 and w2w_2 predicted pizza delivery times. Their error E(w1,w2)E(w_1, w_2) was a long, narrow bowl with its bottom at (4,6)(4, 6). Below it's drawn as a contour map.

Three optimisers start at (1,2)(1, 2) and take 50 steps each. Press play, then try the sliders.

012345678246810w₁ (minutes per km)w₂ (minutes per traffic level)SGDMomentumAdam
SGD (0 steps)Momentum (0 steps)Adam (0 steps)× minimum
Step 0 of 50
Error after 0 steps for each optimiser
After 0 stepsw₁, w₂error
SGD1, 2686
Momentum1, 2686
Adam1, 2686

Momentum uses the SGD learning rate too. The × marks the bottom, (4, 6).

SGD, SGD with momentum, and Adam race down the pizza error valley. Each optimiser gets the exact gradient at every step. The table shows where each one is and its error.

Things to notice:

  • SGD zig-zags. From (1,2)(1, 2) the gradient is (−316,−106)(-316, -106). With α=0.02\alpha = 0.02, the first step goes to (1+6.32,  2+2.12)=(7.32,4.12)(1 + 6.32, \; 2 + 2.12) = (7.32, 4.12), right across the valley. The next steps bounce back and forth while drifting along the floor.
  • SGD can't fix this with a bigger α\alpha. Push the slider to 0.025 or more and the bouncing grows instead of shrinking. Make α\alpha smaller and the bouncing stops, but the crawl along the floor gets slower.
  • Momentum swings wider at first, then arrives much sooner. After 30 steps its error is 0.025, against SGD's 0.23. After 50 it's at the bottom.
  • Adam heads off diagonally. Its first steps are (1.5,2.5)(1.5, 2.5), (2,3)(2, 3), (2.48,3.48)(2.48, 3.48): the same size in both directions, whatever the gradient says. It ends near the bottom, but it keeps circling there.

Why is SGD stuck between two bad choices? The valley's walls are steep across and gentle along. In the language of curvature, the error bends about 25 times more sharply across the valley than along it. A step size that is safe across is tiny along. That's the job momentum takes on.

Momentum: remember where you were going

Picture a ball rolling down the valley instead of a walker taking fresh steps. The ball has speed. Each push from the slope adds to the speed it already has. Pushes in the same direction build up, and pushes that keep flipping cancel out.

Momentum does this with one extra number per weight, a velocity v\mathbf{v}. Each step adds the new gradient to the old velocity, shrunk by a factor β\beta, then moves by the velocity:

v←β v+∇L(w)w←w−α v\begin{aligned} \mathbf{v} &\leftarrow \beta \, \mathbf{v} + \nabla L(\mathbf{w}) \\ \mathbf{w} &\leftarrow \mathbf{w} - \alpha \, \mathbf{v} \end{aligned}

This is momentum. The number β\beta (the momentum) is between 0 and 1. With β=0\beta = 0 it's plain SGD. A common choice is β=0.9\beta = 0.9 (PyTorch's SGD default is 0: no momentum); the race uses 0.7.

Read it back against the race:

  • Across the valley, the gradient flips sign every step. Adding +g+g, then −g-g, then +g+g into v\mathbf{v} mostly cancels, so the bouncing dies down.
  • Along the floor, the gradient points the same way every step. Each step adds a little more to v\mathbf{v}, so the ball speeds up.

Worked example

How fast does momentum get on a steady slope?

  1. Take β=0.9\beta = 0.9 and a gradient that stays at g=1g = 1. Start with v=0v = 0.

That speed-up is also why momentum overshoots at the start of the race. It builds speed heading across the valley before the flips cancel it out.

DeeperMomentum's speed-up, and why it doesn't blow upA steady gradient makes momentum's step 1/(1 − β) times bigger. A flipping one makes it smaller. · 3 min

The worked example found the steady state for a constant gradient gg: v=βv+gv = \beta v + g, so v=g/(1−β)v = g / (1 - \beta). The step is then αg/(1−β)\alpha g / (1 - \beta). Momentum behaves like SGD with a learning rate 1/(1−β)1/(1-\beta) times bigger, but only in directions where the gradient keeps its sign.

Now let the gradient flip: +g,−g,+g,−g,…+g, -g, +g, -g, \dots The steady state alternates between +u+u and −u-u. It satisfies u=−βu+gu = -\beta u + g: the last step's −u-u, shrunk by β\beta, plus the new +g+g. So u=g/(1+β)u = g / (1 + \beta). With β=0.9\beta = 0.9, that's g/1.9g / 1.9: about half a plain SGD step.

So with β=0.9\beta = 0.9, the same α\alpha gives a step about 10 times bigger along a steady direction. Across a flip-flopping one, the step is about 2 times smaller. That's a factor of 19 in favour of the floor of the valley. It's also why a good α\alpha for momentum is usually smaller than a good α\alpha for SGD.

Adam: a step size for every weight

Momentum still uses one learning rate for every weight. Networks have weights whose gradients differ by factors of a hundred or more. Think of a first-layer weight fed by an input measured in thousands, beside one fed by an input near 0.01.

Here is the smallest example. Two weights, aa and bb, both start at 1, and the loss is

L(a,b)=50a2+0.5b2L(a, b) = 50 a^2 + 0.5 b^2

The gradients are 100a100a and bb, so aa's gradient is always 100 times bb's. Plain SGD with α=0.01\alpha = 0.01 moves aa by 0.01×100=10.01 \times 100 = 1, all the way to 0 in one step, and bb by 0.01×1=0.010.01 \times 1 = 0.01. Any α\alpha much bigger makes aa overshoot, so bb crawls.

Predict first

Adam with learning rate α = 0.1. Weight a's gradient is 100 times bigger than weight b's. On the first step, which one moves further?

Two running averages

Adam keeps two numbers for every weight:

  • mm, a running average of its gradient gg. This is momentum, written as an average.
  • vv, a running average of its squared gradient g2g^2. Its square root, v\sqrt{v}, is the gradient's typical size, ignoring its sign.

Both are updated with the incremental mean rule from the Expectation lesson, with a fixed step size. For mm, the step size is 1−β11 - \beta_1, and for vv it's 1−β21 - \beta_2:

m←β1m+(1−β1) gv←β2v+(1−β2) g2\begin{aligned} m &\leftarrow \beta_1 m + (1 - \beta_1)\, g \\ v &\leftarrow \beta_2 v + (1 - \beta_2)\, g^2 \end{aligned}

PyTorch's defaults are β1=0.9\beta_1 = 0.9 and β2=0.999\beta_2 = 0.999. So mm averages over roughly the last 10 gradients and vv over roughly the last 1,000.

The step divides one by the other:

w←w−α m^v^+ϵw \leftarrow w - \alpha \, \frac{\hat m}{\sqrt{\hat v} + \epsilon}

The hats are a small fix explained next, and ϵ=10−8\epsilon = 10^{-8} only stops a division by zero. Read it as "the average gradient, measured in units of its typical size". If every gradient of aa is 100 times bb's, then mm is 100 times bigger and v\sqrt{v} is 100 times bigger too. They cancel, and both weights take the same step.

Bias correction

mm and vv start at 0. After one step, m=0.1 gm = 0.1\,g: the average is dragged towards its starting 0, and is ten times too small. After one step, v=0.001 g2v = 0.001\,g^2, a thousand times too small. Adam undoes this pull by dividing by how much weight the real gradients have had so far:

m^=m1−β1t,v^=v1−β2t\hat m = \frac{m}{1 - \beta_1^t}, \qquad \hat v = \frac{v}{1 - \beta_2^t}

Here tt counts the steps. At t=1t = 1, m^=0.1g/0.1=g\hat m = 0.1 g / 0.1 = g and v^=g2\hat v = g^2, both exact. As tt grows, βt\beta^t goes to 0 and the correction fades away.

Worked example

Two Adam steps by hand

  1. Step 1. The gradients are ga=100×1=100g_a = 100 \times 1 = 100 and gb=1g_b = 1.

    For aa: m=0.1×100=10m = 0.1 \times 100 = 10 and v=0.001×1002=10v = 0.001 \times 100^2 = 10. Corrected: m^=10/0.1=100\hat m = 10 / 0.1 = 100 and v^=10/0.001=10,000\hat v = 10 / 0.001 = 10{,}000, so v^=100\sqrt{\hat v} = 100.

    The step is 0.1×100/100=0.10.1 \times 100 / 100 = 0.1, so aa goes from 1 to 0.9.

Step through it yourself, for ten steps. Untick "Bias correction" to see the first step without the fix.

Loss 50·a² + 0.5·b², both weights start at 1. Adam with α = 0.1. Step t = 1.

Adam’s quantities at step 1 for weights a and b
Quantityweight aweight b
g gradient1001
m average of g100.1
v average of g²100.001
m̂ m ÷ (1 − 0.9ᵗ)1001
v̂ v ÷ (1 − 0.999ᵗ)1.00e41
Adam step α·m̂ ÷ √v̂0.10.1
SGD step (α = 0.01) would be α·g10.01

After this step: a = 0.9, b = 0.9

Adam step 0 of 9
Adam's numbers for weights a and b, step by step. The gradients differ by a factor of 100; every average differs by the same factor, and the steps come out equal. The last row shows what plain SGD with α = 0.01 would do.

Things to notice:

  • Each step is close to α=0.1\alpha = 0.1 for both weights, while SGD's would be 1 for aa and 0.01 for bb.
  • Without bias correction, the first step is 0.316, more than three times α\alpha. mm is 10 times too small but v\sqrt{v} is 1000≈32\sqrt{1000} \approx 32 times too small, so their ratio is too big.
  • The step shrinks as the weights near 0, because mm starts to lag behind the shrinking gradients. Adam's step is about α\alpha only while the gradient keeps its sign.

That last point explains Adam in the race. Near the bottom of the valley, its steps are still about α\alpha long, so it circles the bottom instead of settling. The fix is to make α\alpha smaller as training goes on.

DeeperAdam is two running averagesBoth of Adam's numbers are the incremental mean with a fixed step size, so they forget old gradients at a steady rate. · 3 min

In the Expectation lesson, the incremental mean updated an estimate by moving a fraction α\alpha of the way towards each new sample. With α=1/n\alpha = 1/n, you get the plain average. With a fixed α\alpha, recent samples count more.

Adam's mm is exactly this, with fraction 1−β1=0.11 - \beta_1 = 0.1 and sample gg. Unroll it after three steps:

m3=0.1 g3+0.09 g2+0.081 g1m_3 = 0.1\, g_3 + 0.09\, g_2 + 0.081\, g_1

Each older gradient counts 0.9 times as much as the next. The weights add up to 0.1+0.09+0.081=0.2710.1 + 0.09 + 0.081 = 0.271, not 1, because the rest of the weight (0.729=0.930.729 = 0.9^3) still sits on the starting 0. Dividing by 1−0.93=0.2711 - 0.9^3 = 0.271 makes the weights add to 1. That is the bias correction: it turns mm back into a proper weighted average.

vv is the same with g2g^2 and fraction 0.001, so it remembers about 1,000 steps. That long memory makes v\sqrt{v} a steady estimate of each weight's gradient size.

DigressionOther optimisers you'll meetRMSProp, Adagrad, Lion and Muon, in one line each. · 2 min
  • Adagrad (2011) divides by the square root of the sum of all past squared gradients. The steps keep shrinking, which suits sparse problems but can stall long runs.
  • RMSProp (proposed by Geoffrey Hinton in a 2012 lecture) replaced Adagrad's sum with a running average, like Adam's vv, without the momentum term mm.
  • Adam (Kingma and Ba, 2014) combined RMSProp's vv with momentum's mm and added bias correction. AdamW (2017) changed how weight decay is applied; Lesson 7 covers it.
  • Lion (2023) keeps only a momentum term and steps by its sign, so every weight moves exactly ±α\pm\alpha per step. It needs one stored number per weight instead of Adam's two.
  • Muon (2024) is designed for the weight matrices of large networks. It adjusts each matrix's update so that no single direction dominates. It is newer and less settled than the others.

For the networks in this book, AdamW is the safe default.

In PyTorch

All three are in torch.optim, and every optimiser has the same interface: zero_grad() and step(). The race in PyTorch is one function with the optimiser passed in:

The valley race in PyTorch
# The three deliveries from the Gradients lesson: (km, traffic level) and the minutes each took.
FEATURES = torch.tensor([[2.0, 0.0], [5.0, 1.0], [3.0, 2.0]], dtype=torch.float64)  # (3, 2)
MINUTES = torch.tensor([8.0, 26.0, 24.0], dtype=torch.float64)  # (3,)


def valley_error(w: torch.Tensor) -> torch.Tensor:
    """Total squared error of the prediction w · x over the three deliveries. Lowest (0) at w = (4, 6)."""
    return ((FEATURES @ w - MINUTES) ** 2).sum()


def race(make_optimizer: Callable[[list[torch.Tensor]], Optimizer], steps: int = 50, start: tuple[float, float] = (1.0, 2.0)) -> list[list[float]]:
    """Walk down the valley with one optimiser; return every point visited."""
    w = torch.tensor(start, dtype=torch.float64, requires_grad=True)
    optimizer = make_optimizer([w])
    path = [w.tolist()]
    for _ in range(steps):
        optimizer.zero_grad()
        valley_error(w).backward()
        optimizer.step()
        path.append(w.tolist())
    return path


RACERS: dict[str, Callable[[list[torch.Tensor]], Optimizer]] = {
    "SGD": lambda p: torch.optim.SGD(p, lr=0.02),
    "momentum": lambda p: torch.optim.SGD(p, lr=0.02, momentum=0.7),
    "Adam": lambda p: torch.optim.Adam(p, lr=0.5),  # betas (0.9, 0.999), eps 1e-8: the defaults
}
  • torch.optim.SGD(params, lr=0.02, momentum=0.7) is momentum in the form above: v←βv+g\mathbf{v} \leftarrow \beta\mathbf{v} + \mathbf{g}, then w←w−αv\mathbf{w} \leftarrow \mathbf{w} - \alpha\mathbf{v}. Some books scale the gradient by 1−β1 - \beta instead; PyTorch doesn't, unless you set dampening.
  • torch.optim.Adam(params, lr=0.5) uses betas=(0.9, 0.999) and eps=1e-8 unless you say otherwise. Its default learning rate is 0.001, which is good for big networks and far too slow for this valley.
  • The template uses torch.optim.AdamW, which is Adam plus a separate weight shrink. Lesson 7 explains the difference.

Learning-rate schedules

Adam circling the bottom of the valley suggests the next idea. A big α\alpha makes fast progress early, while the weights are far from good. Near the end, a small α\alpha lets them settle. So why keep it fixed?

A learning-rate schedule sets α\alpha for each epoch (or each step). Three common shapes:

  • Constant: no schedule.
  • Step decay: multiply α\alpha by a factor, such as 0.3, every so often. Here, every 50 epochs.
  • Warm-up then cosine: start at a tenth of α\alpha and rise in a straight line to the full α\alpha over the first 10 epochs. Then fall along half a cosine curve, reaching 0 at the end.

Warm-up guards the first few epochs. The network's first gradients can be large and point in odd directions. Adam's vv is also built from only a few gradients at first, so its step sizes are rough guesses. A few small steps give both time to settle before the big steps begin.

Below, the course's default network trains three times at once from the same starting weights: once with each schedule. The top plot is α\alpha; the bottom one is the mean training loss over each epoch.

05010015020000.050.10.150.2epochrate α05010015020000.20.40.60.811.2epochtraining loss
constantstep decaywarm-up + cosine

Step 0 · epoch 0

Peak learning rate α:
The 2-16-16-2 network trained live with AdamW, batches of 32, 200 epochs, three times at once. Top: the learning rate each schedule uses. Bottom: the mean mini-batch loss in each epoch. Change the peak learning rate to compare.

Things to notice, at the default peak rate of 0.2:

  • The constant rate spikes in the first epoch. Warm-up starts at 0.02 and avoids it.
  • The constant rate stays noisy to the end. Each step is still big, so the loss keeps jumping around.
  • Both schedules end lower. Step decay drops in stages, one at each cut. The cosine glides down as α\alpha fades.
  • At peak rate 0.01, the three runs barely differ: the rate is small enough already.

Here are the PyTorch numbers for the same runs. Your browser shuffles the batches differently, so its numbers differ a little.

Peak rateScheduleFirst-epoch lossFinal training lossValidation accuracy (last epoch)
0.05constant0.590.32091.5%
0.05step decay0.590.18296.0%
0.05warm-up + cosine0.660.19195.5%
0.2constant1.220.36784.5%
0.2step decay1.220.30890.5%
0.2warm-up + cosine0.620.25794.0%

At 0.2, warm-up halves the first-epoch loss (0.62 against 1.22), and the cosine ends with the lowest training loss and the best accuracy. At 0.05, there's no spike to avoid, and both schedules still end well below the constant rate. With 200 validation deliveries, a single delivery is half a percentage point, so read the accuracies loosely. The training losses are the steadier comparison.

In PyTorch

Schedules live in torch.optim.lr_scheduler. Each one wraps an optimiser and changes its learning rate when you call scheduler.step(). SequentialLR chains two schedules, switching at a milestone:

Step decay, and warm-up into cosine decay
def make_scheduler(optimizer: Optimizer, kind: str, epochs: int = 200, warmup: int = 10) -> LRScheduler | None:
    """A learning-rate schedule, stepped once per epoch. 'constant' means no scheduler."""
    if kind == "constant":
        return None
    if kind == "step":  # multiply the rate by 0.3 every 50 epochs
        return StepLR(optimizer, step_size=epochs // 4, gamma=0.3)
    if kind == "warmup-cosine":  # rise from 10% to 100% over `warmup` epochs, then half a cosine down to 0
        rise = LinearLR(optimizer, start_factor=0.1, end_factor=1.0, total_iters=warmup)
        fall = CosineAnnealingLR(optimizer, T_max=epochs - warmup, eta_min=0.0)
        return SequentialLR(optimizer, schedulers=[rise, fall], milestones=[warmup])
    raise ValueError(f"unknown schedule {kind!r}")


def schedule_values(kind: str, lr: float = 0.05, epochs: int = 200) -> list[float]:
    """The learning rate each epoch uses, read from a real scheduler."""
    optimizer = torch.optim.AdamW([torch.zeros(1, requires_grad=True)], lr=lr)
    scheduler = make_scheduler(optimizer, kind, epochs)
    values = []
    for _ in range(epochs):
        values.append(optimizer.param_groups[0]["lr"])
        optimizer.step()  # (PyTorch warns if the scheduler steps before the optimiser)
        if scheduler:
            scheduler.step()
    return values

This lesson's training loop is the template's epoch loop plus a scheduler. It calls scheduler.step() once per epoch, after train_one_epoch has taken that epoch's steps. It also leaves out fit's keep-best step and reports the last epoch. Keeping the best epoch would hide what the schedule does to the end of training.

The template plus a scheduler
def train_with_schedule(kind: str, lr: float = 0.05, epochs: int = 200, seed: int = 0) -> list[dict]:
    """The template's epoch loop plus a scheduler, stepped after each epoch.

    No keep-best weights: we compare last epochs, because keeping the best epoch would hide the schedule's effect.
    """
    seed_everything(seed)
    device = get_device()
    train_loader, val_loader = rush_hour_loaders(batch_size=32, seed=seed)
    model = make_mlp([2, 16, 16, 2]).to(device)
    loss_fn = nn.CrossEntropyLoss()
    optimizer = torch.optim.AdamW(model.parameters(), lr=lr)
    scheduler = make_scheduler(optimizer, kind, epochs)  # new
    history = []
    for epoch in range(1, epochs + 1):
        rate = optimizer.param_groups[0]["lr"]
        train_loss, train_acc = train_one_epoch(model, train_loader, loss_fn, optimizer, device)
        val_loss, val_acc = evaluate(model, val_loader, loss_fn, device)
        if scheduler:
            scheduler.step()  # new: once per epoch, after the optimiser's steps
        history.append({"epoch": epoch, "lr": rate, "train_loss": train_loss, "val_loss": val_loss, "val_acc": val_acc})
    return history

Where scheduler.step() goes matters:

  • After the optimiser's steps, never before. PyTorch warns if you call it before the first optimizer.step(), because the first epoch would then skip the starting rate.
  • Once per epoch or once per batch, to match how you counted. Here total_iters, step_size and T_max are all in epochs, so it's once per epoch. Big models often count in steps instead, and then scheduler.step() goes inside the batch loop, right after optimizer.step().

Putting it together

Back to the valley, with everything from this lesson.

  1. SGD is limited by the steepest direction. With an error that bends 25 times more sharply across than along, any safe α\alpha crawls along the floor.
  2. Momentum adds a velocity. Steady directions build up to 1/(1−β)1/(1 - \beta) times the speed; flip-flopping ones cancel. In the race it reaches the bottom first.
  3. Adam divides each weight's average gradient by its typical size, so every weight steps about α\alpha, whatever its gradient's scale. It's the usual default for networks, where gradient sizes vary from weight to weight and layer to layer.
  4. A schedule lets α\alpha start big and end small. Warm-up protects the first steps; decay lets the weights settle.

The course's template uses AdamW at α=0.01\alpha = 0.01 with no schedule. For a 354-weight network on 200 deliveries, that's plenty. Larger models almost always add a warm-up and a decay.

Common misconceptions

"Adam's learning rate means the same as SGD's." They're in different units. SGD's step is α\alpha times the gradient, so it depends on the gradient's size. Adam's step is about α\alpha itself. In the valley, SGD needs α\alpha below 0.024, while Adam works with 0.5.

"Adam is always faster than SGD." In the valley race, momentum reached the bottom first. Adam's strength is coping with gradients of wildly different sizes without tuning, which is what networks have.

"Momentum makes every step bigger." Only in directions where the gradient keeps its sign. Where it flips, momentum makes the steps smaller.

"Bias correction is a small detail." Without it, Adam's first step here is 0.316 instead of 0.1. That's more than three times too big, at the moment the weights are least reliable.

"Call scheduler.step() before optimizer.step()." It goes after. And call it at the rate the schedule counts in: once per epoch here.

Recap

  • SGD steps against the gradient with one learning rate α\alpha. In long, narrow valleys it bounces across and crawls along.
  • Momentum keeps a velocity v←βv+∇L\mathbf{v} \leftarrow \beta\mathbf{v} + \nabla L. Steady directions speed up by about 1/(1−β)1 / (1 - \beta); flip-flopping ones cancel.
  • Adam keeps running averages mm (gradient) and vv (squared gradient) for every weight, corrects them for starting at 0, and steps by αm^/v^\alpha \hat m / \sqrt{\hat v}. Each weight moves about α\alpha, whatever its gradient's size.
  • A learning-rate schedule changes α\alpha during training: warm up for a few epochs, then decay.
  • PyTorch names in this lesson: torch.optim.SGD(momentum=…), torch.optim.Adam and torch.optim.AdamW, torch.optim.lr_scheduler.StepLR, LinearLR, CosineAnnealingLR and SequentialLR, and scheduler.step().