Skip to main content

Deep Learning 3

Optimizers in PyTorch

Colab link

Open In Colab

In class 2 we trained the MNIST MLP by writing the update by hand:

with torch.no_grad():
    for p in modelo.parameters():
        p -= eta * p.grad
        p.grad.zero_()

Today we’ll see that a PyTorch optimizer is exactly that: the object that applies the update. The advantage is that switching the update rule (SGD, momentum, Adam…) becomes a one-line change.

Plan

  1. torch.optim.SGD is the rule from class 2
  2. The zero_grad() → backward() → step() pattern, and why zero_grad exists
  3. Momentum and Adam on the 2D landscape from class 2
  4. SGD × momentum × Adam training on MNIST
  5. Sensitivity to the learning rate
  6. Back to the Universal Approximation Theorem: approximating any function
Code
import copy
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import datasets, transforms
from torch.utils.data import DataLoader


AZUL, LARANJA, VERDE, CINZA, TINTA = "#2a78d6", "#eb6834", "#1baf7a", "#898781", "#52514e"
plt.rcParams.update({
    "axes.spines.top": False, "axes.spines.right": False,
    "axes.edgecolor": CINZA, "axes.labelcolor": TINTA,
    "xtick.color": TINTA, "ytick.color": TINTA,
    "axes.grid": True, "grid.color": "#e6e5e1", "figure.dpi": 110,
})

torch.manual_seed(42)

treino = datasets.MNIST(root="data", train=True, download=True, transform=transforms.ToTensor())
teste = datasets.MNIST(root="data", train=False, download=True, transform=transforms.ToTensor())

def cria_mlp():
    return nn.Sequential(nn.Flatten(), nn.Linear(784, 128), nn.ReLU(), nn.Linear(128, 10))

def acuracia(modelo, dataset, n=10000):
    x, y = next(iter(DataLoader(dataset, batch_size=n)))
    with torch.no_grad():
        return (modelo(x).argmax(dim=1) == y).float().mean().item()

1. torch.optim.SGD is the rule from class 2

Let’s prove it: two identical copies of the network, the same batch of images. On copy A we apply the update by hand; on copy B we use torch.optim.SGD(..., lr=0.1). The resulting weights must be equal.

Code
torch.manual_seed(0)
modelo_a = cria_mlp()
modelo_b = copy.deepcopy(modelo_a)            # copy with the same weights
x_lote, y_lote = next(iter(DataLoader(treino, batch_size=64, shuffle=True)))
eta = 0.1

# A: update by hand (class 2)
F.cross_entropy(modelo_a(x_lote), y_lote).backward()
with torch.no_grad():
    for p in modelo_a.parameters():
        p -= eta * p.grad

# B: PyTorch optimizer
otimizador = torch.optim.SGD(modelo_b.parameters(), 
                             lr=eta
                             )
F.cross_entropy(modelo_b(x_lote), y_lote).backward()
otimizador.step()

iguais = all(torch.allclose(pa, pb) for pa, pb in zip(modelo_a.parameters(), modelo_b.parameters()))
print(f"Are the weights of the two networks equal after the update? {iguais}")
Os pesos das duas redes são iguais depois da atualização? True

The optimizer receives the list of parameters (modelo.parameters()) when it’s created. After that:

  • otimizador.step() applies the update rule to all of them, using each one’s .grad;
  • otimizador.zero_grad() zeroes all the .grads.

2. The training pattern

Every PyTorch training loop has these three lines, in this order:

otimizador.zero_grad()   # 1. clear the gradients from the previous step
perda.backward()         # 2. compute the new gradients
otimizador.step()        # 3. update the weights

Why do we need zero_grad()?

Because PyTorch accumulates (sums) gradients: each backward() adds to the existing .grad instead of replacing it. See what happens when we call backward() twice without zeroing:

Code
torch.manual_seed(0)
modelo = cria_mlp()
peso = modelo[1].weight                       # first layer weights

F.cross_entropy(modelo(x_lote), y_lote).backward()
grad_1 = peso.grad.clone()

F.cross_entropy(modelo(x_lote), y_lote).backward()      # same batch, without zeroing
grad_2 = peso.grad.clone()

print(f"after the 1st backward: sum |grad| = {grad_1.abs().sum():.4f}")
print(f"after the 2nd backward: sum |grad| = {grad_2.abs().sum():.4f}")
print(f"ratio: {grad_2.abs().sum() / grad_1.abs().sum():.2f}  (the gradient doubled!)")

otimizador = torch.optim.SGD(modelo.parameters(), lr=0.1)
otimizador.zero_grad()
print(f"\nafter zero_grad(): {peso.grad}")
depois do 1º backward: soma |grad| = 98.6423
depois do 2º backward: soma |grad| = 197.2846
razão: 2.00  (o gradiente dobrou!)

depois do zero_grad(): None

Without zero_grad(), each step would use the sum of all previous gradients: the steps would get bigger and bigger and point in stale directions. Training falls apart. (This accumulation is useful in one advanced case, gradient accumulation, to simulate batches too large for memory. That’s why PyTorch doesn’t zero them automatically.)

Momentum and Adam

In class 2, gradient descent zigzagged in the elongated valley. Modern optimizers change the update rule to deal with this.

SGD with momentum: a ball rolling downhill

Instead of using only the current step’s gradient, we accumulate a velocity \(v\), an average of recent gradients:

\[v \leftarrow \beta\, v + \nabla L(\theta) \qquad \theta \leftarrow \theta - \eta\, v\]

With \(\beta\) (typically 0.9), the components that change sign every step (the zigzag) cancel out, and those that always point the same way add up and accelerate.

Adam: one learning rate per parameter

Adam keeps two moving averages per parameter: that of the gradient \(m\) (like momentum) and that of the squared gradient \(s\). The update divides one by the other:

\[\theta \leftarrow \theta - \eta \, \frac{m}{\sqrt{s} + \epsilon}\]

Parameters with large gradients take smaller steps; parameters with small gradients take larger steps. In practice, each parameter has its own learning rate. Adam is the sensible default for starting any project (with lr=1e-3).

Comparing on the landscape from class 2

Same loss \(L(\theta_1, \theta_2) = \theta_1^2 + 25\,\theta_2^2\), same starting point and 60 steps of each optimizer. Here PyTorch’s optimizers update a tensor with 2 parameters, exactly as they would with a network’s weights.

Code
def perda_2d(t):
    return t[0] ** 2 + 25 * t[1] ** 2

def trajetoria(cria_otimizador, passos=60):
    theta = torch.tensor([-4.5, 1.0], requires_grad=True)
    otimizador = cria_otimizador([theta])
    caminho, perdas = [theta.detach().clone()], []
    for _ in range(passos):
        otimizador.zero_grad()
        perda = perda_2d(theta)
        perda.backward()
        otimizador.step()
        caminho.append(theta.detach().clone())
        perdas.append(perda.item())
    return torch.stack(caminho).numpy(), np.array(perdas)

configs_2d = {
    "SGD (η = 0.035)": (lambda p: torch.optim.SGD(p, lr=0.035), CINZA),
    "SGD + momentum (η = 0.02, β = 0.7)": (lambda p: torch.optim.SGD(p, lr=0.02, momentum=0.7), AZUL),
    "Adam (η = 0.2)": (lambda p: torch.optim.Adam(p, lr=0.2), LARANJA),
}
resultados_2d = {nome: trajetoria(f) for nome, (f, _) in configs_2d.items()}

T1, T2 = np.meshgrid(np.linspace(-5, 2, 300), np.linspace(-1.3, 1.3, 300))
fig, axes = plt.subplots(1, 2, figsize=(15, 4.5), width_ratios=[1.6, 1])
axes[0].contour(T1, T2, T1 ** 2 + 25 * T2 ** 2, levels=np.logspace(-1, 1.8, 12), colors=CINZA, linewidths=0.6, alpha=0.6)
for nome, (caminho, perdas) in resultados_2d.items():
    cor = configs_2d[nome][1]
    axes[0].plot(caminho[:, 0], caminho[:, 1], color=cor, marker="o", ms=3, lw=1.5, label=nome)
    axes[1].plot(perdas, color=cor, lw=2, label=nome)
axes[0].scatter(0, 0, marker="*", s=250, color=VERDE, zorder=3)
axes[0].set(xlabel="θ₁", ylabel="θ₂", title="Path of each optimizer (60 steps)")
axes[0].set_aspect("equal")
axes[0].grid(False)
axes[0].legend(frameon=False, loc="upper center", bbox_to_anchor=(0.5, -0.18), ncols=3)
axes[1].set(yscale="log", xlabel="step", ylabel="loss (log scale)", title="Loss over the steps")
plt.tight_layout()
plt.show()

for nome, (_, perdas) in resultados_2d.items():
    print(f"{nome:<36} loss after 20 steps = {perdas[19]:.3f}   after 60 = {perdas[-1]:.5f}")

SGD (η = 0,035)                      perda após 20 passos = 1.285   após 60 = 0.00387
SGD + momentum (η = 0,02, β = 0,7)   perda após 20 passos = 0.035   após 60 = 0.00000
Adam (η = 0,2)                       perda após 20 passos = 1.088   após 60 = 0.03307

Reading the plot:

  • SGD zigzags in the steep direction (\(\theta_2\)). We can’t increase η without diverging in that direction, and so it moves slowly in the flat direction (\(\theta_1\)).
  • Momentum also oscillates at first, but the oscillations quickly cancel out while velocity builds up in the flat direction: after 20 steps, its loss is already dozens of times lower than SGD’s.
  • Adam starts by moving diagonally: since it normalizes each parameter by the size of its own gradient, the first steps are the same size in both directions. On this simple landscape it’s not the fastest. Adam’s real advantage shows up in real networks, with thousands of parameters on different scales, and in its robustness to the choice of η, as we’ll see on MNIST.

SGD × momentum × Adam training on MNIST

Now the comparison that matters: the same MLP, the same initial weights, the same batches in the same order, 2 epochs for each optimizer. An epoch is one full pass through the 60 thousand training images (938 batches of 64).

Notice that the training loop is identical for all three: only the line that creates the optimizer changes.

Code
torch.manual_seed(0)
pesos_iniciais = cria_mlp().state_dict()     # all optimizers start from the same weights

def treina(cria_otimizador, epocas=2, seed=0):
    modelo = cria_mlp()
    modelo.load_state_dict(pesos_iniciais)
    otimizador = cria_otimizador(modelo.parameters())
    gerador = torch.Generator().manual_seed(seed)          # same batch order for all
    carregador = DataLoader(treino, batch_size=64, shuffle=True, generator=gerador)
    historico = []
    for _ in range(epocas):
        for x, y in carregador:
            otimizador.zero_grad()                         # 1
            perda = F.cross_entropy(modelo(x), y)
            perda.backward()                               # 2
            otimizador.step()                              # 3
            historico.append(perda.item())
    return modelo, np.array(historico)

configs_mnist = {
    "SGD (lr = 0.05)": (lambda p: torch.optim.SGD(p, lr=0.05), CINZA),
    "SGD + momentum (lr = 0.05, β = 0.9)": (lambda p: torch.optim.SGD(p, lr=0.05, momentum=0.9), AZUL),
    "Adam (lr = 0.001)": (lambda p: torch.optim.Adam(p, lr=1e-3), LARANJA),
}
resultados_mnist = {}
for nome, (cria_otimizador, _) in configs_mnist.items():
    modelo, historico = treina(cria_otimizador)
    resultados_mnist[nome] = (modelo, historico)
    print(f"{nome:<36} test accuracy = {acuracia(modelo, teste):.2%}")
SGD (lr = 0,05)                      acurácia no teste = 92.82%
SGD + momentum (lr = 0,05, β = 0,9)  acurácia no teste = 97.04%
Adam (lr = 0,001)                    acurácia no teste = 96.24%
Code
def suaviza(serie, janela=50):
    return np.convolve(serie, np.ones(janela) / janela, mode="valid")

fig, axes = plt.subplots(1, 2, figsize=(14, 4.5))
for nome, (_, historico) in resultados_mnist.items():
    cor = configs_mnist[nome][1]
    for ax in axes:
        ax.plot(np.arange(len(suaviza(historico))) + 49, suaviza(historico), color=cor, lw=2, label=nome)
lotes_por_epoca = len(historico) // 2
for ax in axes:
    ax.axvline(lotes_por_epoca, color=CINZA, ls=":", lw=1)
    ax.set(xlabel="step (batch of 64 images)", ylabel="cross-entropy (50-batch moving average)")
axes[0].set_title("Training loss: 2 epochs")
axes[0].text(lotes_por_epoca, axes[0].get_ylim()[1] * 0.95, " end of epoch 1", color=TINTA, fontsize=9, va="top")
axes[1].set(title="Zoom on the first 300 steps", xlim=(40, 300))
axes[1].legend(frameon=False)
plt.tight_layout()
plt.show()

Sensitivity to the learning rate

The comparison above depends on the η chosen for each optimizer. For a fair comparison, we train for 1 epoch with several learning rates and look at test accuracy. (This cell takes about 20 seconds.)

Code
taxas = [1e-4, 1e-3, 1e-2, 1e-1, 1.0]
otimizadores = {
    "SGD": lambda p, lr: torch.optim.SGD(p, lr=lr),
    "SGD + momentum": lambda p, lr: torch.optim.SGD(p, lr=lr, momentum=0.9),
    "Adam": lambda p, lr: torch.optim.Adam(p, lr=lr),
}
grade = pd.DataFrame(index=otimizadores, columns=[f"{lr:g}" for lr in taxas], dtype=float)
for nome, f in otimizadores.items():
    for lr in taxas:
        modelo, _ = treina(lambda p: f(p, lr), epocas=1)
        grade.loc[nome, f"{lr:g}"] = acuracia(modelo, teste)

fig, ax = plt.subplots(figsize=(9, 3.2))
im = ax.imshow(grade.values, cmap="Blues", vmin=0, vmax=1, aspect="auto")
for i in range(grade.shape[0]):
    for j in range(grade.shape[1]):
        v = grade.iloc[i, j]
        ax.text(j, i, f"{v:.0%}", ha="center", va="center", color="white" if v > 0.6 else TINTA, fontsize=11)
ax.set(xticks=range(len(taxas)), xticklabels=grade.columns, yticks=range(len(otimizadores)), yticklabels=grade.index,
       xlabel="learning rate (lr)", title="Test accuracy after 1 epoch")
ax.grid(False)
plt.colorbar(im, ax=ax, format=lambda v, _: f"{v:.0%}")
plt.show()

Reading the plot:

  • Each optimizer has its own good range of learning rates: plain SGD needs a large η (0.1 to 1), momentum works best with an η an order of magnitude smaller, and Adam does well between 0.001 and 0.01.
  • Adam is the most forgiving: it already exceeds 90% with η = 0.0001, while plain SGD stays close to a random guess.
  • Outside their range, they all fail: an η that’s too small doesn’t get anywhere in 1 epoch; one that’s too large diverges (Adam with lr = 1 stays at random-guess level).
  • The Adam(lr=1e-3) default works well “out of the box” on most problems. That’s why it’s the recommended starting point.

Back to the Universal Approximation Theorem

In class 1 we saw the theorem:

A network with one hidden layer and a non-linear activation approximates any continuous function on a bounded interval, as long as it has enough neurons.

There, the treina function was a black box. Now we know exactly what it does: it’s the zero_grad(), then backward(), then step() pattern with an optimizer. Let’s write a function aproxima that takes any function \(f(x)\) and tries to approximate it with a \(1 \to n \to 1\) ReLU network:

  1. we draw random points \(x\) in the interval and compute \(y = f(x)\): that’s our “dataset”;
  2. we create the network with \(n\) hidden neurons;
  3. we train with the MSE loss (regression, class 2) and whichever optimizer we like (this class).
Code
def aproxima(f, n_neuronios=64, intervalo=(-2, 2), passos=3000, n_pontos=500,
             cria_otimizador=lambda p: torch.optim.Adam(p, lr=0.01), seed=0):
    """Approximates any function f with a 1 → n_neuronios → 1 network (ReLU)."""
    torch.manual_seed(seed)
    x = torch.linspace(*intervalo, n_pontos).unsqueeze(1)       # (n_pontos, 1)
    y = f(x)
    rede = nn.Sequential(nn.Linear(1, n_neuronios), nn.ReLU(), nn.Linear(n_neuronios, 1))
    otimizador = cria_otimizador(rede.parameters())
    historico = []
    for _ in range(passos):
        otimizador.zero_grad()
        perda = F.mse_loss(rede(x), y)
        perda.backward()
        otimizador.step()
        historico.append(perda.item())
    return rede, np.array(historico)

Limit 1: it only holds inside the interval

The theorem talks about a bounded interval. Outside the training points, the network knows nothing about the function: with ReLU, it simply continues in a straight line.

Code
rede_sen, _ = aproxima(torch.sin, n_neuronios=256, intervalo=(-2 * np.pi, 2 * np.pi), passos=4000)

x_largo = torch.linspace(-4 * np.pi, 4 * np.pi, 800).unsqueeze(1)
fig, ax = plt.subplots(figsize=(12, 4))
ax.axvspan(-2 * np.pi, 2 * np.pi, color=AZUL, alpha=0.08, label="training interval")
ax.plot(x_largo, torch.sin(x_largo), color=CINZA, lw=5, alpha=0.4, label="sin(x)")
with torch.no_grad():
    ax.plot(x_largo, rede_sen(x_largo), color=LARANJA, lw=2, label="network (256 neurons)")
ax.set(xlabel="x", ylim=(-4, 4), title="Inside the training interval the network gets it right; outside, it extrapolates in a straight line")
ax.legend(frameon=False, loc="lower left", ncols=3)
plt.show()

Limit 2: a solution existing ≠ being able to find it

The theorem guarantees that weights approximating the function exist, but doesn’t say how to find them. The one doing the searching is the optimizer. Same network (256 neurons), same oscillating function, same initial weights and the same 3,000 steps, changing only the optimizer:

Code
f_dificil = funcoes["sin(3x) + 0.5·cos(7x)"]
configs_uat = {
    "SGD (lr = 0.01)": (lambda p: torch.optim.SGD(p, lr=0.01), CINZA),
    "SGD + momentum (lr = 0.01, β = 0.9)": (lambda p: torch.optim.SGD(p, lr=0.01, momentum=0.9), AZUL),
    "Adam (lr = 0.01)": (lambda p: torch.optim.Adam(p, lr=0.01), LARANJA),
}

fig, axes = plt.subplots(1, 2, figsize=(15, 4.5), width_ratios=[1.3, 1])
axes[0].plot(x_plot, f_dificil(x_plot), color=CINZA, lw=6, alpha=0.3, label="true function")
for nome, (cria_otimizador, cor) in configs_uat.items():
    rede, historico = aproxima(f_dificil, n_neuronios=256, cria_otimizador=cria_otimizador)
    with torch.no_grad():
        axes[0].plot(x_plot, rede(x_plot), color=cor, lw=2, label=nome)
    axes[1].plot(historico, color=cor, lw=2, label=nome)
    print(f"{nome:<38} MSE final = {historico[-1]:.5f}")
axes[0].set(xlabel="x", title="Same network, different optimizers")
axes[0].legend(frameon=False, loc="upper center", bbox_to_anchor=(0.5, -0.15), ncols=2)
axes[1].set(yscale="log", xlabel="step", ylabel="MSE (log scale)", title="Loss during training")
plt.tight_layout()
plt.show()
SGD (lr = 0,01)                        MSE final = 0.06749
SGD + momentum (lr = 0,01, β = 0,9)    MSE final = 0.01236
Adam (lr = 0,01)                       MSE final = 0.00265

The network is the same in all three cases: the capacity to represent the function is there. What changes is whether the optimizer can reach the right weights in 3,000 steps. That’s why the theorem alone isn’t enough: in practice, the choice of optimizer and learning rate decides whether the existing solution is found.

The spikes in Adam’s curve are normal with a relatively high learning rate: every now and then it takes a step that’s too big, the loss goes up, and it recovers right afterwards.

What about more dimensions?

The theorem holds for functions of several variables. We just change the input from 1 to 2 numbers: a \(2 \to 256 \to 1\) network approximating the surface \(f(x, y) = \sin(x)\cos(y)\).

Code
torch.manual_seed(0)
eixo = torch.linspace(-3, 3, 60)
X, Y = torch.meshgrid(eixo, eixo, indexing="xy")
entradas = torch.stack([X.flatten(), Y.flatten()], dim=1)       # (3600, 2): each row is a point (x, y)
alvo = (torch.sin(X) * torch.cos(Y)).flatten().unsqueeze(1)

rede_2d = nn.Sequential(nn.Linear(2, 256), nn.ReLU(), nn.Linear(256, 1))
otimizador = torch.optim.Adam(rede_2d.parameters(), lr=0.01)
for _ in range(3000):
    otimizador.zero_grad()
    perda = F.mse_loss(rede_2d(entradas), alvo)
    perda.backward()
    otimizador.step()

with torch.no_grad():
    previsto = rede_2d(entradas).reshape(60, 60)
real = alvo.reshape(60, 60)

fig, axes = plt.subplots(1, 3, figsize=(15, 4.5))
extensao = [-3, 3, -3, 3]
for ax, dados, titulo, cmap, lim in [
    (axes[0], real, "true function: sin(x)·cos(y)", "RdBu_r", 1),
    (axes[1], previsto, "network 2 → 256 → 1", "RdBu_r", 1),
    (axes[2], previsto - real, f"error (MSE = {perda.item():.5f})", "RdBu_r", 0.1),
]:
    im = ax.imshow(dados, extent=extensao, origin="lower", cmap=cmap, vmin=-lim, vmax=lim)
    ax.set(title=titulo, xlabel="x", ylabel="y")
    ax.grid(False)
    plt.colorbar(im, ax=ax, shrink=0.8)
plt.tight_layout()
plt.show()

Your turn: approximate any function

Replace minha_funcao with any function of x written with PyTorch operations (torch.sin, torch.exp, torch.abs, **, …), choose the number of neurons and the interval, and see how far the network gets.

Code
minha_funcao = lambda x: torch.sin(x ** 2) * torch.exp(-0.1 * x ** 2)   # ← change this
N_NEURONIOS = 128
INTERVALO = (-4, 4)

rede, historico = aproxima(minha_funcao, n_neuronios=N_NEURONIOS, intervalo=INTERVALO, passos=4000)

x_sua = torch.linspace(*INTERVALO, 800).unsqueeze(1)
fig, ax = plt.subplots(figsize=(11, 4))
ax.plot(x_sua, minha_funcao(x_sua), color=CINZA, lw=6, alpha=0.3, label="your function")
with torch.no_grad():
    ax.plot(x_sua, rede(x_sua), color=LARANJA, lw=2, label=f"network ({N_NEURONIOS} neurons)")
ax.set(xlabel="x", title=f"MSE final = {historico[-1]:.5f}")
ax.legend(frameon=False)
plt.show()

With 128 neurons and the interval \([-4, 4]\), the network gets the center right but misses the fast oscillations at the edges: there \(\sin(x^2)\) oscillates faster and faster and it runs out of “bends”. Try increasing N_NEURONIOS (or passos inside aproxima) and see what it takes to capture the edges.

7. Discussion

  • The optimizer is the object that applies the weight update. torch.optim.SGD is exactly the rule \(\theta \leftarrow \theta - \eta \nabla L\) from class 2.
  • Every PyTorch training loop follows the zero_grad() → backward() → step() pattern. zero_grad() is needed because PyTorch sums gradients on each backward().
  • Momentum accumulates a velocity that dampens the zigzag and accelerates in consistent directions.
  • Adam adapts the learning rate of each parameter. It’s the sensible default to start with.
  • The learning rate is still the most important hyperparameter, for any optimizer.
  • The Universal Approximation Theorem guarantees that a wide enough network can represent any continuous function on an interval; it’s the optimizer that decides whether that solution is found. Outside the training interval, the network knows nothing.

Exercises

  1. On the 2D landscape, increase SGD’s η to 0.045. What happens? Compute: what is the largest stable η in the \(\theta_2\) direction? (Hint: the gradient in that direction is \(50\,\theta_2\).)
  2. Try momentum with β = 0.99 on the 2D landscape. Why does the path get so “loose”?
  3. Replace Adam with torch.optim.AdamW and torch.optim.RMSprop on MNIST. Is either one better after 2 epochs?
  4. In section 2, instead of zeroing the gradients, divide them by 2 after the second backward(). What gradient do you get? That’s the idea behind gradient accumulation.
  5. In the “Your turn” cell, what is the smallest number of neurons that brings the MSE below 0.001 for the function \(\sin(3x) + 0.5\cos(7x)\)? And if you replace nn.ReLU() with nn.Tanh() inside aproxima?