Code
# on Google Colab, PyTorch comes preinstalled; Lightning doesn't
import sys
if "google.colab" in sys.modules:
!pip install -q lightningLightningDataModule: all the data in one objectLightningModuleTrainer’s superpowersColab link
In class 4 we built the complete pipeline by hand (Dataset, DataLoader, training loop, evaluation loop) and then saw the same pipeline in Lightning. Today we’ll show why Lightning is worth it: with a single generic LightningModule, we’ll train networks for completely different problems.
The central idea of the class:
Every supervised deep learning problem is a combination of 3 pieces: the data, the network and the loss. Everything else (training loop, validation, early stopping, saving the best model, logging metrics, GPU…) is always the same, and Lightning takes care of it.
Plan
LightningDataModule: how data is organized into one objectLightningModuleTrainer’s superpowers (callbacks, logger, smoke test, learning rate finder)import io
import os
import time
import contextlib
import logging
import warnings
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader, TensorDataset, random_split
from torchvision import datasets, transforms
from sklearn.datasets import make_moons, load_diabetes
import lightning as L
from lightning.pytorch.callbacks import EarlyStopping, ModelCheckpoint
from lightning.pytorch.loggers import CSVLogger
from lightning.pytorch.tuner import Tuner
from lightning.pytorch.utilities.model_summary import ModelSummary
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,
})
# cleaner Lightning output for class
logging.getLogger("lightning.pytorch").setLevel(logging.ERROR)
logging.getLogger("lightning.fabric").setLevel(logging.ERROR)
for aviso in [".*does not have many workers.*", ".*GPU available but not used.*", ".*LeafSpec.*",
".*smaller than the logging interval.*", ".*Checkpoint directory.*exists.*"]:
warnings.filterwarnings("ignore", aviso)
# the CPU is faster than the Mac GPU (MPS) for small networks; on Colab with a GPU, we use CUDA
ACELERADOR = "gpu" if torch.cuda.is_available() else "cpu"
L.seed_everything(42)
print(f"Lightning {L.__version__}, accelerator: {ACELERADOR}")Lightning 2.6.6, acelerador: cpu
Lightning doesn’t change PyTorch: it separates a project’s code into three objects, each with one responsibility. You write what’s specific to your problem in methods with fixed names, and Lightning calls those methods at the right time.
┌──────────────────────────────┐ ┌──────────────────────────────────┐
│ LightningDataModule │ │ LightningModule │
│ "THE DATA" │ │ "THE MODEL" │
│ │ │ │
│ prepare_data() → download │ │ __init__() → the network │
│ setup() → Datasets, │ │ forward() → prediction │
│ split, │ │ training_step() → loss │
│ standardize│ │ validation_step() → metrics │
│ train_dataloader() │ │ test_step() │
│ val_dataloader() │ │ configure_optimizers() │
│ test_dataloader() │ │ → optimizer │
└──────────────┬───────────────┘ └────────────────┬─────────────────┘
│ │
└──────────────────┬────────────────────┘
▼
┌──────────────────────────────────────────┐
│ Trainer "THE ENGINE" │
│ epoch and batch loops, CPU/GPU, │
│ callbacks (early stopping, checkpoint), │
│ logger (CSV, TensorBoard, W&B) │
│ │
│ trainer.fit(modelo, datamodule=dm) │
│ trainer.test(...) trainer.predict(...) │
└──────────────────────────────────────────┘
| What | Where | In this class |
|---|---|---|
| Download the data | LightningDataModule.prepare_data() |
MNISTDataModule.prepare_data |
Create the Datasets, split train/val/test, standardize |
LightningDataModule.setup() |
TabelaDataModule.setup |
DataLoaders (batch size, shuffling) |
train_dataloader(), val_dataloader(), test_dataloader() |
batch_size=32, shuffle=True for training only |
| The network architecture | LightningModule.__init__() (built inside or passed as an argument) |
self.rede = rede |
| How the network makes a prediction | forward() |
return self.rede(x) |
| The loss | training_step(): computes and returns the loss |
self.perda(saida, y) |
| Metrics | training_step(), validation_step(), test_step() with self.log(...) |
accuracy, MAE |
| Optimizer (and lr scheduler) | configure_optimizers() |
torch.optim.Adam(self.parameters(), lr=self.lr) |
| Number of epochs, CPU/GPU, precision | Trainer(max_epochs=..., accelerator=..., precision=...) |
the treina function |
| Early stopping, saving the best model | Trainer(callbacks=[EarlyStopping(...), ModelCheckpoint(...)]) |
the treina function |
| Where to log the metrics | Trainer(logger=...) |
CSVLogger (and W&B at the end of the class) |
| Train, test, predict | trainer.fit(), trainer.test(), trainer.predict() |
trainer.fit() does under the hoodIn pseudo-code, trainer.fit(modelo, datamodule=dm) essentially runs the loop we wrote by hand in class 4, calling your methods:
dm.prepare_data() # 1. download the data
dm.setup("fit") # 2. create the Datasets
modelo.to(device) # 3. move the network to CPU/GPU
otimizador = modelo.configure_optimizers()
# 4. "sanity check": run 2 validation batches BEFORE training, to catch validation bugs early
for epoca in range(max_epochs):
modelo.train() # training mode
for i, lote in enumerate(dm.train_dataloader()):
lote = mover_para(device, lote)
perda = modelo.training_step(lote, i) # ← your code
otimizador.zero_grad()
perda.backward()
otimizador.step()
modelo.eval() # evaluation mode
with torch.no_grad():
for i, lote in enumerate(dm.val_dataloader()):
modelo.validation_step(lote, i) # ← your code
# 5. end of epoch: average the self.log(..., on_epoch=True) values and send them to the logger
# 6. callbacks: ModelCheckpoint saves if val_perda improved; EarlyStopping decides whether to stop.to(device), zero_grad(), backward(), step(), model.train(), model.eval() or torch.no_grad(): the Trainer does it. training_step only needs to return the loss. (For special cases, like GANs with two optimizers, there’s manual optimization: self.automatic_optimization = False.)self.log("name", value, on_step=..., on_epoch=...): with on_epoch=True, Lightning averages the value over all batches in the epoch (weighted by batch size) and logs one number per epoch.self.log is what the callbacks see: EarlyStopping(monitor="val_perda") only works because validation_step logs "val_perda".self.save_hyperparameters() stores the __init__ arguments (like lr) inside the checkpoint, so you can reload the model later with load_from_checkpoint.trainer.test(..., ckpt_path="best") reloads the best saved checkpoint before testing.logs/<name>/version_N/ folder with the metrics (metrics.csv), the hyperparameters (hparams.yaml) and the checkpoints.LightningDataModule: all the data in one objectIn class 4, the data was scattered: a Dataset, a random_split, three DataLoaders.
With PyTorch Lightning we can organize all of this in a single structure, the LightningDataModule, which brings everything together in a class with fixed-name methods:
| Method | Responsibility |
|---|---|
prepare_data() |
download the data |
setup(stage) |
split train/validation/test, standardize |
train_dataloader() |
the training DataLoader (with shuffling) |
val_dataloader() / test_dataloader() |
the validation and test DataLoaders |
We’ll write two. The first works for any table of numbers (X, y) and already does what we learned in the Machine Learning classes: it splits the data (randomly or temporally) and standardizes using only the training mean and standard deviation.
class TabelaDataModule(L.LightningDataModule):
"""Takes X and y (tensors) and handles the train/val/test split, standardization and DataLoaders."""
def __init__(self, X, y, batch_size=32,
frac_val=0.15, frac_teste=0.15,
padroniza_x=True,
padroniza_y=False,
temporal=False,
seed=42):
super().__init__()
self.X, self.y = X.float(), y
self.batch_size, self.frac_val, self.frac_teste = batch_size, frac_val, frac_teste
self.padroniza_x, self.padroniza_y, self.temporal, self.seed = padroniza_x, padroniza_y, temporal, seed
# Lightning's standard method that organizes the whole data structure
def setup(self,
stage=None):
if hasattr(self, "treino"): # setup is called by Lightning
return
# measure the size of the dataset
n = len(self.X)
# compute the fraction for training and the fraction for test
n_teste, n_val = int(n * self.frac_teste), int(n * self.frac_val)
n_treino = n - n_val - n_teste
# handling temporal data: remember the split can't be random
idx = torch.arange(n) if self.temporal else torch.randperm(n, generator=torch.Generator().manual_seed(self.seed))
tr, va, te = idx[:n_treino], idx[n_treino:n_treino + n_val], idx[n_treino + n_val:]
X, y = self.X.clone(), self.y.clone()
if self.padroniza_x: # mean and std computed ONLY on training data #standardization
self.x_media, self.x_desvio = X[tr].mean(0), X[tr].std(0)
X = (X - self.x_media) / self.x_desvio
if self.padroniza_y:
self.y_media, self.y_desvio = y[tr].mean(0), y[tr].std(0)
y = (y - self.y_media) / self.y_desvio
self.treino, self.val, self.teste = TensorDataset(X[tr], y[tr]), TensorDataset(X[va], y[va]), TensorDataset(X[te], y[te])
def train_dataloader(self):
return DataLoader(self.treino,
batch_size=self.batch_size,
shuffle=True,
generator=torch.Generator().manual_seed(self.seed))
def val_dataloader(self):
return DataLoader(self.val, batch_size=1024)
def test_dataloader(self):
return DataLoader(self.teste, batch_size=1024)The second is for MNIST, and shows prepare_data (download). It also has an autoencoder option: instead of (image, label), each sample becomes (image, image). We’ll use it in the last problem.
class ParesIguais(Dataset):
"""Wraps an image dataset to return (image, image)"""
def __init__(self, base):
self.base = base
def __len__(self):
return len(self.base)
def __getitem__(self, i):
x, _ = self.base[i]
return x, x
class MNISTDataModule(L.LightningDataModule):
def __init__(self, batch_size=128, autoencoder=False):
super().__init__()
self.batch_size, self.autoencoder = batch_size, autoencoder
def prepare_data(self): # only downloads (the first time)
datasets.MNIST("data", train=True, download=True)
datasets.MNIST("data", train=False, download=True)
def setup(self, stage=None):
if hasattr(self, "treino"):
return
completo = datasets.MNIST("data", train=True, transform=transforms.ToTensor())
self.teste = datasets.MNIST("data", train=False, transform=transforms.ToTensor())
if self.autoencoder:
completo, self.teste = ParesIguais(completo), ParesIguais(self.teste)
self.treino, self.val = random_split(completo, [55000, 5000], generator=torch.Generator().manual_seed(42))
def train_dataloader(self):
return DataLoader(self.treino, batch_size=self.batch_size, shuffle=True)
def val_dataloader(self):
return DataLoader(self.val, batch_size=1000)
def test_dataloader(self):
return DataLoader(self.teste, batch_size=1000)LightningModuleIn class 4, the LightningModule had the MNIST network written inside it. Now we’ll take the network, the loss and the metrics as arguments. Everything else (the training, validation and test steps, metric logging and the optimizer) is the same for any problem.
class ModeloGenerico(L.LightningModule):
"""Treina QUALQUER rede com QUALQUER perda.
Note que essa classe está usando a recebendo metodos da classe LightningModule (inherent)"""
def __init__(self, rede, perda, metricas=None, lr=1e-3):
super().__init__()
self.save_hyperparameters(ignore=["rede", "perda", "metricas"]) # stores the lr with the checkpoint
self.rede = rede
self.perda = perda
self.metricas = metricas or {}
self.lr = lr
def forward(self, x):
return self.rede(x) ## compute the forward pass
def _passo(self, lote, etapa):
x, y = lote
saida = self(x) # this is also a forward pass
perda = self.perda(saida, y) # compute the loss
self.log(f"{etapa}_perda", perda, on_step=False, on_epoch=True) # log the loss for this step
for nome, funcao in self.metricas.items():
self.log(f"{etapa}_{nome}", funcao(saida, y), on_step=False, on_epoch=True)
return perda
def training_step(self, lote, i):
## the training step has a fixed name by definition and receives the batch
return self._passo(lote, "treino")
def validation_step(self, lote, i):
self._passo(lote, "val")
def test_step(self, lote, i):
self._passo(lote, "teste")
def predict_step(self, lote, i):
# inference
return self(lote[0])
def configure_optimizers(self):
## the optimizer will run backpropagation and update the network's weights
return torch.optim.Adam(self.parameters(), lr=self.lr)
## here we write the metrics
# two simple metrics we'll reuse
def acuracia(logits, y):
return (logits.argmax(dim=1) == y).float().mean()
def mae(previsto, y):
return (previsto - y).abs().mean()Trainer’s superpowersThe Trainer makes life much easier when building neural networks. It has many options that are extremely useful and save you a lot of time when writing code, such as:
| Option | What it does | Without Lightning, you’d have to… |
|---|---|---|
max_epochs |
maximum number of epochs | write the epoch loop |
accelerator, devices |
CPU, GPU, multiple GPUs | move the model and every batch with .to(device) |
callbacks=[EarlyStopping(...)] |
stops when validation stops improving | track the best value and count epochs without improvement |
callbacks=[ModelCheckpoint(...)] |
saves the best model to disk | save and reload the state_dict by hand |
logger=CSVLogger(...) |
logs the metrics (also TensorBoard, W&B, MLflow) | build lists and save files |
fast_dev_run=True |
runs 1 batch of training and validation, to find bugs in seconds | wait a whole epoch to see the error |
overfit_batches=1 |
trains on a single batch: if the loss doesn’t get close to zero, there’s a bug | write a debugging script |
precision="16-mixed" |
half-precision training (faster on GPU) | use torch.autocast and GradScaler |
gradient_clip_val |
limits the gradient size | call clip_grad_norm_ in the right place |
Tuner(trainer).lr_find(...) |
suggests a learning rate | search by hand |
Let’s bundle the most commonly used ones into a treina (train) function that works for all five problems: early stopping, a checkpoint of the best model (by validation loss), CSV logging and evaluation on the test set with the best model, not the one from the last epoch.
def treina(modelo, dm, nome, max_epocas=100, paciencia=10):
checkpoint = ModelCheckpoint(monitor="val_perda", mode="min") # keeps the best model, the one with the lowest validation loss
trainer = L.Trainer(
max_epochs=max_epocas,
accelerator=ACELERADOR,
callbacks=[EarlyStopping(monitor="val_perda", patience=paciencia), checkpoint],
logger=CSVLogger("logs/dl5", name=nome),
enable_progress_bar=False,
enable_model_summary=False,
)
inicio = time.time()
trainer.fit(modelo, datamodule=dm) # fit our model with the data module
# reload the best set of weights and run inference
resultado = trainer.test(modelo, datamodule=dm, ckpt_path="best", verbose=False)[0] # reload the best
melhor_epoca = int(checkpoint.best_model_path.split("epoch=")[1].split("-")[0])
print(f"[{nome}] {trainer.current_epoch} epochs in {time.time() - inicio:.0f} s; best epoch: {melhor_epoca}")
print(f"[{nome}] test: " + " ".join(f"{k} = {v:.4f}" for k, v in resultado.items()))
return trainer
def historico(trainer):
"""Reads the logger's CSV and returns one row per epoch."""
df = pd.read_csv(os.path.join(trainer.logger.log_dir, "metrics.csv"))
return df.groupby("epoch")[["treino_perda", "val_perda"]].first().dropna()
def plota_perda(trainer, ax, titulo):
h = historico(trainer)
ax.plot(h.index, h["treino_perda"], color=AZUL, lw=2, label="train")
ax.plot(h.index, h["val_perda"], color=LARANJA, lw=2, label="validation")
ax.axvline(h["val_perda"].idxmin(), color=CINZA, ls="--", lw=1, label="best epoch")
ax.set(title=titulo, xlabel="epoch", ylabel="loss")
ax.legend(frameon=False)Two moon-shaped groups of points, where a straight line can’t separate the classes.
| Piece | Choice |
|---|---|
| Data | make_moons: 1,000 points, 2 features, 2 classes |
| Network | MLP 2 → 32 → 32 → 2 |
| Loss | nn.CrossEntropyLoss() |
# create the dataset, based on a common dataset that imitates two half-moons
X_luas, y_luas = make_moons(n_samples=1000, noise=0.25, random_state=0)
# prepare the data module.
dm_luas = TabelaDataModule(torch.tensor(X_luas), torch.tensor(y_luas), batch_size=32)
## here we create our neural network
## A very simple network: just a sequential MLP with hidden layers of 32 neurons.
rede_luas = nn.Sequential(
nn.Linear(2, 32),
nn.ReLU(),
nn.Linear(32, 32),
nn.ReLU(),
nn.Linear(32, 2)
)
# Here we build our model and pass the loss function; in this case we use cross-entropy as the loss.
# Note, however, that we monitor the model with the accuracy metric: how right the model is on the validation data
## So the model is trained to minimize cross-entropy, but we monitor how well it generalizes
modelo_luas = ModeloGenerico(rede_luas,
nn.CrossEntropyLoss(),
metricas={"acc": acuracia},
lr=1e-2
)
print(ModelSummary(modelo_luas)) | Name | Type | Params | Mode | FLOPs
-----------------------------------------------------------
0 | rede | Sequential | 1.2 K | train | 0
1 | perda | CrossEntropyLoss | 0 | train | 0
-----------------------------------------------------------
1.2 K Trainable params
0 Non-trainable params
1.2 K Total params
0.005 Total estimated model params size (MB)
7 Modules in train mode
0 Modules in eval mode
0 Total Flops
Before training for real, it’s always good to run a test, like a smoke test. With fast_dev_run=True, Lightning runs one batch of training and one of validation. If there’s any shape, type or logic error, it shows up in seconds, not after an hour of training. Use it whenever you change something.
smoke test, se tiver um erro iria printar aqui!
[luas] 30 épocas em 0 s; melhor época: 14
[luas] teste: teste_perda = 0.2699 teste_acc = 0.9000
tensor([[-2.0000, -1.5000],
[-1.9833, -1.5000],
[-1.9666, -1.5000],
...,
[ 2.9666, 2.0000],
[ 2.9833, 2.0000],
[ 3.0000, 2.0000]])
# decision boundary: the grid is standardized with the TRAINING mean and std, like the data
g1, g2 = np.meshgrid(np.linspace(-2, 3, 300), np.linspace(-1.5, 2, 300))
grade = torch.tensor(np.c_[g1.ravel(), g2.ravel()], dtype=torch.float32)
with torch.no_grad():
prob = torch.softmax(modelo_luas((grade - dm_luas.x_media) / dm_luas.x_desvio), dim=1)[:, 1].reshape(300, 300)
X_teste_luas = dm_luas.teste.tensors[0] * dm_luas.x_desvio + dm_luas.x_media # back to the original scale
y_teste_luas = dm_luas.teste.tensors[1]
fig, axes = plt.subplots(1, 2, figsize=(14, 4.5), width_ratios=[1.2, 1])
axes[0].contourf(g1, g2, prob, levels=[0, 0.5, 1], colors=["#cde2fb", "#f9d0bf"])
axes[0].contour(g1, g2, prob, levels=[0.5], colors=TINTA, linewidths=2)
axes[0].grid(False)
for classe, cor in [(0, AZUL), (1, LARANJA)]:
m = y_teste_luas == classe
axes[0].scatter(X_teste_luas[m, 0], X_teste_luas[m, 1], s=25, color=cor, edgecolor="white", lw=0.5, label=f"class {classe}")
axes[0].set(title="Decision boundary and TEST points", xlabel="x₁", ylabel="x₂")
axes[0].legend(frameon=False, loc="lower left")
plota_perda(trainer_luas, axes[1], "Loss curves")
plt.tight_layout()
plt.show()
scikit-learn’s diabetes dataset has 442 patients, 10 clinical measurements (age, BMI, blood pressure, blood tests…) and the target is an index of disease progression one year later. Now it’s regression: the network returns a number, and the loss changes to mean squared error.
| Piece | Choice |
|---|---|
| Data | 442 rows, 10 features; X and y standardized (with the training mean and std) |
| Network | MLP 10 → 64 → 64 → 1 |
| Loss | nn.MSELoss() |
Notice that the treina function is the same as in the previous problem: only the data, network and loss changed.
diabetes = load_diabetes()
dm_diab = TabelaDataModule(torch.tensor(diabetes.data), torch.tensor(diabetes.target).float().unsqueeze(1),
batch_size=32, padroniza_y=True)
torch.manual_seed(0)
## create the network here
rede_diab = nn.Sequential(nn.Linear(10, 64), nn.ReLU(), nn.Linear(64, 64), nn.ReLU(), nn.Linear(64, 1))
## build the model with the loss and the metric
modelo_diab = ModeloGenerico(rede_diab, nn.MSELoss(), metricas={"mae": mae}, lr=1e-3)
trainer_diab = treina(modelo_diab, dm_diab, "diabetes", max_epocas=300, paciencia=20)[diabetes] 38 épocas em 0 s; melhor época: 17
[diabetes] teste: teste_perda = 0.6152 teste_mae = 0.6170
To interpret the results, we use trainer.predict and undo the standardization of y, going back to the index’s original unit. We compare with a baseline that always predicts the training mean:
previsto = torch.cat(trainer_diab.predict(modelo_diab, dataloaders=dm_diab.test_dataloader()))
previsto = previsto * dm_diab.y_desvio + dm_diab.y_media
real = dm_diab.teste.tensors[1] * dm_diab.y_desvio + dm_diab.y_media
mae_rede = (previsto - real).abs().mean().item()
mae_base = (dm_diab.y_media - real).abs().mean().item()
print(f"mean absolute error on test: network = {mae_rede:.1f} baseline (training mean) = {mae_base:.1f}")
fig, axes = plt.subplots(1, 2, figsize=(13, 4.5))
axes[0].scatter(real, previsto, s=30, color=AZUL, alpha=0.7, edgecolor="white", lw=0.5)
lim = [real.min().item() - 10, real.max().item() + 10]
axes[0].plot(lim, lim, color=CINZA, ls="--", lw=1, label="perfect prediction")
axes[0].set(xlim=lim, ylim=lim, xlabel="actual progression", ylabel="predicted progression",
title=f"Test: predicted × actual (MAE = {mae_rede:.1f})")
axes[0].legend(frameon=False)
plota_perda(trainer_diab, axes[1], "Loss curves (standardized)")
plt.tight_layout()
plt.show()erro absoluto médio no teste: rede = 47.2 baseline (média do treino) = 68.6

The network is off by ~47 index points on average, versus ~69 for the baseline: it learned something useful, but the table is small (442 patients) and the problem is hard. Look at the curves too: the validation loss stops improving around epoch 17 while the training loss keeps falling (the start of overfitting). EarlyStopping waited 20 epochs without improvement (paciencia=20), stopped training, and the test used the best checkpoint, not the last one.
A synthetic series, like a sensor reading: the sum of two cycles plus noise. The task: looking at the last 30 values, predict the next one. Each sample is a window of 30 values, and the target is the following value.
| Piece | Choice |
|---|---|
| Data | 30-step windows; temporal split (train = past, test = future), as in the beach water quality class |
| Network | LSTM, a recurrent network made for sequences (we’ll see it in detail in upcoming classes) |
| Loss | nn.MSELoss() |
The LSTM has a different interface from nn.Sequential, so we wrap it in a small class. For ModeloGenerico, that makes no difference: it just needs something that takes x and returns the prediction.
t = torch.arange(2000, dtype=torch.float32)
torch.manual_seed(0)
serie = torch.sin(2 * np.pi * t / 50) + 0.5 * torch.sin(2 * np.pi * t / 17) + 0.1 * torch.randn(2000)
JANELA = 30
X_serie = torch.stack([serie[i:i + JANELA] for i in range(len(serie) - JANELA)]) # (1970, 30)
y_serie = serie[JANELA:].unsqueeze(1) # (1970, 1)
dm_serie = TabelaDataModule(X_serie, y_serie, batch_size=64, padroniza_x=False, temporal=True)
class PrevisorLSTM(nn.Module):
def __init__(self, oculto=32):
super().__init__()
self.lstm = nn.LSTM(input_size=1, hidden_size=oculto, batch_first=True)
self.saida = nn.Linear(oculto, 1)
def forward(self, x): # x: (batch, 30)
h, _ = self.lstm(x.unsqueeze(-1)) # (batch, 30, 1) - (batch, 30, hidden)
return self.saida(h[:, -1]) # use the state of the last step - (batch, 1)
torch.manual_seed(0)
modelo_serie = ModeloGenerico(PrevisorLSTM(), nn.MSELoss(), metricas={"mae": mae}, lr=5e-3)
trainer_serie = treina(modelo_serie, dm_serie, "serie_temporal", max_epocas=100, paciencia=10)[serie_temporal] 43 épocas em 3 s; melhor época: 32
[serie_temporal] teste: teste_perda = 0.0130 teste_mae = 0.0880
previsto_serie = torch.cat(trainer_serie.predict(modelo_serie,
dataloaders=dm_serie.test_dataloader()
)
)
real_serie = dm_serie.teste.tensors[1]
inicio_teste = len(serie) - len(real_serie)
fig, axes = plt.subplots(2, 1, figsize=(13, 6.5), height_ratios=[1, 1.2])
axes[0].plot(t, serie, color=CINZA, lw=0.8)
axes[0].axvspan(inicio_teste, len(serie), color=LARANJA, alpha=0.12, label="test (future)")
axes[0].set(title="The full series", xlabel="time")
axes[0].legend(frameon=False, loc="upper left")
trecho = slice(0, 150)
tt = t[inicio_teste:][trecho]
axes[1].plot(tt, real_serie[trecho], color=CINZA, lw=4, alpha=0.5, label="real")
axes[1].plot(tt, previsto_serie[trecho], color=LARANJA, lw=2, label="LSTM forecast (1 step ahead)")
axes[1].set(title="Zoom on the first 150 test steps", xlabel="time")
axes[1].legend(frameon=False, loc="upper left", ncols=2)
plt.tight_layout()
plt.show()
Back to MNIST, but now with a convolutional network (CNN) instead of the MLP. The CNN looks at small regions of the image (3 × 3 pixels) and exploits the spatial structure that the MLP lost by flattening the image. The details of convolutions are for the next class; today we’ll just look at the network’s structure in Lightning.
| Piece | Choice |
|---|---|
| Data | MNISTDataModule: 55 thousand training, 5 thousand validation, 10 thousand test |
| Network | 2 convolutional layers + 1 linear layer |
| Loss | nn.CrossEntropyLoss() |
Instead of guessing the lr, the Tuner trains for 100 steps while increasing the lr exponentially (from 0.000001 to 1) and records the loss. A good rate lies in the region where the loss falls fastest, before it blows up.
dm_mnist = MNISTDataModule(batch_size=128)
torch.manual_seed(0)
## building the network with convolutions; we'll look deeper next week
rede_cnn = nn.Sequential(
nn.Conv2d(1, 16, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2), # (1, 28, 28) - (16, 14, 14)
nn.Conv2d(16, 32, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2), # - (32, 7, 7)
nn.Flatten(), nn.Linear(32 * 7 * 7, 10),
)
# again, we build our model with the metrics
modelo_cnn = ModeloGenerico(rede_cnn, nn.CrossEntropyLoss(), metricas={"acc": acuracia})
print(ModelSummary(modelo_cnn, max_depth=2))
tuner = Tuner(L.Trainer(max_epochs=1,
accelerator=ACELERADOR,
logger=False,
enable_progress_bar=False,
enable_model_summary=False,
default_root_dir="logs/dl5/lr_find")
)
with contextlib.redirect_stderr(io.StringIO()): # hide the finder's progress bar
busca_lr = tuner.lr_find(modelo_cnn,
datamodule=dm_mnist,
min_lr=1e-6,
max_lr=1.0,
num_training=100
)
r = busca_lr.results
fig, ax = plt.subplots(figsize=(8, 3.5))
ax.plot(r["lr"], r["loss"], color=AZUL, lw=2)
ax.axvline(busca_lr.suggestion(), color=LARANJA, ls="--", lw=1.5, label=f"suggestion: lr = {busca_lr.suggestion():.1e}")
ax.set(xscale="log", xlabel="learning rate", ylabel="loss", title="Learning rate finder (lr_find)")
ax.legend(frameon=False)
plt.show()
print(f"the model's lr was automatically updated to {modelo_cnn.lr:.1e}") | Name | Type | Params | Mode | FLOPs
------------------------------------------------------------
0 | rede | Sequential | 20.5 K | train | 0
1 | rede.0 | Conv2d | 160 | train | 0
2 | rede.1 | ReLU | 0 | train | 0
3 | rede.2 | MaxPool2d | 0 | train | 0
4 | rede.3 | Conv2d | 4.6 K | train | 0
5 | rede.4 | ReLU | 0 | train | 0
6 | rede.5 | MaxPool2d | 0 | train | 0
7 | rede.6 | Flatten | 0 | train | 0
8 | rede.7 | Linear | 15.7 K | train | 0
9 | perda | CrossEntropyLoss | 0 | train | 0
------------------------------------------------------------
20.5 K Trainable params
0 Non-trainable params
20.5 K Total params
0.082 Total estimated model params size (MB)
10 Modules in train mode
0 Modules in eval mode
0 Total Flops

o lr do modelo foi atualizado automaticamente para 4.0e-03
The suggestion is a heuristic: always look at the curve. Values below it learn slowly; values close to the point where the loss blows up are unstable. With the suggested lr already applied to the model, we train for 3 epochs (about 20 seconds on CPU):
[mnist_cnn] 3 épocas em 19 s; melhor época: 2
[mnist_cnn] teste: teste_perda = 0.0371 teste_acc = 0.9879
In class 4, the MLP reached ~97% test accuracy. The CNN, with fewer parameters, beats that in a few epochs.
ModelCheckpoint saved the best model to disk. Anyone can reload it later (in another notebook, on a server) and use it to make predictions. Since the network was passed as an argument, we provide the architecture when loading:
caminho = trainer_cnn.checkpoint_callback.best_model_path
print(f"best model saved at: {caminho}")
# reload the best weights from training
recarregado = ModeloGenerico.load_from_checkpoint(caminho, rede=rede_cnn, perda=nn.CrossEntropyLoss())
## evaluation mode: the weights won't be updated anymore
recarregado.eval()
x_ex, y_ex = next(iter(dm_mnist.test_dataloader()))
with torch.no_grad():
prob_ex = torch.softmax(recarregado(x_ex[:12]), dim=1)
fig, axes = plt.subplots(2, 6, figsize=(12, 4.5))
for ax, img, y, p in zip(axes.flat, x_ex[:12], y_ex[:12], prob_ex):
pred = p.argmax().item()
ax.imshow(img[0], cmap="gray_r")
ax.set_title(f"predicted {pred} ({p[pred]:.0%})", color=VERDE if pred == y else LARANJA, fontsize=10)
ax.axis("off")
plt.suptitle("Predictions from the model reloaded from the checkpoint")
plt.tight_layout()
plt.show()melhor modelo salvo em: logs/dl5/mnist_cnn/version_2/checkpoints/epoch=2-step=1290.ckpt

What if there are no labels? An autoencoder learns to compress the image into a few numbers (the code or latent space) and then reconstruct it from them. The target is the image itself, so no labels are needed at all: it’s unsupervised learning, like the clustering from the ML class.
| Piece | Choice |
|---|---|
| Data | MNISTDataModule(autoencoder=True): each sample is (image, image) |
| Network | encoder 784 → 128 → 2 and decoder 2 → 128 → 784 |
| Loss | nn.MSELoss() between the reconstructed and the original image |
We compress each 784-pixel image into just 2 numbers, so we can plot the latent space.
class Autoencoder(nn.Module):
def __init__(self, dim_latente=2):
super().__init__()
self.codificador = nn.Sequential(nn.Flatten(), nn.Linear(784, 128), nn.ReLU(), nn.Linear(128, dim_latente))
self.decodificador = nn.Sequential(nn.Linear(dim_latente, 128), nn.ReLU(), nn.Linear(128, 784), nn.Sigmoid())
def forward(self, x):
z = self.codificador(x) # (batch, 2): the compressed image
return self.decodificador(z).reshape(-1, 1, 28, 28) # reconstruction with the input's shape
dm_ae = MNISTDataModule(batch_size=128, autoencoder=True)
torch.manual_seed(0)
autoencoder = Autoencoder()
modelo_ae = ModeloGenerico(autoencoder, nn.MSELoss(), lr=2e-3)
trainer_ae = treina(modelo_ae, dm_ae, "autoencoder", max_epocas=10, paciencia=3)[autoencoder] 10 épocas em 13 s; melhor época: 9
[autoencoder] teste: teste_perda = 0.0422
x_ae, _ = next(iter(dm_ae.test_dataloader()))
with torch.no_grad():
reconstruido = modelo_ae(x_ae[:10])
fig, axes = plt.subplots(2, 10, figsize=(14, 3.2))
for j in range(10):
axes[0, j].imshow(x_ae[j, 0], cmap="gray_r")
axes[1, j].imshow(reconstruido[j, 0], cmap="gray_r")
axes[0, j].axis("off"); axes[1, j].axis("off")
axes[0, 0].set_title("original", loc="left", fontsize=10)
axes[1, 0].set_title("reconstructed from 2 numbers", loc="left", fontsize=10)
plt.tight_layout()
plt.show()
The reconstructions are blurry: 2 numbers is very little to store an image. Digits with very distinct shapes (0, 1, 7) come back recognizable, but several turn into a similar digit (a 2 becomes something like a 3, a 4 becomes a 9). The most interesting part is the latent space: where did each test image land on the 2D plane? The autoencoder never saw the labels, but let’s color the points by the true digit:
teste_mnist = datasets.MNIST("data", train=False, transform=transforms.ToTensor())
x_todos = torch.stack([teste_mnist[i][0] for i in range(5000)])
rotulos = teste_mnist.targets[:5000]
with torch.no_grad():
z = autoencoder.codificador(x_todos)
import matplotlib.patheffects as pe
fig, ax = plt.subplots(figsize=(10, 7.5))
cores_digitos = plt.get_cmap("tab10")
for d in range(10):
m = rotulos == d
ax.scatter(z[m, 0], z[m, 1], s=4, color=cores_digitos(d), alpha=0.5, label=str(d))
cx, cy = z[m].median(dim=0).values
ax.text(cx, cy, str(d), fontsize=16, fontweight="bold", ha="center", va="center", color=cores_digitos(d),
path_effects=[pe.withStroke(linewidth=4, foreground="white")])
ax.legend(title="digit", frameon=False, markerscale=4, loc="upper left", bbox_to_anchor=(1, 1))
ax.set(xlabel="latent dimension 1", ylabel="latent dimension 2",
title="Autoencoder latent space (5 thousand test images; color is the true digit)")
plt.show()
Without ever seeing a label, the autoencoder organized the latent space by shape: 0, 1 and 6 sit in their own regions, while digits with similar strokes mix together, like 4, 7 and 9, or 3, 5 and 8. The same confusions appear in the reconstructions above. It’s the same intuition as in the unsupervised learning class, now with a neural network.
| Problem | Data (DataModule) |
Network | Loss | Metric |
|---|---|---|---|---|
| Two moons | TabelaDataModule, random split |
MLP | CrossEntropyLoss |
accuracy |
| Diabetes | TabelaDataModule, padroniza_y=True |
MLP | MSELoss |
MAE |
| Time series | TabelaDataModule, temporal=True |
LSTM | MSELoss |
MAE |
| Digits | MNISTDataModule |
CNN | CrossEntropyLoss |
accuracy |
| Autoencoder | MNISTDataModule(autoencoder=True) |
encoder + decoder | MSELoss |
— |
ModeloGenerico and the treina function didn’t change a single line. Early stopping, checkpoints, metric logging, evaluation with the best model and GPU support came for free in every case. That’s what it means to say that, with the right three pieces, you can train a neural network for (almost) anything.
LightningDataModule organizes the data: download, split, standardization and DataLoaders in a single object.LightningModule can be generic: taking the network, the loss and the metrics as arguments.Trainer concentrates the repetitive code: early stopping, checkpoints, logging, accelerators, mixed precision.fast_dev_run=True is a programmer’s best friend: it finds bugs in seconds.Tuner.lr_find suggests a learning rate instead of guessing (but always look at the curve).sklearn.datasets.load_wine (178 wines, 13 features, 3 classes) with TabelaDataModule and ModeloGenerico. How many new lines of code did you need?L.Trainer(overfit_batches=1, max_epochs=200). Does the training loss get close to zero? Why is this a good debugging test?CSVLogger with TensorBoardLogger and open the dashboard with %load_ext tensorboard and %tensorboard --logdir logs.dim_latente=2 to dim_latente=16. Do the reconstructions improve? (To visualize the 16-dimensional latent space, you’d need PCA or t-SNE.)PrevisorLSTM with an MLP nn.Sequential(nn.Linear(30, 64), nn.ReLU(), nn.Linear(64, 1)). Which has the lower test error?So far the metrics went to a CSV in the logs/ folder. In real projects, with dozens of experiments, that becomes hard to follow. Weights & Biases (W&B) is an online platform (free for personal and academic use) that receives the metrics during training and shows everything on a dashboard in the browser:
lr, which network, which optimizer was best?);log_model=True);With Lightning, connecting W&B means changing one line: the Trainer’s logger.
ModeloGenerico’s self.log(...) calls don’t change: Lightning sends the same values to W&B.
uv add wandb in the project (or pip install wandb on Colab).USAR_WANDB = True and run it. The first time, wandb.login() asks for the API key (it’s saved on your computer; don’t put the key in the code or on GitHub).No internet? Use
os.environ["WANDB_MODE"] = "offline"before training. The data stays in thewandb/folder and can be uploaded later withwandb sync wandb/offline-run-*.
USAR_WANDB = False # ← set to True after creating the account and installing wandb
if USAR_WANDB:
import wandb
from lightning.pytorch.loggers import WandbLogger
wandb.login() # asks for the API key the first time
logger_wandb = WandbLogger(
project="spacetech-dl5", # groups runs into a project
name="mnist_cnn_adam", # name of this run on the dashboard
log_model=True, # uploads the best checkpoint to the cloud
)
logger_wandb.experiment.config.update({"batch_size": 128, "rede": "CNN 16-32", "otimizador": "Adam"})
torch.manual_seed(0)
rede_wandb = nn.Sequential( # the same CNN as in problem 4, with fresh weights
nn.Conv2d(1, 16, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
nn.Conv2d(16, 32, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
nn.Flatten(), nn.Linear(32 * 7 * 7, 10),
)
modelo_wandb = ModeloGenerico(rede_wandb, nn.CrossEntropyLoss(), metricas={"acc": acuracia}, lr=4e-3)
trainer_wandb = L.Trainer(
max_epochs=3,
accelerator=ACELERADOR,
logger=logger_wandb, # ← the only difference from the treina function
callbacks=[EarlyStopping(monitor="val_perda", patience=2), ModelCheckpoint(monitor="val_perda", mode="min")],
)
trainer_wandb.fit(modelo_wandb, datamodule=dm_mnist)
trainer_wandb.test(modelo_wandb, datamodule=dm_mnist, ckpt_path="best")
wandb.finish() # ends the run and finishes uploading
else:
print("W&B is off. Follow the steps above and set USAR_WANDB = True to see training on the dashboard.")W&B desligado. Siga o passo a passo acima e mude USAR_WANDB = True para ver o treino no painel.
On the W&B dashboard you’ll see, among other things, the treino_perda (train loss), val_perda, treino_acc and val_acc charts (the same names as in self.log), the Overview tab with the hyperparameters and the System tab with CPU and memory usage. Train again with a different lr or network and compare the runs side by side: that’s how deep learning teams organize hundreds of experiments.