Skip to content

MLDay 34 of 50Deep Learning

Optimizers and Learning-Rate Schedules

9 min read

Plain gradient descent trains Day 33's clothing classifier, but slowly: after 10 epochs it labels only 72% of the validation images right. Change the optimizer and let the learning rate shrink as training goes, and the same network reaches 88% in the same 10 epochs.

The idea

SGD (stochastic gradient descent) is the update from D09, with each step's gradient computed on one mini-batch (D32). Each step looks only at the slope right where it stands. On a gentle slope it crawls. In a narrow valley it zig-zags from wall to wall. In a small dip it stops.

Momentum gives the walk a memory. It keeps a velocity: a running total of recent gradients, where older ones fade by a factor β\beta each step. The weights move along the velocity. Gradients that keep pointing the same way add up, so the steps grow. Gradients that flip back and forth cancel, so the zig-zag calms down. Like a ball rolling downhill, the walk can coast over a small bump.

Adam keeps a second memory for each weight: the typical size of its recent gradients. It divides each step by that size, so every weight moves about η\eta per step, whether its gradient is tiny or huge. AdamW is Adam plus weight decay, a small pull of every weight toward 0 (D36). It's a common default for neural networks.

The learning rate matters as much as the optimizer. A learning-rate sweep trains briefly at rates 10× apart and keeps the largest one that trains steadily. A schedule then changes the rate during training: big steps early cover ground fast, and small steps late settle into the bottom instead of bouncing around it. The cosine schedule lowers the rate along half a cosine wave, from its start value down to 0.

A tiny example

Walk down a long, straight slope where the gradient is 1 at every step. Use η=0.1\eta = 0.1 and β=0.9\beta = 0.9. At step 4 the walk hits a small bump, and the slope flips to −1.

Step Gradient gg SGD moves Velocity vv Momentum moves
1 1 0.1 downhill 1 0.1 downhill
2 1 0.1 downhill 0.9 × 1 + 1 = 1.9 0.19 downhill
3 1 0.1 downhill 0.9 × 1.9 + 1 = 2.71 0.271 downhill
4 (bump) −1 0.1 back 0.9 × 2.71 − 1 = 1.439 0.144 downhill

After three steps, momentum has covered 0.561 to SGD's 0.3, and its steps keep growing toward 10× SGD's. At the bump, SGD backs up, while momentum keeps rolling forward.

The formula

Momentum updates the velocity, then steps along it (PyTorch's form):

vt=β vt−1+gt,w←w−η vtv_t = \beta\, v_{t-1} + g_t, \qquad w \leftarrow w - \eta\, v_t
Symbol Meaning
vtv_t the velocity after step tt; it starts at 0
β\beta how much of the old velocity survives each step ("beta"); 0.9 is typical
gtg_t the gradient from this step's mini-batch
η\eta the learning rate
ww one weight

Worked: β=0.9\beta = 0.9, an old velocity vt−1=1v_{t-1} = 1 and a gradient gt=0.5g_t = 0.5 give vt=0.9×1+0.5=1.4v_t = 0.9 \times 1 + 0.5 = 1.4.

The cosine schedule sets the learning rate for each epoch:

ηt=η02(1+cos⁡πtT)\eta_t = \frac{\eta_0}{2}\left(1 + \cos\frac{\pi t}{T}\right)
Symbol Meaning
η0\eta_0 the starting learning rate
tt the epochs finished so far: 0, 1, 2, …
TT the total number of epochs (T_max in PyTorch)
ηt\eta_t the learning rate for the next epoch

Worked: η0=0.01\eta_0 = 0.01 and T=10T = 10. Halfway, at t=5t = 5, cos⁡(π/2)=0\cos(\pi/2) = 0, so η5=0.005\eta_5 = 0.005. The last epoch (t=9t = 9) uses about 0.00024.

Try it

Race three optimizers down a bumpy loss

Each step moves w against the slope: w ← w − η·dL/dw. Pick a learning rate η and take steps toward the lowest point, w* = 3. This loss has small dips that can trap a path.

-50510020406080weight wloss Llocal minw*local minSGD: w = -4, L = 51.322Momentum: w = -4, L = 51.322Adam: w = -4, L = 51.322
Changing η starts again from w = -4.
  • SGD: step 0, w = -4, L = 51.322, stuck in a local minimum's valley, w ≈ 1.21 (L = 3.79)
  • Momentum (β = 0.9): step 0, w = -4, L = 51.322, stuck in a local minimum's valley, w ≈ 1.21 (L = 3.79)
  • Adam: step 0, w = -4, L = 51.322, stuck in a local minimum's valley, w ≈ 1.21 (L = 3.79)
0510152002040steploss L

At η=0.05\eta = 0.05, press Run 20 four times. SGD stops in the dip at w≈1.21w \approx 1.21 for good; Momentum swings past it and settles near w∗=3w^* = 3; Adam crawls about 0.04 per step and is still at −0.64. Then set η\eta to 0.3 and run 80 steps again: Adam reaches w∗w^*, but Momentum now carries too much speed and swings from one side to the other, and SGD now jumps out of the dip but bounces around w∗w^*.

In code

This is the D33 MLP on the Fashion-MNIST slice, with the course's split and seeds. Every run starts from the same weights and sees the batches in the same order, so only the optimizer differs.

# script_id: day_034_optimizers_and_schedules/optimizers
import os
from pathlib import Path

import numpy as np
import torch
from sklearn.model_selection import train_test_split
from torch import nn
from torch.utils.data import DataLoader, TensorDataset

DATA_DIR = Path(os.environ.get("ML_DATA", "datasets"))
data = np.load(DATA_DIR / "fashion_mnist" / "fashion_mnist_slice.npz")
X = data["X_train"].astype(np.float32) / 255
X_tr, X_val, y_tr, y_val = train_test_split(X, data["y_train"], test_size=1000,
                                            stratify=data["y_train"], random_state=42)
X_tr, X_val, y_tr, y_val = (torch.tensor(a) for a in (X_tr, X_val, y_tr, y_val))
y_tr, y_val = y_tr.long(), y_val.long()


def train(make_optimizer, epochs=10, cosine=False):
    torch.manual_seed(42)                                    # same starting weights every run
    model = nn.Sequential(nn.Flatten(), nn.Linear(784, 128), nn.ReLU(), nn.Linear(128, 10))
    opt = make_optimizer(model.parameters())
    sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, T_max=epochs) if cosine else None
    loader = DataLoader(TensorDataset(X_tr, y_tr), batch_size=64, shuffle=True,
                        generator=torch.Generator().manual_seed(42))  # same batch order every run
    loss_fn, curve = nn.CrossEntropyLoss(), []
    for _ in range(epochs):
        model.train()
        total = 0.0
        for xb, yb in loader:
            loss = loss_fn(model(xb), yb)
            opt.zero_grad()
            loss.backward()
            opt.step()
            total += loss.item() * len(yb)
        curve.append(total / len(y_tr))                      # this epoch's average training loss
        if sched:
            sched.step()                                     # lower the learning rate, once per epoch
    model.eval()
    with torch.no_grad():
        logits = model(X_val)
    return curve, loss_fn(logits, y_val).item(), (logits.argmax(1) == y_val).float().mean().item()


optimizers = {
    "SGD": lambda p: torch.optim.SGD(p, lr=0.01),
    "SGD + momentum": lambda p: torch.optim.SGD(p, lr=0.01, momentum=0.9),
    "AdamW": lambda p: torch.optim.AdamW(p, lr=0.001),      # weight_decay=0.01 by default
}
curves = {}
for name, make in optimizers.items():
    curves[name], val_loss, val_acc = train(make)
    print(f"{name:14}  train loss {curves[name][0]:.3f} -> {curves[name][-1]:.3f}   "
          f"val loss {val_loss:.3f}, acc {val_acc:.3f}")
SGD             train loss 2.112 -> 0.807   val loss 0.784, acc 0.723
SGD + momentum  train loss 1.399 -> 0.450   val loss 0.496, acc 0.811
AdamW           train loss 1.037 -> 0.380   val loss 0.427, acc 0.837

At the same learning rate of 0.01, momentum reaches in 2 epochs a training loss that plain SGD doesn't reach in 10. AdamW's validation loss of 0.427 matches Day 33's Adam: the small default weight decay barely changes this run. The chart overlays the three curves:

# script_id: day_034_optimizers_and_schedules/optimizers
import matplotlib.pyplot as plt

FIG_DIR = Path(os.environ.get("ML_FIG_DIR", "figures"))
FIG_DIR.mkdir(exist_ok=True)
fig, ax = plt.subplots(figsize=(6, 4))
for name, curve in curves.items():
    ax.plot(range(1, len(curve) + 1), curve, marker="o", label=name)
ax.set(xlabel="epoch", ylabel="training loss (cross-entropy)",
       title="Momentum and AdamW train far faster than plain SGD")
ax.legend()
fig.tight_layout()
fig.savefig(FIG_DIR / "optimizer_race.png", dpi=120)
plt.close(fig)

Momentum and AdamW train far faster than plain SGD

Now a learning-rate sweep for AdamW, 3 epochs per rate, then the best rate with and without a cosine schedule:

# script_id: day_034_optimizers_and_schedules/optimizers
for lr in [0.0001, 0.001, 0.01, 0.1, 1.0]:                  # rates 10x apart
    curve, val_loss, _ = train(lambda p: torch.optim.AdamW(p, lr=lr), epochs=3)
    print(f"AdamW lr {lr:<6}  train loss after 3 epochs {curve[-1]:.3f}   val loss {val_loss:.3f}")
for cosine in [False, True]:
    _, val_loss, val_acc = train(lambda p: torch.optim.AdamW(p, lr=0.01), cosine=cosine)
    print(f"AdamW lr 0.01, {'cosine  ' if cosine else 'constant'}  val loss {val_loss:.3f}, acc {val_acc:.3f}")
AdamW lr 0.0001  train loss after 3 epochs 1.068   val loss 0.973
AdamW lr 0.001   train loss after 3 epochs 0.552   val loss 0.514
AdamW lr 0.01    train loss after 3 epochs 0.466   val loss 0.482
AdamW lr 0.1     train loss after 3 epochs 1.540   val loss 1.510
AdamW lr 1.0     train loss after 3 epochs 2.077   val loss 2.057
AdamW lr 0.01, constant  val loss 0.469, acc 0.820
AdamW lr 0.01, cosine    val loss 0.370, acc 0.877

The sweep picks 0.01: 0.0001 crawls, and 0.1 and up wreck the network. Held constant, 0.01 keeps bouncing around the bottom, and the 10th epoch lands at 0.820. The cosine schedule takes the same big early steps, then small ones, and reaches the best result here: 0.877.

Quick check

Quick check

1. With β = 0.9, the velocity is v = 2. The next gradient is g = −1 (a bump). What is the new velocity?

2. A 3-epoch sweep gives validation losses 0.97 (lr 0.0001), 0.51 (0.001), 0.48 (0.01) and 1.51 (0.1). Which rate do you start from?

3. Why does a cosine schedule help at the end of training?

Next

D35: Keep Deep Nets Trainable stacks ten layers, and shows why no optimizer can train a network whose gradients vanish before they reach the first layer.

Data: Fashion-MNIST (Zalando Research), MIT licence; cite Xiao, H., Rasul, K. and Vollgraf, R. (2017), "Fashion-MNIST: a Novel Image Dataset for Benchmarking Machine Learning Algorithms", arXiv:1708.07747.

Next · Day 35 · 9 minKeep Deep Nets Trainable← Previous: Day 33 · Losses, Logits and Softmax
Not tapped yet