Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Concept · 20 min · revision 2

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

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.

Python · valley.py
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}")
Terminal
python valley.py
Expected output
plain 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.7

Raising 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.

Python · momentum.py
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}")
Terminal
python momentum.py
Expected output
optimizer                    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.0008685

After 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.

Python · decay.py
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}")
Terminal
python decay.py
Expected output
Adam  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.9048

With 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.

Python · schedules.py
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))
Terminal
python schedules.py
Expected output
epoch:               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.0004

StepLR 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

Practice check · 3 questions

Steps and schedules

Use the scripts and outputs of this lesson.

Q1. In `decay.py`, the weight gets no gradient from the loss. After 100 steps with weight decay 0.1, Adam has moved it to 0.2244 but AdamW only to 0.9048. Why?
Q2. A loop calls `scheduler.step()` after every batch, but `CosineAnnealingLR(opt, T_max=30)` was written for 30 epochs of 17 batches each. What happens to the learning rate?
Q3. With the same learning rate of 0.03, SGD with momentum 0.9 reaches a loss of 0.0001 on the valley after 100 steps, plain SGD only 0.028. What does momentum add here?
Practice only: not graded, not saved, not evidence.

07. Apply it

Use the MLP from the training-loop lab for the practice project.

  1. Train it with AdamW at learning rates 1e-4, 1e-3 and 1e-2 for 30 epochs and plot the validation loss of each.
  2. Add a 3-epoch linear warm-up followed by cosine decay to the best rate, and compare the final validation loss.
  3. 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.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check