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 :
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 as training goes on, finishes the lesson.
The valley again
Here is a valley you have met before. In the Gradients lesson, two weights and predicted pizza delivery times. Their error was a long, narrow bowl with its bottom at . Below it's drawn as a contour map.
Three optimisers start at and take 50 steps each. Press play, then try the sliders.
| After 0 steps | w₁, w₂ | error |
|---|---|---|
| SGD | 1, 2 | 686 |
| Momentum | 1, 2 | 686 |
| Adam | 1, 2 | 686 |
Momentum uses the SGD learning rate too. The × marks the bottom, (4, 6).
Things to notice:
- SGD zig-zags. From the gradient is . With , the first step goes to , right across the valley. The next steps bounce back and forth while drifting along the floor.
- SGD can't fix this with a bigger . Push the slider to 0.025 or more and the bouncing grows instead of shrinking. Make 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 , , : 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 . Each step adds the new gradient to the old velocity, shrunk by a factor , then moves by the velocity:
This is momentum. The number (the momentum) is between 0 and 1. With it's plain SGD. A common choice is (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 , then , then into 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 , so the ball speeds up.
Worked example
How fast does momentum get on a steady slope?
Take and a gradient that stays at . Start with .
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 : , so . The step is then . Momentum behaves like SGD with a learning rate times bigger, but only in directions where the gradient keeps its sign.
Now let the gradient flip: The steady state alternates between and . It satisfies : the last step's , shrunk by , plus the new . So . With , that's : about half a plain SGD step.
So with , the same 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 for momentum is usually smaller than a good 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, and , both start at 1, and the loss is
The gradients are and , so 's gradient is always 100 times 's. Plain SGD with moves by , all the way to 0 in one step, and by . Any much bigger makes overshoot, so 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:
- , a running average of its gradient . This is momentum, written as an average.
- , a running average of its squared gradient . Its square root, , 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 , the step size is , and for it's :
PyTorch's defaults are and . So averages over roughly the last 10 gradients and over roughly the last 1,000.
The step divides one by the other:
The hats are a small fix explained next, and only stops a division by zero. Read it as "the average gradient, measured in units of its typical size". If every gradient of is 100 times 's, then is 100 times bigger and is 100 times bigger too. They cancel, and both weights take the same step.
Bias correction
and start at 0. After one step, : the average is dragged towards its starting 0, and is ten times too small. After one step, , a thousand times too small. Adam undoes this pull by dividing by how much weight the real gradients have had so far:
Here counts the steps. At , and , both exact. As grows, goes to 0 and the correction fades away.
Worked example
Two Adam steps by hand
Step 1. The gradients are and .
For : and . Corrected: and , so .
The step is , so 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.
| Quantity | weight a | weight b |
|---|---|---|
| g gradient | 100 | 1 |
| m average of g | 10 | 0.1 |
| v average of g² | 10 | 0.001 |
| m̂ m ÷ (1 − 0.9ᵗ) | 100 | 1 |
| v̂ v ÷ (1 − 0.999ᵗ) | 1.00e4 | 1 |
| Adam step α·m̂ ÷ √v̂ | 0.1 | 0.1 |
| SGD step (α = 0.01) would be α·g | 1 | 0.01 |
After this step: a = 0.9, b = 0.9
Things to notice:
- Each step is close to for both weights, while SGD's would be 1 for and 0.01 for .
- Without bias correction, the first step is 0.316, more than three times . is 10 times too small but is times too small, so their ratio is too big.
- The step shrinks as the weights near 0, because starts to lag behind the shrinking gradients. Adam's step is about 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 long, so it circles the bottom instead of settling. The fix is to make 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 of the way towards each new sample. With , you get the plain average. With a fixed , recent samples count more.
Adam's is exactly this, with fraction and sample . Unroll it after three steps:
Each older gradient counts 0.9 times as much as the next. The weights add up to , not 1, because the rest of the weight () still sits on the starting 0. Dividing by makes the weights add to 1. That is the bias correction: it turns back into a proper weighted average.
is the same with and fraction 0.001, so it remembers about 1,000 steps. That long memory makes 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 , without the momentum term .
- Adam (Kingma and Ba, 2014) combined RMSProp's with momentum's 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 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 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: , then . Some books scale the gradient by instead; PyTorch doesn't, unless you setdampening.torch.optim.Adam(params, lr=0.5)usesbetas=(0.9, 0.999)andeps=1e-8unless 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 makes fast progress early, while the weights are far from good. Near the end, a small lets them settle. So why keep it fixed?
A learning-rate schedule sets for each epoch (or each step). Three common shapes:
- Constant: no schedule.
- Step decay: multiply by a factor, such as 0.3, every so often. Here, every 50 epochs.
- Warm-up then cosine: start at a tenth of and rise in a straight line to the full 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 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 ; the bottom one is the mean training loss over each epoch.
Step 0 · epoch 0
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 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 rate | Schedule | First-epoch loss | Final training loss | Validation accuracy (last epoch) |
|---|---|---|---|---|
| 0.05 | constant | 0.59 | 0.320 | 91.5% |
| 0.05 | step decay | 0.59 | 0.182 | 96.0% |
| 0.05 | warm-up + cosine | 0.66 | 0.191 | 95.5% |
| 0.2 | constant | 1.22 | 0.367 | 84.5% |
| 0.2 | step decay | 1.22 | 0.308 | 90.5% |
| 0.2 | warm-up + cosine | 0.62 | 0.257 | 94.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:
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 valuesThis 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.
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 historyWhere 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_sizeandT_maxare all in epochs, so it's once per epoch. Big models often count in steps instead, and thenscheduler.step()goes inside the batch loop, right afteroptimizer.step().
Putting it together
Back to the valley, with everything from this lesson.
- SGD is limited by the steepest direction. With an error that bends 25 times more sharply across than along, any safe crawls along the floor.
- Momentum adds a velocity. Steady directions build up to times the speed; flip-flopping ones cancel. In the race it reaches the bottom first.
- Adam divides each weight's average gradient by its typical size, so every weight steps about , whatever its gradient's scale. It's the usual default for networks, where gradient sizes vary from weight to weight and layer to layer.
- A schedule lets start big and end small. Warm-up protects the first steps; decay lets the weights settle.
The course's template uses AdamW at 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 times the gradient, so it depends on the gradient's size. Adam's step is about itself. In the valley, SGD needs 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 . In long, narrow valleys it bounces across and crawls along.
- Momentum keeps a velocity . Steady directions speed up by about ; flip-flopping ones cancel.
- Adam keeps running averages (gradient) and (squared gradient) for every weight, corrects them for starting at 0, and steps by . Each weight moves about , whatever its gradient's size.
- A learning-rate schedule changes during training: warm up for a few epochs, then decay.
- PyTorch names in this lesson:
torch.optim.SGD(momentum=…),torch.optim.Adamandtorch.optim.AdamW,torch.optim.lr_scheduler.StepLR,LinearLR,CosineAnnealingLRandSequentialLR, andscheduler.step().