Skip to main content

Model and hyperparameters

Author

Marie-Hélène Burle

The toy example early in this course trained a model with a bare five-line loop. Real training needs more: mixed precision, a learning-rate scheduler, gradient clipping, proper metrics, early stopping, and checkpointing of the best model.

In this section, we assemble a small convolutional neural network (CNN) and all the hyperparameters into a Python script.

Setup

import math  # for the cosine schedule
import time  # to time epochs
from pathlib import Path

import torch
from matplotlib import pyplot as plt
from torch import nn
from torch.utils.data import DataLoader, Subset
from torchmetrics import MeanMetric
from torchmetrics.classification import MulticlassAccuracy
from torchvision.datasets import EuroSAT
from torchvision.transforms import v2 as T

torchmetrics provides composable, device-aware metrics (MeanMetric for weighted averages, MulticlassAccuracy for the classification score).

As we saw in the first section, we pick the accelerator if there is one, fall back to the CPU otherwise, and seed for reproducibility:

device = (
    torch.accelerator.current_accelerator()
    if torch.accelerator.is_available()
    else torch.device("cpu")
)
torch.manual_seed(42)
print(f"Torch version: {torch.__version__}\nDevice: {device}")
Torch version: 2.13.0+cu130
Device: cuda

The data pipeline is the one built in the previous sections: transforms with augmentation for training and deterministic transforms for validation, loaders with 8 workers. The training shuffle gets a seeded generator, so that runs are reproducible:

root = Path("/project/def-sponsor00/data")
IMAGENET_MEAN, IMAGENET_STD = [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]

train_tf = T.Compose(
    [
        T.ToImage(),
        T.RandomHorizontalFlip(),
        T.RandomVerticalFlip(),
        T.RandomRotation(90),
        T.ToDtype(torch.float32, scale=True),
        T.Normalize(IMAGENET_MEAN, IMAGENET_STD),
    ]
)
val_tf = T.Compose(
    [
        T.ToImage(),
        T.ToDtype(torch.float32, scale=True),
        T.Normalize(IMAGENET_MEAN, IMAGENET_STD),
    ]
)

idx = torch.load(root / "split.pt", weights_only=True)
train = Subset(EuroSAT(root=root, transform=train_tf), idx["train"])
val = Subset(EuroSAT(root=root, transform=val_tf), idx["val"])

loader_kwargs = {"batch_size": 64}
train_loader = DataLoader(
    train, shuffle=True, generator=torch.Generator().manual_seed(42), **loader_kwargs
)
val_loader = DataLoader(val, **loader_kwargs)
print(f"Train batches: {len(train_loader)}\nVal batches: {len(val_loader)}")
Train batches: 338
Val batches: 85

A deliberately small model

The model is a small convolutional network: three conv blocks that double the channels (the first two also halve the image), then a global average pool and a linear layer producing one score per class.

class Net(nn.Module):
    """A small CNN for 64x64 images and 10 classes."""

    def __init__(self):
        super().__init__()
        self.layers = nn.Sequential(
            # 3 conv blocks: each doubles the channels; the first two halve the image
            nn.Conv2d(3, 32, 3, padding=1),
            nn.ReLU(),
            nn.MaxPool2d(2),  # 64 -> 32
            nn.Conv2d(32, 64, 3, padding=1),
            nn.ReLU(),
            nn.MaxPool2d(2),  # 32 -> 16
            nn.Conv2d(64, 128, 3, padding=1),
            nn.ReLU(),  # 16 -> 16
            nn.AdaptiveAvgPool2d(1),  # one value per channel: 128 features
            nn.Flatten(),
            nn.Linear(128, 10),  # one score per class
        )

    def forward(self, x):
        return self.layers(x)
  • Each nn.Conv2d slides 3 × 3 filters over the image (padding=1 keeps the size).
  • nn.AdaptiveAvgPool2d(1) averages each channel over the whole image: whatever the input size, the output is 128 numbers. This makes the architecture tolerant to other image sizes.
model = Net().to(device)
print("Parameters:", sum(p.numel() for p in model.parameters()))
Parameters: 94538

The model contains roughly 95,000 parameters. It is deliberately modest. Trained from scratch, it will land on a mediocre baseline, and that is the point: it gives every later technique something to improve upon, and its epochs run in seconds even on small GPUs.

Hyperparameters

The training hyperparameters include the loss function, the optimizer, and the learning-rate schedule.

The loss function and optimizer are the ones used in our toy example: cross-entropy for classification, AdamW with decoupled weight decay:

loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0.01)

The new ingredient is the schedule. A constant learning rate is a poor default: too high and early updates destabilize the run, too low and training crawls. We combine two standard ideas:

  • Warmup: the learning rate ramps up from almost zero over the first epoch. The first steps happen on random weights, where gradients are large and noisy.
  • Cosine decay: afterwards, it anneals smoothly down to zero: large steps while the model is coarse, small steps while it refines.
max_epochs, warmup = 15, len(train_loader)  # warmup: 1 epoch
total_steps = max_epochs * len(train_loader)


def lr_lambda(step):
    if step < warmup:
        return (step + 1) / warmup  # linear ramp from ~0 to 1
    progress = (step - warmup) / (total_steps - warmup)
    return 0.5 * (1.0 + math.cos(math.pi * progress))  # cosine down to ~0


scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda)
print(f"Warmup: {warmup} steps\nTotal: {total_steps} steps")
Warmup: 338 steps
Total: 5070 steps

LambdaLR multiplies the base learning rate (1e-3) by our function at every step. Here is its shape over the planned run:

base_lr = optimizer.param_groups[0]["initial_lr"]
lrs = [base_lr * lr_lambda(s) for s in range(total_steps)]
fig, ax = plt.subplots(figsize=(7, 3))
ax.plot(lrs)
ax.set_xlabel("step")
ax.set_ylabel("learning rate")

Metrics

Hand-rolled accuracy is easy to get subtly wrong (averaging over batches instead of samples is a classic mistake). We use the torchmetrics package: metrics are objects with an update() method called once per batch and a compute() method called at the end.

We need two metrics: MeanMetric for a weighted average (per-batch losses weighted by batch size, since the last batch is smaller), and MulticlassAccuracy:

metric = MulticlassAccuracy(num_classes=10).to(device)
with torch.inference_mode():
    logits = torch.eye(10).repeat(3, 1).to(device)  # 30 rows of perfect logits
    preds = logits.argmax(dim=1)
metric.update(preds, torch.arange(10).repeat(3).to(device))
print(f"Accuracy: {metric.compute().item()}")
Accuracy: 1.0

We get perfect predictions on three passes over the 10 classes: the accuracy is 1.0.

One epoch of training

One more modern ingredient: mixed precision. The compute happens in bfloat16, which halves memory traffic and, on recent GPUs, uses dedicated fast paths, while sensitive operations stay in float32. torch.autocast handles the casting per operation:

# bf16 only accelerates on Ampere (2020) and newer GPUs; on older ones it
# runs in emulation and can be slower than plain fp32, hence the gate
use_bf16 = device.type == "cuda" and torch.cuda.get_device_capability()[0] >= 8
print(f"Use of mixed precision: {use_bf16}")
Use of mixed precision: False

On my machine, as you can see, the GPU does not allow mixed precision.

On the cluster, the GPUs can. We can’t test it here since we are using JupyterHub on one CPU, but you will see it later.

Why bf16 rather than the classic fp16?

bf16 keeps the exponent range of float32, so it does not need the gradient scaling that fp16 training requires (the GradScaler you will see in older tutorials). On GPUs too old to accelerate bf16 (like the RTX 2060 of my laptop this page renders on) fp32 remains the proper choice: I tested it and bf16 epoch emulations took twice as long as with fp32. On the Alliance clusters’ GPUs however, the gate opens and the same code runs in bf16.

Here is one epoch:

def train_epoch():
    model.train()
    loss_metric = MeanMetric().to(device)
    for x, y in train_loader:
        x = x.to(device, non_blocking=True)
        y = y.to(device, non_blocking=True)
        optimizer.zero_grad()
        with torch.autocast(
            device_type=device.type, dtype=torch.bfloat16, enabled=use_bf16
        ):
            loss = loss_fn(model(x), y)
        loss.backward()
        nn.utils.clip_grad_norm_(model.parameters(), 1.0)
        optimizer.step()
        scheduler.step()  # the schedule advances every batch
        loss_metric.update(loss.detach(), weight=x.size(0))
    return loss_metric.compute().item()
  • model.train() switches to training behaviour (our CNN has no mode-dependent layers, but the habit prevents silent bugs the day the model changes).
  • Batches move to the accelerator with non_blocking=True: with pinned memory, the copies overlap with compute.
  • The forward pass and the loss sit inside the autocast context; the backward pass and the optimizer work outside it: autocast casts the inputs of selected operations, the weights stay in float32, and no gradient scaling is needed.
  • clip_grad_norm_ rescales the gradients if their global norm exceeds 1.0: one pathological batch cannot produce a huge parameter jump. This protects the run at a negligible cost.
  • The scheduler advances at every batch, matching the per-step warmup and cosine.
  • loss_metric.update receives the detached loss weighted by the batch size, so the epoch loss is the mean over images, not over batches.

Evaluation

Evaluation runs the validation batches through the model without the training machinery:

def evaluate():
    model.eval()
    loss_metric = MeanMetric().to(device)
    acc_metric = MulticlassAccuracy(num_classes=10).to(device)
    for x, y in val_loader:
        x = x.to(device, non_blocking=True)
        y = y.to(device, non_blocking=True)
        with torch.inference_mode():
            logits = model(x)
            preds = logits.argmax(dim=1)
        loss_metric.update(loss_fn(logits, y), weight=x.size(0))
        acc_metric.update(preds, y)
    return loss_metric.compute().item(), acc_metric.compute().item()
  • model.eval() is the counterpart of model.train().
  • torch.inference_mode() disables the autograd engine: no graph is recorded, so evaluation is faster and leaner.
  • Predictions are the class with the highest logit, computed inside the context. The loss and the metric updates come after it, on tensors created inside. That works because such tensors can be read anywhere: outside inference_mode(), their only limits are in-place modification and autograd. The loss and the updates would work inside the context as well.

Early stopping

Instead of stopping as soon as the validation loss goes up, one hyperparameter that can be set is patience: patience is the number of epochs the model should continue training after the validation loss goes up (usually 3 to 5). This allows the model to recover from temporary plateaus and avoids the problem of double descent. Once that patience value is reached, you should use the checkpoint for the best validation loss (before the patience period) as your trained model. Let’s set it at a value of 4.

The last piece is the loop around the epochs. It keeps a history for plotting, saves a checkpoint whenever validation improves, and stops when it has not improved for patience epochs:

patience = 4

def fit():
    history = {"train_loss": [], "val_loss": [], "val_acc": [], "lr": []}
    best_acc, best_epoch, wait = 0.0, 0, 0
    for epoch in range(1, max_epochs + 1):
        t0 = time.perf_counter()
        train_loss = train_epoch()
        val_loss, val_acc = evaluate()
        history["train_loss"].append(train_loss)
        history["val_loss"].append(val_loss)
        history["val_acc"].append(val_acc)
        history["lr"].append(scheduler.get_last_lr()[0])
        marker = ""
        if val_acc > best_acc:
            best_acc, best_epoch, wait = val_acc, epoch, 0
            torch.save(
                {"model": model.state_dict(), "epoch": epoch, "val_acc": val_acc},
                root / "best.pt",
            )
            marker = " *"
        else:
            wait += 1
        print(
            f"epoch {epoch:2d}  train {train_loss:.3f}  val {val_loss:.3f}  "
            f"acc {val_acc:5.1%}  lr {scheduler.get_last_lr()[0]:.2e}  "
            f"{time.perf_counter() - t0:4.1f} s{marker}"
        )
        if wait >= patience:
            print(f"early stop: no improvement for {patience} epochs")
            break
    return history, best_epoch, best_acc
  • The * marks epochs that improved on the best validation accuracy so far, each of which overwrites the checkpoint.
  • Why checkpoint at all? Validation metrics wobble from epoch to epoch, so the model at the last epoch is not necessarily the best one. The saved checkpoint is the one to keep and evaluate.
  • Early stopping ends the run when wait reaches patience: the model has stopped improving and further epochs are wasted compute (and, given enough of them, would slowly overfit).

Running fit() would now launch training and return history, best_epoch, and best_acc.

The best checkpoint

The file saved along the way holds the best model seen:

ckpt = torch.load(root / "best.pt", weights_only=True)
print(f"Best epoch: {ckpt['epoch']} (val acc: {ckpt['val_acc']:.1%})")
model.load_state_dict(ckpt["model"])
val_loss, val_acc = evaluate()
print(f"Restored model: val loss {val_loss:.3f}, acc {val_acc:.1%}")
Best epoch: 14 (val acc: 80.4%)
Restored model: val loss 0.547, acc 80.4%
  • weights_only=True keeps torch.load restricted to plain data: loading a checkpoint should never execute code.
  • Restoring the weights and re-evaluating confirms the numbers: this is the baseline model of the course, a small CNN at about 81% validation accuracy.

Script

Let’s wrap all this code in a Python script called train.py so that we can test it on the cluster.

There is something that we need to change though. In a Python script, code that creates DataLoaders with workers must sit under the main guard:

if __name__ == "__main__":

Without it, worker startup re-imports your script: module-level code runs again and the run crashes with a RuntimeError. A standard way to handle this is to bring the setup and our three functions inside a main() function and run that that function under the guard.

Jupyter notebook cells are immune to this which is why we didn’t have to worry about this until now.

import math  # for the cosine schedule
import time  # to time epochs
from pathlib import Path

import torch
from torch import nn
from torch.utils.data import DataLoader, Subset
from torchmetrics import MeanMetric
from torchmetrics.classification import MulticlassAccuracy
from torchvision.datasets import EuroSAT
from torchvision.transforms import v2 as T


class Net(nn.Module):
    """A small CNN for 64x64 images and 10 classes."""

    def __init__(self):
        super().__init__()
        self.layers = nn.Sequential(
            # 3 conv blocks: each doubles the channels; the first two halve the image
            nn.Conv2d(3, 32, 3, padding=1),
            nn.ReLU(),
            nn.MaxPool2d(2),  # 64 -> 32
            nn.Conv2d(32, 64, 3, padding=1),
            nn.ReLU(),
            nn.MaxPool2d(2),  # 32 -> 16
            nn.Conv2d(64, 128, 3, padding=1),
            nn.ReLU(),  # 16 -> 16
            nn.AdaptiveAvgPool2d(1),  # one value per channel: 128 features
            nn.Flatten(),
            nn.Linear(128, 10),  # one score per class
        )

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


def main():
    device = (
        torch.accelerator.current_accelerator()
        if torch.accelerator.is_available()
        else torch.device("cpu")
    )
    torch.manual_seed(42)
    print(f"Torch version: {torch.__version__}\nDevice: {device}")

    root = Path("/project/def-sponsor00/data")

    IMAGENET_MEAN, IMAGENET_STD = [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]

    train_tf = T.Compose(
        [
            T.ToImage(),
            T.RandomHorizontalFlip(),
            T.RandomVerticalFlip(),
            T.RandomRotation(90),
            T.ToDtype(torch.float32, scale=True),
            T.Normalize(IMAGENET_MEAN, IMAGENET_STD),
        ]
    )
    val_tf = T.Compose(
        [
            T.ToImage(),
            T.ToDtype(torch.float32, scale=True),
            T.Normalize(IMAGENET_MEAN, IMAGENET_STD),
        ]
    )

    idx = torch.load(root / "split.pt", weights_only=True)
    train = Subset(EuroSAT(root=root, transform=train_tf), idx["train"])
    val = Subset(EuroSAT(root=root, transform=val_tf), idx["val"])

    loader_kwargs = {"batch_size": 64}
    train_loader = DataLoader(
        train,
        shuffle=True,
        generator=torch.Generator().manual_seed(42),
        **loader_kwargs,
    )
    val_loader = DataLoader(val, **loader_kwargs)
    print(f"Train batches: {len(train_loader)}\nVal batches: {len(val_loader)}")

    model = Net().to(device)
    print("Parameters:", sum(p.numel() for p in model.parameters()))

    loss_fn = nn.CrossEntropyLoss()
    optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0.01)

    max_epochs, patience, warmup = 15, 4, len(train_loader)  # warmup: 1 epoch
    total_steps = max_epochs * len(train_loader)

    def lr_lambda(step):
        if step < warmup:
            return (step + 1) / warmup  # linear ramp from ~0 to 1
        progress = (step - warmup) / (total_steps - warmup)
        return 0.5 * (1.0 + math.cos(math.pi * progress))  # cosine down to ~0

    scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda)
    print(f"Warmup: {warmup} steps\nTotal: {total_steps} steps")

    metric = MulticlassAccuracy(num_classes=10).to(device)
    with torch.inference_mode():
        logits = torch.eye(10).repeat(3, 1).to(device)  # 30 rows of perfect logits
        preds = logits.argmax(dim=1)
    metric.update(preds, torch.arange(10).repeat(3).to(device))
    print(f"Accuracy: {metric.compute().item()}")

    # bf16 only accelerates on Ampere (2020) and newer GPUs; on older ones it
    # runs in emulation and can be slower than plain fp32, hence the gate
    use_bf16 = device.type == "cuda" and torch.cuda.get_device_capability()[0] >= 8
    print(f"Use of mixed precision: {use_bf16}")

    def train_epoch():
        model.train()
        loss_metric = MeanMetric().to(device)
        for x, y in train_loader:
            x = x.to(device, non_blocking=True)
            y = y.to(device, non_blocking=True)
            optimizer.zero_grad()
            with torch.autocast(
                device_type=device.type, dtype=torch.bfloat16, enabled=use_bf16
            ):
                loss = loss_fn(model(x), y)
            loss.backward()
            nn.utils.clip_grad_norm_(model.parameters(), 1.0)
            optimizer.step()
            scheduler.step()  # the schedule advances every batch
            loss_metric.update(loss.detach(), weight=x.size(0))
        return loss_metric.compute().item()

    def evaluate():
        model.eval()
        loss_metric = MeanMetric().to(device)
        acc_metric = MulticlassAccuracy(num_classes=10).to(device)
        for x, y in val_loader:
            x = x.to(device, non_blocking=True)
            y = y.to(device, non_blocking=True)
            with torch.inference_mode():
                logits = model(x)
                preds = logits.argmax(dim=1)
            loss_metric.update(loss_fn(logits, y), weight=x.size(0))
            acc_metric.update(preds, y)
        return loss_metric.compute().item(), acc_metric.compute().item()

    def fit():
        history = {"train_loss": [], "val_loss": [], "val_acc": [], "lr": []}
        best_acc, best_epoch, wait = 0.0, 0, 0
        for epoch in range(1, max_epochs + 1):
            t0 = time.perf_counter()
            train_loss = train_epoch()
            val_loss, val_acc = evaluate()
            history["train_loss"].append(train_loss)
            history["val_loss"].append(val_loss)
            history["val_acc"].append(val_acc)
            history["lr"].append(scheduler.get_last_lr()[0])
            marker = ""
            if val_acc > best_acc:
                best_acc, best_epoch, wait = val_acc, epoch, 0
                torch.save(
                    {"model": model.state_dict(), "epoch": epoch, "val_acc": val_acc},
                    root / "best.pt",
                )
                marker = " *"
            else:
                wait += 1
            print(
                f"epoch {epoch:2d}  train {train_loss:.3f}  val {val_loss:.3f}  "
                f"acc {val_acc:5.1%}  lr {scheduler.get_last_lr()[0]:.2e}  "
                f"{time.perf_counter() - t0:4.1f} s{marker}"
            )
            if wait >= patience:
                print(f"early stop: no improvement for {patience} epochs")
                break
        return history, best_epoch, best_acc

    fit()  # returns history, best_epoch, best_acc

    ckpt = torch.load(root / "best.pt", weights_only=True)
    print(f"Best epoch: {ckpt['epoch']} (val acc: {ckpt['val_acc']:.1%})")
    model.load_state_dict(ckpt["model"])
    val_loss, val_acc = evaluate()
    print(f"Restored model: val loss {val_loss:.3f}, acc {val_acc:.1%}")


if __name__ == "__main__":
    main()