Skip to main content

Deep Learning 4

The minimum requirements for a training pipeline

Colab link

Open In Colab

In classes 1 to 3 we saw each piece separately: the network (function), the loss, backward() and the optimizer. Today we assemble the complete pipeline, from raw data to a trained and evaluated model, the way it’s done in real projects:

  1. Dataset and DataLoader: how PyTorch feeds data to the network
  2. Training, validation and test: what each one is for
  3. The training loop and the evaluation loop in plain PyTorch
  4. A first look at overfitting
  5. Final evaluation on the test set
  6. The same pipeline with PyTorch Lightning, hiding nothing
Code
# on Google Colab, PyTorch comes preinstalled; Lightning doesn't
import sys
if "google.colab" in sys.modules:
    !pip install -q lightning
Code
import time
import warnings
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 torch.utils.data import Dataset, DataLoader, Subset, random_split
from torchvision import datasets, transforms
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay

# chart colors and style (the same as in the Machine Learning classes)
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)

# the CPU is faster than the Mac GPU (MPS) for such a small network; on Colab with a GPU, we use CUDA
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
DEVICE
'cpu'

1. Dataset: how to get one sample

A PyTorch Dataset is any object that can answer two questions:

  • __len__: how many samples are there?
  • __getitem__(i): what is sample number i? (returns the input and the label)

That’s it. To understand it, let’s write our own Dataset from MNIST’s raw arrays (images as uint8, from 0 to 255):

Code
mnist_bruto = datasets.MNIST(root="data", train=True, download=True)
print(f"images: {tuple(mnist_bruto.data.shape)} {mnist_bruto.data.dtype}   labels: {tuple(mnist_bruto.targets.shape)}")

class DigitosDataset(Dataset):
    def __init__(self, imagens, rotulos):
        self.imagens = imagens          # (N, 28, 28), uint8 from 0 to 255
        self.rotulos = rotulos          # (N,)

    def __len__(self):
        return len(self.rotulos)

    def __getitem__(self, i):
        x = self.imagens[i].float().div(255).unsqueeze(0)   # (1, 28, 28), float from 0 to 1
        y = self.rotulos[i]
        return x, y

meu_dataset = DigitosDataset(mnist_bruto.data, mnist_bruto.targets)
x0, y0 = meu_dataset[0]
print(f"len = {len(meu_dataset)}   sample 0: x {tuple(x0.shape)}, y = {y0.item()}")
imagens: (60000, 28, 28) torch.uint8   rótulos: (60000,)
len = 60000   amostra 0: x (1, 28, 28), y = 5

The torchvision datasets.MNIST we used in previous classes is exactly this: a class with __len__ and __getitem__, plus downloading and the transform (ToTensor() does the same 0–255 to 0–1 conversion). From here on we use the ready-made version:

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

x_tv, y_tv = treino_completo[0]
print(f"same sample? {torch.equal(x_tv, x0) and y_tv == y0.item()}")
mesma amostra? True

2. DataLoader: batching and shuffling

The Dataset delivers one sample at a time; the DataLoader groups several into a batch and, if we ask, shuffles the order every epoch. Shuffling keeps the network from always seeing the same sequence (for example, all the “0”s together), which would hurt stochastic gradient descent.

Code
carregador = DataLoader(treino_completo, batch_size=64, shuffle=True)
x_lote, y_lote = next(iter(carregador))
print(f"one batch: x {tuple(x_lote.shape)}   y {tuple(y_lote.shape)}")
print(f"batches per epoch: {len(carregador)}  (60000 / 64, rounded up)")

print(f"\nlabels of the 1st batch, 1st time:  {next(iter(carregador))[1][:12].tolist()}")
print(f"labels of the 1st batch, 2nd time:  {next(iter(carregador))[1][:12].tolist()}   a new order every epoch")
um lote: x (64, 1, 28, 28)   y (64,)
lotes por época: 938  (60000 / 64, arredondado para cima)

rótulos do 1º lote, 1ª vez:  [9, 3, 7, 7, 2, 6, 0, 8, 9, 7, 5, 0]
rótulos do 1º lote, 2ª vez:  [2, 7, 1, 0, 5, 0, 3, 5, 9, 3, 0, 2]   nova ordem a cada epoch

3. Training, validation and test

Set Size What it’s for How often we use it
Training 50,000 fitting the weights (backward() + step()) every step
Validation 10,000 monitoring training and choosing hyperparameters (lr, number of epochs, network size) every epoch
Test 10,000 estimating performance on new data only once, at the end

If we choose hyperparameters by looking at the test set, it stops being “new data” and the score becomes optimistic (the same data leakage idea from the supervised ML class).

MNIST already comes with a separate test set (10 thousand images). We split the 60 thousand training images into 50 thousand + 10 thousand with random_split. A random split is fine here because the images are independent of each other. In the beach water quality class, with temporal data, we had to split by time.

Code
gerador = torch.Generator().manual_seed(42)        # reproducible split
treino, validacao = random_split(treino_completo, [50000, 10000], generator=gerador)

carregador_treino = DataLoader(treino, batch_size=64, shuffle=True, generator=torch.Generator().manual_seed(0))
carregador_val = DataLoader(validacao, batch_size=1000)     # no shuffling: order doesn't matter for evaluation
carregador_teste = DataLoader(teste, batch_size=1000)

print(f"train: {len(treino)}   validation: {len(validacao)}   test: {len(teste)}")
treino: 50000   validação: 10000   teste: 10000

4. The training loop in plain PyTorch

Two functions, which we’ll reuse until the end of the class:

  • treina_uma_epoca (train one epoch): for each batch, forward -> loss -> backward -> step (the pattern from class 3).
  • avalia (evaluate): computes loss and accuracy without training. Two new lines:
    • modelo.eval() puts the network in evaluation mode (it turns off layers that behave differently during training, like Dropout and BatchNorm; our MLP has none, but it’s a mandatory habit). modelo.train() goes back to training mode.
    • torch.no_grad() turns off autograd: we won’t call backward(), so we don’t need to record the operations. It’s faster and uses less memory.
Code
def cria_mlp(escondida=128):
    return nn.Sequential(nn.Flatten(), nn.Linear(784, escondida), nn.ReLU(), nn.Linear(escondida, 10))


def treina_uma_epoca(modelo, carregador, otimizador):
    modelo.train()                                   # training mode
    soma_perda, acertos, total = 0.0, 0, 0
    for x, y in carregador:                          # for each batch...
        x, y = x.to(DEVICE), y.to(DEVICE)
        logits = modelo(x)                           # 1. forward
        perda = F.cross_entropy(logits, y)           # 2. loss
        otimizador.zero_grad()                       # 3. zero the gradients
        perda.backward()                             # 4. backward
        otimizador.step()                            # 5. update the weights
        soma_perda += perda.item() * len(y)
        acertos += (logits.argmax(dim=1) == y).sum().item()
        total += len(y)
    return soma_perda / total, acertos / total


@torch.no_grad()                                     # turn off autograd for the whole function
def avalia(modelo, carregador):
    modelo.eval()                                    # evaluation mode
    soma_perda, acertos, total = 0.0, 0, 0
    for x, y in carregador:
        x, y = x.to(DEVICE), y.to(DEVICE)
        logits = modelo(x)
        soma_perda += F.cross_entropy(logits, y, reduction="sum").item()
        acertos += (logits.argmax(dim=1) == y).sum().item()
        total += len(y)
    return soma_perda / total, acertos / total
Code
torch.manual_seed(0)
modelo = cria_mlp().to(DEVICE)
otimizador = torch.optim.Adam(modelo.parameters(), lr=1e-3)
EPOCAS = 5

historico = []
inicio = time.time()
for epoca in range(1, EPOCAS + 1):                   # for each epoch...
    perda_tr, acc_tr = treina_uma_epoca(modelo, carregador_treino, otimizador)
    perda_val, acc_val = avalia(modelo, carregador_val)
    historico.append({"época": epoca, "perda treino": perda_tr, "perda validação": perda_val,
                      "acurácia treino": acc_tr, "acurácia validação": acc_val})
    print(f"epoch {epoca}: train loss = {perda_tr:.3f}  val loss = {perda_val:.3f}  "
          f"train acc = {acc_tr:.2%}  val acc = {acc_val:.2%}")
print(f"\ntotal time: {time.time() - inicio:.0f} s")
historico = pd.DataFrame(historico).set_index("época")
época 1: perda treino = 0.364  perda val = 0.220  acc treino = 90.32%  acc val = 93.57%
época 2: perda treino = 0.172  perda val = 0.159  acc treino = 95.04%  acc val = 95.23%
época 3: perda treino = 0.122  perda val = 0.137  acc treino = 96.42%  acc val = 96.13%
época 4: perda treino = 0.093  perda val = 0.115  acc treino = 97.26%  acc val = 96.46%
época 5: perda treino = 0.075  perda val = 0.112  acc treino = 97.78%  acc val = 96.52%

tempo total: 5 s
Code
def plota_curvas(hist, titulo, marca=None):
    fig, axes = plt.subplots(1, 2, figsize=(13, 4))
    for ax, metrica in zip(axes, ["perda", "acurácia"]):
        ax.plot(hist.index, hist[f"{metrica} treino"], color=AZUL, lw=2, marker="o", ms=4, label="train")
        ax.plot(hist.index, hist[f"{metrica} validação"], color=LARANJA, lw=2, marker="o", ms=4, label="validation")
        if marca is not None:
            ax.axvline(marca, color=CINZA, ls="--", lw=1)
        ax.set(xlabel="epoch", title=metrica.capitalize())
        ax.xaxis.set_major_locator(plt.MaxNLocator(integer=True))
    axes[1].yaxis.set_major_formatter(lambda v, _: f"{v:.0%}")
    axes[0].legend(frameon=False)
    plt.suptitle(titulo, y=1.02)
    plt.tight_layout()
    plt.show()

plota_curvas(historico, "MLP 784 → 128 → 10, Adam, 50 thousand training images")

The two curves move together: the network improves on the training data and on data it didn’t use to fit the weights. That’s healthy behavior.

Why is validation better than training in epoch 1? The training loss is the average over the epoch, including the first batches, when the network was still guessing. Validation is measured at the end of the epoch, with the network already trained on that whole epoch.

5. A first look at overfitting

What happens if the network is large and the training data is scarce? Let’s train a much bigger network (784 -> 512 -> 10, with ~407 thousand parameters) on only 1,000 training images, for 60 epochs. Validation still uses the same 10 thousand images.

Code
poucas = Subset(treino, range(1000))
carregador_poucas = DataLoader(poucas, batch_size=64, shuffle=True, generator=torch.Generator().manual_seed(0))

torch.manual_seed(0)
modelo_grande = cria_mlp(escondida=512).to(DEVICE)
print(f"parameters: {sum(p.numel() for p in modelo_grande.parameters()):,} for {len(poucas)} training images")
otimizador_grande = torch.optim.Adam(modelo_grande.parameters(), lr=1e-3)

hist_overfit = []
for epoca in range(1, 61):
    perda_tr, acc_tr = treina_uma_epoca(modelo_grande, carregador_poucas, otimizador_grande)
    perda_val, acc_val = avalia(modelo_grande, carregador_val)
    hist_overfit.append({"época": epoca, "perda treino": perda_tr, "perda validação": perda_val,
                         "acurácia treino": acc_tr, "acurácia validação": acc_val})
hist_overfit = pd.DataFrame(hist_overfit).set_index("época")

melhor_epoca = hist_overfit["perda validação"].idxmin()
print(f"lowest validation loss at epoch {melhor_epoca}: {hist_overfit.loc[melhor_epoca, 'perda validação']:.3f}")
print(f"epoch 60: train loss = {hist_overfit['perda treino'].iloc[-1]:.4f}   validation loss = {hist_overfit['perda validação'].iloc[-1]:.3f}")
print(f"epoch 60: train accuracy = {hist_overfit['acurácia treino'].iloc[-1]:.1%}   validation accuracy = {hist_overfit['acurácia validação'].iloc[-1]:.1%}")
parâmetros: 407,050 para 1000 imagens de treino
menor perda de validação na época 11: 0.386
época 60: perda treino = 0.0014   perda validação = 0.486
época 60: acurácia treino = 100.0%   acurácia validação = 89.6%
Code
plota_curvas(hist_overfit, f"Overfitting: large network, only 1,000 training images (dashed line = epoch {melhor_epoca})",
             marca=melhor_epoca)

This is overfitting:

  • the training loss drops to almost zero and training accuracy reaches 100%: the network memorized the 1,000 images;
  • the validation loss stops falling (dashed line) and then rises: the network becomes more and more confident in answers that don’t generalize;
  • validation accuracy plateaus at ~90%, well below the ~97% from section 4: with 1,000 images the network doesn’t have enough examples to generalize, however big it is.

Without a validation set, we’d only see the blue curve and think the model was great. Validation shows when to stop (the idea behind early stopping). Other weapons against overfitting: more data, smaller networks and regularization (dropout, weight decay), which we’ll see later.

6. Final evaluation on the test set

We go back to the model from section 4 (50 thousand images, 5 epochs) and use the test set only once.

Code
perda_teste, acc_teste = avalia(modelo, carregador_teste)
print(f"TEST: loss = {perda_teste:.3f}   accuracy = {acc_teste:.2%}")

@torch.no_grad()
def predicoes(modelo, carregador):
    modelo.eval()
    ys, preds = [], []
    for x, y in carregador:
        preds.append(modelo(x.to(DEVICE)).argmax(dim=1).cpu())
        ys.append(y)
    return torch.cat(ys), torch.cat(preds)

y_teste, pred_teste = predicoes(modelo, carregador_teste)
TESTE: perda = 0.097   acurácia = 97.22%
Code
fig, ax = plt.subplots(figsize=(7.5, 6.5))
ConfusionMatrixDisplay(confusion_matrix(y_teste, pred_teste)).plot(ax=ax, cmap="Blues", colorbar=False, values_format="d")
ax.set(xlabel="predicted digit", ylabel="true digit", title="Confusion matrix on the test set (10 thousand images)")
ax.grid(False)
plt.show()

Code
erros = torch.nonzero(pred_teste != y_teste).flatten()[:18]
fig, axes = plt.subplots(3, 6, figsize=(12, 6.5))
for ax, i in zip(axes.flat, erros):
    ax.imshow(teste[i][0][0], cmap="gray_r")
    ax.set_title(f"true {y_teste[i].item()} -> predicted {pred_teste[i].item()}", color=LARANJA, fontsize=10)
    ax.axis("off")
plt.suptitle(f"Some of the {(pred_teste != y_teste).sum().item()} errors on the test set")
plt.tight_layout()
plt.show()

Many of the errors are digits that even a human would hesitate to classify. To go beyond ~97–98% on images, we need networks that understand the spatial structure of the image (neighborhoods between pixels), instead of flattening it into a vector: convolutional networks, the subject of the next classes.

7. The same pipeline with PyTorch Lightning

Every PyTorch project ends up rewriting the same things: the epoch loop, model.train()/model.eval(), torch.no_grad(), moving data to the GPU, logging metrics, saving checkpoints… PyTorch Lightning organizes this boilerplate for you. You still write PyTorch: you just put each piece in a method with a fixed name, and the Trainer runs the loop.

A LightningModule has four main methods:

  • forward: the network (class 1);
  • training_step: what to do with one batch of training data; returns the loss;
  • validation_step / test_step: what to do with a validation/test batch;
  • configure_optimizers: which optimizer to use (class 3).
Code
import lightning as L
from lightning.pytorch.loggers import CSVLogger
from lightning.pytorch.utilities.model_summary import ModelSummary
import logging

# keep Lightning's output cleaner for class
logging.getLogger("lightning.pytorch").setLevel(logging.ERROR)
warnings.filterwarnings("ignore", ".*does not have many workers.*")
warnings.filterwarnings("ignore", ".*GPU available but not used.*")     # the Mac GPU (MPS), which we don't use here
warnings.filterwarnings("ignore", ".*LeafSpec.*")                       # internal Lightning warning


class MLPMnist(L.LightningModule):
    def __init__(self, escondida=128, lr=1e-3):
        super().__init__()
        self.save_hyperparameters()                         # stores escondida (hidden size) and lr with the model
        self.rede = cria_mlp(escondida)

    def forward(self, x):
        return self.rede(x)

    def _passo(self, lote, etapa):
        x, y = lote
        logits = self(x)                                    # forward
        perda = F.cross_entropy(logits, y)                  # loss
        acc = (logits.argmax(dim=1) == y).float().mean()
        self.log(f"{etapa}_perda", perda, on_step=False, on_epoch=True)
        self.log(f"{etapa}_acc", acc, on_step=False, on_epoch=True)
        return perda

    def training_step(self, lote, indice):
        return self._passo(lote, "treino")                  # Lightning runs backward() and step() with the returned loss

    def validation_step(self, lote, indice):
        self._passo(lote, "val")

    def test_step(self, lote, indice):
        self._passo(lote, "teste")

    def configure_optimizers(self):
        return torch.optim.Adam(self.parameters(), lr=self.hparams.lr)


torch.manual_seed(0)
modelo_l = MLPMnist()
print(ModelSummary(modelo_l))
  | Name | Type       | Params | Mode  | FLOPs
----------------------------------------------------
0 | rede | Sequential | 101 K  | train | 0    
----------------------------------------------------
101 K     Trainable params
0         Non-trainable params
101 K     Total params
0.407     Total estimated model params size (MB)
5         Modules in train mode
0         Modules in eval mode
0         Total Flops
Code
trainer = L.Trainer(
    max_epochs=5,                                           # the epoch loop
    accelerator="gpu" if torch.cuda.is_available() else "cpu",
    logger=CSVLogger("logs", name="mlp_mnist"),             # saves the metrics to a CSV
    enable_progress_bar=False,
    enable_checkpointing=False,
)
inicio = time.time()
trainer.fit(modelo_l, carregador_treino, carregador_val)    # training + validation every epoch
print(f"total time: {time.time() - inicio:.0f} s")
tempo total: 7 s
Code
metricas_l = pd.read_csv(f"{trainer.logger.log_dir}/metrics.csv")
hist_l = metricas_l.groupby("epoch").first().rename(columns={
    "treino_perda": "perda treino", "val_perda": "perda validação",
    "treino_acc": "acurácia treino", "val_acc": "acurácia validação"})
hist_l.index = hist_l.index + 1
hist_l.index.name = "época"

plota_curvas(hist_l, "The same MLP trained with Lightning")

Code
resultado = trainer.test(modelo_l, carregador_teste, verbose=False)[0]
print(f"TEST (Lightning):     loss = {resultado['teste_perda']:.3f}   accuracy = {resultado['teste_acc']:.2%}")
print(f"TEST (plain PyTorch): loss = {perda_teste:.3f}   accuracy = {acc_teste:.2%}")
TESTE (Lightning):    perda = 0.087   acurácia = 97.40%
TESTE (PyTorch puro): perda = 0.097   acurácia = 97.22%

The results are very close to the plain PyTorch ones, as expected: it’s the same network, the same loss and the same optimizer. (They aren’t identical because the initialization and batch order aren’t exactly the same.)

Nothing is hidden: where did each line go?

Plain PyTorch (section 4) Lightning
for epoca in range(EPOCAS): Trainer(max_epochs=5)
for x, y in carregador_treino: trainer.fit(modelo, carregador_treino, ...) calls training_step for each batch
modelo.train() / modelo.eval() automatic, before training and validation
x, y = x.to(DEVICE), y.to(DEVICE) automatic (accelerator=...)
logits = modelo(x) forward
perda = F.cross_entropy(logits, y) inside training_step, which returns the loss
otimizador.zero_grad() → perda.backward() → otimizador.step() automatic, using the loss returned by training_step
torch.optim.Adam(modelo.parameters(), lr=1e-3) configure_optimizers
@torch.no_grad() + the loop in the avalia function validation_step / test_step (already without gradients)
avalia(modelo, carregador_val) every epoch trainer.fit(..., carregador_val)
historico.append(...) and print(...) self.log(...) + CSVLogger
avalia(modelo, carregador_teste) trainer.test(modelo, carregador_teste)

Writing the loop by hand first is the best way to learn. In bigger projects, Lightning saves repeated code and gives you multi-GPU training, checkpoints, early stopping and metric logging for free.

8. Discussion

  • Dataset defines how to get one sample; DataLoader handles batching and shuffling.
  • Training fits the weights, validation monitors training and chooses hyperparameters, test is used only once at the end.
  • The training loop is always: epochs → batches → forward → loss → zero_grad → backward → step. Evaluation uses model.eval() and torch.no_grad().
  • Overfitting shows up when the training loss keeps falling while the validation loss rises: the network memorized the training set. The validation curves tell you when to stop.
  • Lightning organizes the same code into methods with fixed names; the Trainer runs the loop.

Exercises

  1. In section 5, change 1,000 to 10,000 training images. Does overfitting decrease? In which epoch is the validation loss lowest?
  2. Add nn.Dropout(0.5) after the nn.ReLU() of the large network and repeat section 5. What changes in the curves? (Why do model.train()/model.eval() make a difference now?)
  3. In Lightning, add the L.pytorch.callbacks.EarlyStopping(monitor="val_perda", patience=3) callback to the Trainer and train the large network with 1,000 images for up to 60 epochs. In which epoch does it stop?
  4. Replace cria_mlp with a network with two hidden layers (784 → 256 → 128 → 10). Does test accuracy improve?