Optimizers, Learning Rates and Schedules
Watch the learning rate decide between slow progress, fast convergence and divergence on a narrow valley, see how momentum and Adam change the steps, measure why AdamW applies weight decay differently from Adam, and print the learning rate of step, cosine and warm-up schedules epoch by epoch.
Contentsand lesson path
On this page
- Why it matters
- The learning rate on a narrow valley
- Momentum and Adam
- Weight decay: Adam versus AdamW
- Learning-rate schedules
- Check your understanding
- Apply it
- Review prompt
Lessons of Deep Learning Fundamentals
- From Logistic Regression to a Neural Network Concept · 20 min
- Backpropagation and Autograd, Step by Step Worked example · 25 min
- Lab: Your First PyTorch Training Loop Lab · 30 min
- Optimizers, Learning Rates and Schedules Concept · 20 min
- Lab: Reading Loss Curves and Fixing a Broken Run Lab · 30 min
- Check: Why Did Training Fail? Knowledge check · 6 questions
What you will learn
- Implement a PyTorch training and evaluation loop for a multilayer perceptron with nn.Module, a DataLoader, a suitable loss and an optimizer such as SGD or AdamW.
- Diagnose training from loss and metric curves (underfitting, overfitting, divergence, vanishing or exploding gradients) and apply fixes such as learning-rate schedules, initialization, normalization, dropout, weight decay and early stopping.
Prerequisites: Machine Learning Fundamentals, Linear Algebra & Calculus for ML
01. Why it matters
The gradient tells the optimizer which way is downhill. Everything else is up to the optimizer: how far to step, whether to remember earlier steps, whether each weight gets its own step size, and how all of that changes during training. These choices often decide whether a run trains in minutes, crawls for hours or blows up.
This lesson uses a tiny problem you can see completely: a loss with two weights, shaped like a long, narrow valley. Real networks have millions of weights, but their loss surfaces have the same feature that makes optimisation hard: some directions are steep and others are almost flat. You need Python 3.12 and PyTorch 2. All four scripts run in about a second.
02. The learning rate on a narrow valley
The loss below is 0.5 × (w₀² + 25 w₁²). Along w₀ it is gentle (curvature 1), along w₁ it is 25 times steeper. Plain gradient descent multiplies each coordinate by (1 − lr × curvature) at every step. For the gentle direction with lr = 0.03 that factor is 0.97, so progress is slow. For the steep direction the factor goes below −1 once lr > 2 / 25 = 0.08: each step overshoots further than the last and the loss grows without limit. That is divergence. The largest stable learning rate is set by the steepest direction, while the speed of training is set by the flattest one.
import torch
CURVE = torch.tensor([1.0, 25.0]) # gentle along w[0], steep along w[1]
def loss_fn(w):
return 0.5 * (CURVE * w ** 2).sum()
def run(make_opt, steps):
w = torch.tensor([5.0, 1.0], requires_grad=True)
opt = make_opt([w])
for _ in range(steps):
opt.zero_grad()
loss_fn(w).backward()
opt.step()
return loss_fn(w).item()
if __name__ == "__main__":
print("plain SGD, 50 steps, start loss 25.0")
for lr in [0.01, 0.03, 0.07, 0.079, 0.081]:
final = run(lambda p: torch.optim.SGD(p, lr=lr), 50)
print(f" lr {lr:<5} final loss {final:.4g}")python valley.pyplain SGD, 50 steps, start loss 25.0
lr 0.01 final loss 4.575
lr 0.03 final loss 0.5944
lr 0.07 final loss 0.008815
lr 0.079 final loss 0.9973
lr 0.081 final loss 147.7Raising the rate from 0.01 to 0.07 cuts the final loss from 4.6 to 0.009. At 0.079 the steep direction is barely stable and oscillates (loss 1.0), and at 0.081, just past the limit, the loss climbs to 148. In a real network you cannot compute the limit, so you search for the learning rate on a log scale (for example 1e-4, 3e-4, 1e-3, 3e-3) and look at the first few hundred steps: a loss that jumps or turns into NaN means the rate is too high.
03. Momentum and Adam
Momentum keeps a running "velocity": a decaying sum of recent gradients, with a factor of 0.9 a common choice. Directions where the gradients keep pointing the same way build up speed, up to about 1 / (1 − 0.9) = 10 times the plain step, while directions where they flip back and forth cancel out. On a valley, that means faster travel along the floor without more bouncing across it.
Adam goes further and gives every weight its own step size. It keeps two running averages per weight: of the gradient (like momentum) and of the squared gradient. Dividing the first by the square root of the second makes the step roughly the same size, about lr, for every weight, whether its gradients are large or tiny. That makes Adam forgiving about scaling and a common default, especially for large networks.
import torch
from valley import run
optimizers = {
"SGD, lr 0.03": lambda p: torch.optim.SGD(p, lr=0.03),
"SGD + momentum 0.9, lr 0.03": lambda p: torch.optim.SGD(p, lr=0.03, momentum=0.9),
"Adam, lr 0.1": lambda p: torch.optim.Adam(p, lr=0.1),
}
print(f"{'optimizer':<28} {'loss after 20':>13} {'after 100':>10}")
for name, make in optimizers.items():
print(f"{name:<28} {run(make, 20):13.4g} {run(make, 100):10.4g}")python momentum.pyoptimizer loss after 20 after 100
SGD, lr 0.03 3.696 0.02827
SGD + momentum 0.9, lr 0.03 3.386 0.0001123
Adam, lr 0.1 5.602 0.0008685After 20 steps the three are close. After 100, momentum is about 250 times lower than plain SGD with the same rate, because the gentle direction has gathered speed. Adam with lr 0.1 also gets far below plain SGD, without anyone tuning the rate for the steep direction. Neither result is a ranking of optimizers in general: on real networks, well-tuned SGD with momentum and Adam-type optimizers are both widely used, and the learning rate usually matters more than the choice between them.
04. Weight decay: Adam versus AdamW
Weight decay pulls every weight a little towards zero at each step. It is a regulariser, a fix for overfitting: smaller weights give a smoother function that relies less on any single input. In plain SGD, decay is the same as adding an L2 penalty λw²/2 to the loss. In Adam it is not, and the difference is easy to measure. torch.optim.Adam(weight_decay=…) adds λw to the gradient, so the decay then passes through Adam's per-weight scaling. AdamW applies the decay directly to the weight, separately from the gradient step: w ← w − lr × λ × w. This is called decoupled weight decay.
import torch
# A weight that the loss does not use at all: its loss gradient is always 0,
# so only weight decay can move it.
for name, cls in [("Adam ", torch.optim.Adam), ("AdamW", torch.optim.AdamW)]:
w = torch.tensor([1.0], requires_grad=True)
opt = cls([w], lr=0.01, weight_decay=0.1)
for step in range(1, 101):
opt.zero_grad()
(0.0 * w).sum().backward()
opt.step()
if step in (1, 10, 100):
print(f"{name} step {step:3d}: w = {w.item():.4f}")python decay.pyAdam step 1: w = 0.9900
Adam step 10: w = 0.9003
Adam step 100: w = 0.2244
AdamW step 1: w = 0.9990
AdamW step 10: w = 0.9900
AdamW step 100: w = 0.9048With AdamW the unused weight shrinks by a factor of (1 − 0.01 × 0.1) per step, to 0.9048 after 100 steps, the same gentle pull every weight gets. With Adam, the only gradient is the decay term, and Adam's scaling turns even that small gradient into a step of about lr: the weight drops to 0.99 after one step and to 0.22 after 100. So under Adam, weights with small loss gradients are decayed much harder than weights with large ones. AdamW keeps decay and gradient steps independent, which is why it is the usual choice when you want weight decay with an adaptive optimizer.
05. Learning-rate schedules
A learning-rate schedule changes the rate during training. Early on, large steps make fast progress; later, mini-batch noise keeps the weights jittering around the minimum, and smaller steps let them settle. StepLR divides the rate by 10 at fixed epochs. Cosine annealing lowers it smoothly along a cosine curve. Warm-up starts small and ramps up over the first epochs or steps, which protects the start of training, when Adam's running averages are still based on very few gradients and a large step can throw the weights off. A scheduler is stepped after the optimizer, usually once per epoch, and its T_max or step_size count those steps.
import torch
from torch.optim.lr_scheduler import CosineAnnealingLR, LinearLR, SequentialLR, StepLR
def lrs(make_scheduler, epochs=30):
opt = torch.optim.SGD([torch.zeros(1, requires_grad=True)], lr=0.1)
sched = make_scheduler(opt)
values = []
for _ in range(epochs):
values.append(opt.param_groups[0]["lr"]) # the rate used in this epoch
opt.step() # (training would happen here)
sched.step() # once per epoch, after the updates
return values
def warmup_cosine(opt):
warm = LinearLR(opt, start_factor=0.1, total_iters=5)
return SequentialLR(opt, [warm, CosineAnnealingLR(opt, T_max=25)], milestones=[5])
show = [0, 1, 4, 5, 10, 15, 20, 25, 29]
print("epoch: " + " ".join(f"{e:>6}" for e in show))
for name, make in [("StepLR", lambda o: StepLR(o, step_size=10, gamma=0.1)),
("cosine", lambda o: CosineAnnealingLR(o, T_max=30)),
("warm-up+cosine", warmup_cosine)]:
v = lrs(make)
print(f"{name:<15} " + " ".join(f"{v[e]:6.4f}" for e in show))python schedules.pyepoch: 0 1 4 5 10 15 20 25 29
StepLR 0.1000 0.1000 0.1000 0.1000 0.0100 0.0100 0.0010 0.0010 0.0010
cosine 0.1000 0.0997 0.0957 0.0933 0.0750 0.0500 0.0250 0.0067 0.0003
warm-up+cosine 0.0100 0.0280 0.0820 0.1000 0.0905 0.0655 0.0345 0.0095 0.0004StepLR drops in jumps at epochs 10 and 20. Cosine starts at 0.1, is at half the rate at epoch 15 and almost zero at the end. The combined schedule rises from 0.01 to 0.1 in five epochs, then follows a cosine over the remaining 25. If you step a scheduler per batch instead, its counts must be in batches too: T_max=30 would then mean 30 batches, after which the cosine rises again.
06. Check your understanding
07. Apply it
Use the MLP from the training-loop lab for the practice project.
- Train it with AdamW at learning rates 1e-4, 1e-3 and 1e-2 for 30 epochs and plot the validation loss of each.
- Add a 3-epoch linear warm-up followed by cosine decay to the best rate, and compare the final validation loss.
- Write down the rate and schedule you would keep, and the evidence for it from the curves.
08. Review prompt
Without looking back, explain what limits the largest stable learning rate and what limits the speed of training on a narrow valley; describe what momentum keeps and what Adam keeps for each weight; explain how AdamW applies weight decay differently from Adam and why it matters; and sketch the learning rate over time for StepLR, cosine and warm-up plus cosine.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.