PT05: Training deeper networks¶
This lab follows the lecture on deeper models. We implement batch normalization and dropout from scratch, build residual blocks, and repeat the opening experiment of the lecture on KMNIST, the dataset of PT04. To keep the experiments fast, after checking that our layers compute the same thing as PyTorch's, we use torch.nn layers when training larger models. Nothing here uses your code from PT04.
| Activity | What you write | Section | |
|---|---|---|---|
| 1 | Batch normalization | 2 | ★★ |
| 2 | A residual block | 3 | ★ |
| 3 | Dropout | 4 | ★ |
Exercises are rated from 1 to 3 stars based on expected difficulty. Three optional sections close the notebook: fusing batch normalization into a convolution, two bugs with batch normalization, and data augmentation with MixUp.
How to work. Run the cells in order. Each activity ends with a one-line check that stops with a message telling you what to look at. A function you have not written yet raises NotImplementedError the first time it is used, so complete the activities in order. Data loading and the training loop are given. The solutions, with a short explanation for each exercise, are in PT05 solutions.
We assume PT01 and PT02 (tensors, autograd and the training loop) and the CNN layers of PT04. Everything runs on the CPU; the depth experiment takes a few minutes. In Colab, a GPU runtime makes training faster but is not needed.
Try to solve these exercises without AI coding assistants.
1. Setup and data¶
We use jaxtyping to annotate shapes, as in PT02, and torchvision for loading and preprocessing the data. The second code cell defines the checks of the activities.
%pip install jaxtyping --quiet
import copy
import math
import time
import matplotlib.pyplot as plt
import torch
import torch.nn.functional as F
import torchvision
from torch.nn import Parameter
from torchvision.transforms import v2
from jaxtyping import Float, Int
torch.manual_seed(0)
torch.set_printoptions(precision=3, sci_mode=False)
print("PyTorch", torch.__version__, "· torchvision", torchvision.__version__)
#@title Checks for the activities (run this cell; you do not need to read it)
def check_batchnorm(MyBatchNorm2d):
torch.manual_seed(0)
bn = MyBatchNorm2d(3)
parameters, buffers = dict(bn.named_parameters()), dict(bn.named_buffers())
assert set(parameters) == {"weight", "bias"}, f"The trainable parameters should be weight and bias, found {sorted(parameters)}."
assert set(buffers) == {"running_mean", "running_var"}, f"Register running_mean and running_var as buffers, found {sorted(buffers)}."
with torch.no_grad():
bn.weight.uniform_(0.5, 2.)
bn.bias.normal_()
scale = torch.tensor([1., 3., 0.5])[None, :, None, None]
offset = torch.tensor([2., -1., 5.])[None, :, None, None]
mean, var, biased_var = torch.zeros(3), torch.ones(3), torch.ones(3) # Updated by F.batch_norm and below.
bn.train()
for step in (1, 2, 3):
x = (torch.randn(8, 3, 5, 6) * scale + offset).requires_grad_()
out = bn(x)
expected = F.batch_norm(x.detach(), mean, var, bn.weight, bn.bias, training=True, momentum=0.1, eps=1e-5)
biased_var.lerp_(x.detach().var(dim=(0, 2, 3), correction=0), 0.1)
assert out.shape == x.shape, f"The output should have the shape of the input, {tuple(x.shape)}."
assert torch.allclose(out, expected, atol=1e-5), \
"Wrong output in training mode: normalize each channel with the mean and variance of the mini-batch."
assert not bn.running_mean.requires_grad, "Update the running statistics inside torch.no_grad()."
assert torch.allclose(bn.running_mean, mean, atol=1e-5), f"Wrong running_mean after {step} training steps (momentum 0.1)."
assert torch.allclose(bn.running_var, var, atol=1e-4) or torch.allclose(bn.running_var, biased_var, atol=1e-4), \
f"Wrong running_var after {step} training steps (momentum 0.1)."
bn.eval()
x = torch.randn(4, 3, 5, 6) * scale + offset
saved = bn.running_mean.clone()
expected = F.batch_norm(x, bn.running_mean, bn.running_var, bn.weight, bn.bias, training=False, eps=1e-5)
assert torch.allclose(bn(x), expected, atol=1e-5), "Wrong output in inference mode: normalize with the running statistics."
assert torch.equal(bn.running_mean, saved), "Inference must not change the running statistics."
print("MyBatchNorm2d is correct.")
def check_residual(ResidualBlock):
count = lambda module: sum(p.numel() for p in module.parameters())
x = torch.randn(4, 8, 6, 6, generator=torch.Generator().manual_seed(8))
block = ResidualBlock(8)
assert count(block) == 2 * 8 * 8 * 9 + 4 * 8, \
f"{count(block)} parameters: expected two 3x3 convolutions without bias and two BN layers."
for residual, expected, message in [(True, F.relu(x), "With f(x) = 0, a residual block should return ReLU(x)."),
(False, torch.zeros_like(x), "With residual=False the block should return ReLU(f(x)).")]:
block = ResidualBlock(8, residual=residual)
with torch.no_grad(): # Setting gamma of the last BN layer to zero makes f(x) = 0.
[m for m in block.modules() if isinstance(m, torch.nn.BatchNorm2d)][-1].weight.zero_()
block.eval()
assert torch.allclose(block(x), expected, atol=1e-6), message
no_bn = ResidualBlock(8, batchnorm=False)
assert not any(isinstance(m, torch.nn.BatchNorm2d) for m in no_bn.modules()), "batchnorm=False should not use BN."
assert count(no_bn) == 2 * (8 * 8 * 9 + 8), "Without BN, the convolutions keep their bias."
print("ResidualBlock is correct.")
def check_dropout(MyDropout):
torch.manual_seed(9)
dropout = MyDropout(0.3)
dropout.eval()
x = torch.randn(64, 1, 28, 28)
assert torch.equal(dropout(x), x), "In inference mode, dropout must return its input unchanged."
dropout.train()
out = dropout(torch.ones(200_000))
dropped = (out == 0).float().mean().item()
assert abs(dropped - 0.3) < 0.01, f"{dropped:.1%} of the values were dropped, expected about 30%."
kept = out[out != 0]
assert torch.allclose(kept, torch.full_like(kept, 1 / 0.7)), "Kept values must be divided by 1 - p."
assert not torch.equal(dropout(torch.ones(1000)), dropout(torch.ones(1000))), "Sample a new mask at every call."
print("MyDropout is correct.")
def check_fusion(fuse_conv_bn):
torch.manual_seed(7)
conv, bn = torch.nn.Conv2d(3, 5, 3, padding=1), torch.nn.BatchNorm2d(5)
with torch.no_grad():
bn.weight.uniform_(0.5, 2.)
bn.bias.normal_()
bn.running_mean.normal_()
bn.running_var.uniform_(0.5, 3.)
bn.eval()
saved = copy.deepcopy((conv.state_dict(), bn.state_dict()))
fused = fuse_conv_bn(conv, bn)
assert isinstance(fused, torch.nn.Conv2d) and fused is not conv, "Return a new torch.nn.Conv2d."
x = torch.randn(2, 3, 9, 9)
with torch.no_grad():
assert torch.allclose(fused(x), bn(conv(x)), atol=1e-5), "The fused layer differs from bn(conv(x))."
for module, state in zip((conv, bn), saved):
assert all(torch.equal(v, state[k]) for k, v in module.state_dict().items()), "fuse_conv_bn modified conv or bn."
print("fuse_conv_bn is correct.")
def check_safe_evaluate(safe_evaluate, model):
model = copy.deepcopy(model)
for mode in [True, False]:
model.train(mode)
state = copy.deepcopy(model.state_dict())
alone = safe_evaluate(model, val_x[:1])
together = safe_evaluate(model, val_x[:64])[:1]
assert torch.allclose(alone, together, atol=1e-5), "The prediction for an image must not depend on the rest of the batch."
assert model.training == mode, "Restore the previous mode of the model."
assert all(torch.equal(state[k], v) for k, v in model.state_dict().items()), "safe_evaluate changed the model."
assert torch.allclose(alone.sum(dim=1), torch.ones(1)), "Return probabilities."
class Sneaky(torch.nn.Module): # A model whose forward always changes its buffer.
def __init__(self):
super().__init__()
self.register_buffer("calls", torch.zeros(()))
def forward(self, x):
self.calls += 1
return x.flatten(1)[:, :10]
try:
safe_evaluate(Sneaky(), val_x[:2])
except AssertionError:
pass
else:
raise AssertionError("safe_evaluate should fail when the call changes a buffer.")
print("safe_evaluate is correct.")
def check_augment_mixup(augment, mixup):
torch.manual_seed(11)
images, labels = val_x[:64], val_y[:64]
augmented = augment(images[:8])
assert augmented.shape == (8, 1, 28, 28) and not torch.equal(augmented, images[:8]), "augment should change the images."
mixed_x, mixed_y = mixup(images, labels)
assert mixed_x.shape == images.shape and mixed_y.shape == (64, 10), "mixup returns images (64, 1, 28, 28) and soft targets (64, 10)."
assert torch.allclose(mixed_y.sum(dim=1), torch.ones(64)), "Mixed targets must sum to 1."
pairs = mixed_y[(mixed_y > 0).sum(dim=1) == 2].sort(dim=1, descending=True).values[:, :2]
assert torch.allclose(pairs, pairs[:1].expand_as(pairs)), "Use a single lambda for the whole batch."
print("augment and mixup are correct.")
As in PT04, we use KMNIST: (28, 28) black-and-white images of cursive Japanese characters (Kuzushiji), in 10 classes, with 60,000 training images. The images are standardized with the mean and standard deviation of the training images, and 6,000 training images are kept aside for validation, with the same split as in PT04. We do not use the test set in this lab.
train_raw = torchvision.datasets.KMNIST("./kmnist", train=True, download=True)
split = torch.randperm(60_000, generator=torch.Generator().manual_seed(0))
train_idx, val_idx = split[:54_000], split[54_000:]
pixels = train_raw.data[train_idx].float() / 255
mean, std = pixels.mean().item(), pixels.std().item()
background = (0 - mean) / std # The value of an empty pixel (0) after standardization.
transform = v2.Compose([
v2.ToImage(),
v2.ToDtype(torch.float32, scale=True),
v2.Normalize((mean,), (std,)),
])
full_data = torchvision.datasets.KMNIST("./kmnist", train=True, transform=transform)
train_data = torch.utils.data.Subset(full_data, train_idx.tolist())
val_data = torch.utils.data.Subset(full_data, val_idx.tolist())
train_loader = torch.utils.data.DataLoader(train_data, batch_size=64, shuffle=True)
val_loader = torch.utils.data.DataLoader(val_data, batch_size=500)
val_x, val_y = next(iter(torch.utils.data.DataLoader(val_data, batch_size=2000)))
xb, yb = next(iter(train_loader))
print(xb.shape, yb.shape)
The training loop is the one of PT04: the mini-batch loop of PT02, with the AdamW optimizer and a validation pass at the end of every epoch. If a GPU is available, fit uses it and moves the model back to the CPU at the end.
device = "cuda" if torch.cuda.is_available() else "cpu"
print("Training on", device)
@torch.no_grad()
def evaluate(model, loader):
model.eval()
model_device = next(model.parameters()).device
total_loss, correct, count = 0.0, 0, 0
for x, y in loader:
x, y = x.to(model_device), y.to(model_device)
logits = model(x)
total_loss += F.cross_entropy(logits, y, reduction="sum").item()
correct += (logits.argmax(dim=1) == y).sum().item()
count += len(y)
return total_loss / count, correct / count
def fit(model, loader=train_loader, epochs=3, lr=1e-3, verbose=True):
model.to(device)
optimizer = torch.optim.AdamW(model.parameters(), lr=lr)
history = {"train_loss": [], "val_loss": [], "val_accuracy": []}
for epoch in range(epochs):
model.train()
start = time.time()
for x, y in loader:
x, y = x.to(device), y.to(device)
optimizer.zero_grad()
loss = F.cross_entropy(model(x), y)
loss.backward()
optimizer.step()
history["train_loss"].append(loss.item())
val_loss, val_accuracy = evaluate(model, val_loader)
history["val_loss"].append(val_loss)
history["val_accuracy"].append(val_accuracy)
if verbose:
print(f"Epoch {epoch + 1}: validation loss {val_loss:.3f}, "
f"accuracy {val_accuracy:.3f} ({time.time() - start:.0f} s)")
model.cpu()
return history
2. Activity 1: batch normalization ★★¶
After a convolution, a batch normalization layer standardizes each channel using every position of every image in the mini-batch:
$$\widetilde{\mu}_c = \frac{1}{BHW}\sum_{b,i,j} Z_{b,c,i,j}, \qquad \widetilde{\sigma}_c^2 = \frac{1}{BHW}\sum_{b,i,j} \left(Z_{b,c,i,j} - \widetilde{\mu}_c\right)^2,$$
$$\text{BN}(Z)_{b,c,i,j} = \gamma_c\, \frac{Z_{b,c,i,j} - \widetilde{\mu}_c}{\sqrt{\widetilde{\sigma}_c^2 + \varepsilon}} + \beta_c,$$
where $\gamma_c, \beta_c$ are trainable and $\varepsilon$ is a small value to avoid division by zero. During inference, the mean and the variance are fixed. In the simplest case, we keep a running average during training:
$$\mu_c \leftarrow (1 - m)\,\mu_c + m\,\widetilde{\mu}_c,$$
and similarly for $\sigma_c^2$. The momentum $m$ is 0.1 in PyTorch. PyTorch updates the running variance with the unbiased estimate of the mini-batch variance (dividing by $BHW - 1$ instead of $BHW$); with thousands of values per channel the two are almost identical, and the check accepts both. Thus, for an input with $C$ channels, the layer has $2C$ trainable parameters and $2C$ untrainable ones.
TODO (★★): implement the layer. As in PyTorch, call the parameters
weight($\gamma$, initialized to ones) andbias($\beta$, zeros), and the running statisticsrunning_mean(zeros) andrunning_var(ones).
Hint 1: non-trainable state in PyTorch should be handled with buffers: they are saved with the model and moved with .to(), but they are not returned by .parameters().
Hint 2: the updates of the running statistics should not be differentiated, so they go within a torch.no_grad() scope to avoid "cluttering" the computational graph.
Hint 3: training and inference mode can be checked with the internal self.training flag.
class MyBatchNorm2d(torch.nn.Module):
def __init__(self, channels: int, eps: float = 1e-5, momentum: float = 0.1):
super().__init__()
# TODO: complete the code.
raise NotImplementedError("Complete Activity 1: MyBatchNorm2d.__init__")
def forward(self, xb: Float[torch.Tensor, "batch channels height width"]) -> Float[torch.Tensor, "batch channels height width"]:
# TODO: complete the code.
raise NotImplementedError("Complete Activity 1: MyBatchNorm2d.forward")
check_batchnorm(MyBatchNorm2d)
In training mode, your layer normalizes a batch of images to mean zero and standard deviation one:
bn = MyBatchNorm2d(1)
out = bn(xb)
print(f"Before: mean {xb.mean():.3f}, std {xb.std():.3f}. After: mean {out.mean():.3f}, std {out.std():.3f}")
3. Activity 2: residual blocks ★¶
In the lecture we saw that very deep plain networks are hard to optimize, and that residual connections fix this. The block we use is the one from the lecture: two 3×3 convolutions with batch normalization, a ReLU between them, the sum with the input, and a final ReLU after the sum:
$$\mathbf{h} = \text{ReLU}\big(\mathbf{x} + f(\mathbf{x})\big), \qquad f(\mathbf{x}) = \text{BN}(\text{Conv}(\text{ReLU}(\text{BN}(\text{Conv}(\mathbf{x}))))).$$
The convolutions have no bias, since BN would remove it anyway.
TODO (★): complete
ResidualBlock, usingtorch.nn.Conv2dandtorch.nn.BatchNorm2dfor speed. Withresidual=False, the same block computes $\text{ReLU}(f(\mathbf{x}))$, which we use as the plain baseline. Withbatchnorm=False, replace the BN layers withtorch.nn.Identity()and keep the bias of the convolutions.
class ResidualBlock(torch.nn.Module):
def __init__(self, channels: int, residual: bool = True, batchnorm: bool = True):
super().__init__()
# TODO: complete the code.
raise NotImplementedError("Complete Activity 2: ResidualBlock.__init__")
def forward(self, xb: Float[torch.Tensor, "batch channels height width"]) -> Float[torch.Tensor, "batch channels height width"]:
# TODO: complete the code.
raise NotImplementedError("Complete Activity 2: ResidualBlock.forward")
check_residual(ResidualBlock)
We now repeat the opening experiment of the lecture on a small scale. Each network has a first convolution with stride 2 (to 16 channels, 14×14), a stack of blocks, global average pooling and a linear layer. We train it on 10,000 training images for two epochs, for three depths and three variants: plain, plain with BN, and residual with BN. This takes a few minutes on a CPU.
Predict. Before running: how will the training loss of the three variants change with depth?
DEPTHS, SUBSET = [2, 8, 16], 10_000
def deep_cnn(n_blocks, residual, batchnorm, channels=16):
return torch.nn.Sequential(
torch.nn.Conv2d(1, channels, 3, stride=2, padding=1), torch.nn.ReLU(),
*[ResidualBlock(channels, residual, batchnorm) for _ in range(n_blocks)],
torch.nn.AdaptiveAvgPool2d(1), torch.nn.Flatten(), torch.nn.Linear(channels, 10))
subset_loader = torch.utils.data.DataLoader(torch.utils.data.Subset(train_data, range(SUBSET)), batch_size=64, shuffle=True)
train_check = next(iter(torch.utils.data.DataLoader(torch.utils.data.Subset(train_data, range(2000)), batch_size=2000)))
variants = {"Plain": (False, False), "Plain + BN": (False, True), "Residual + BN": (True, True)}
depth_results = {name: {"train_loss": [], "val_accuracy": []} for name in variants}
for n_blocks in DEPTHS:
for name, (residual, batchnorm) in variants.items():
torch.manual_seed(0)
model = deep_cnn(n_blocks, residual, batchnorm)
start = time.time()
history = fit(model, loader=subset_loader, epochs=2, lr=1e-3, verbose=False)
with torch.no_grad():
model.eval()
train_loss = F.cross_entropy(model(train_check[0]), train_check[1]).item()
depth_results[name]["train_loss"].append(train_loss)
depth_results[name]["val_accuracy"].append(history["val_accuracy"][-1])
print(f"{2 * n_blocks + 2:>2} layers, {name:<13}: training loss {train_loss:.3f}, "
f"validation accuracy {history['val_accuracy'][-1]:.3f} ({time.time() - start:.0f} s)")
layers = [2 * n + 2 for n in DEPTHS]
fig, axes = plt.subplots(1, 2, figsize=(10, 3.5))
for name, result in depth_results.items():
axes[0].plot(layers, result["train_loss"], "o-", label=name)
axes[1].plot(layers, result["val_accuracy"], "o-", label=name)
axes[0].axhline(math.log(10), color="gray", linestyle="--", label="Chance")
axes[0].set(xlabel="Layers", ylabel="Training loss")
axes[1].set(xlabel="Layers", ylabel="Validation accuracy", ylim=(0, 1))
fig.legend(*axes[0].get_legend_handles_labels(), loc="upper center", ncol=4, bbox_to_anchor=(0.5, 1.08))
fig.tight_layout()
plt.show()
4. Activity 3: dropout ★¶
Recall that dropout during training works as:
$$\text{Dropout}(X) = \frac{X \odot M}{1 - p},$$
where $M$ is a binary mask whose entries are 0 with probability $p$, sampled again at every call. During inference, the layer does nothing and leaves the input untouched. As we saw in the lecture, dropout is used much less in modern CNNs and LLMs than it used to be, but it is still used, for instance when fine-tuning large models.
TODO (★): implement the dropout layer below.
Hint 1: if $u$ is sampled according to a uniform distribution, $u > p$ will be 0 with probability $p$.
Hint 2: as for batch normalization, use the internal training flag.
class MyDropout(torch.nn.Module):
def __init__(self, p: float = 0.5):
super().__init__()
self.p = p
def forward(self, xb: Float[torch.Tensor, "..."]) -> Float[torch.Tensor, "..."]:
# TODO: complete the code.
raise NotImplementedError("Complete Activity 3: MyDropout.forward")
check_dropout(MyDropout)
Discuss
- Why do we divide by $1 - p$ during training, rather than multiplying by $1 - p$ during inference? Both give the same expected value.
- Where in this notebook does a layer behave differently in training and in inference mode?
This is the end of the core of the lab.
Optional A: fusing batch normalization ★★¶
The optional sections can be done in any order. At inference, the statistics are fixed, so batch normalization is just an affine function of each channel:
$$\text{BN}(z) = a \odot z + c, \qquad a_c = \frac{\gamma_c}{\sqrt{\sigma_c^2 + \varepsilon}}, \qquad c_c = \beta_c - a_c\,\mu_c.$$
Composed with the convolution before it, it gives another convolution: each filter is multiplied by $a_c$, and the new bias is $a_c b_c + c_c$. Deployed networks do this to save one layer.
TODO (★★): complete
fuse_conv_bn, which returns a newtorch.nn.Conv2dthat computesbn(conv(x))in inference mode, for a convolution with a bias and atorch.nn.BatchNorm2dlayer (yourMyBatchNorm2dhas the same attributes). Do not modifyconvorbn.
Hint: start from copy.deepcopy(conv) and overwrite its parameters within torch.no_grad().
def fuse_conv_bn(conv: torch.nn.Conv2d, bn: torch.nn.BatchNorm2d) -> torch.nn.Conv2d:
# TODO: complete the code.
raise NotImplementedError("Optional exercise: fuse_conv_bn")
check_fusion(fuse_conv_bn)
Discuss. Why can we fuse the two layers only at inference, and not during training?
Optional B: two bugs with batch normalization ★★¶
Batch normalization is easy to get wrong, because it has two modes and a hidden state. We first train a small CNN with batch normalization (using PyTorch's layers, which compute the same thing as yours). Then we look at two pieces of code that have a bug.
def bn_cnn():
def block(c_in, c_out):
return [torch.nn.Conv2d(c_in, c_out, 3, padding=1, bias=False), torch.nn.BatchNorm2d(c_out), torch.nn.ReLU()]
return torch.nn.Sequential(*block(1, 32), torch.nn.MaxPool2d(2), *block(32, 64), torch.nn.MaxPool2d(2),
*block(64, 64), torch.nn.AdaptiveAvgPool2d(1), torch.nn.Flatten(), torch.nn.Linear(64, 10))
torch.manual_seed(0)
model_bn = bn_cnn()
_ = fit(model_bn, epochs=1, lr=2e-3)
Case 1. Is the prediction a property of the image? A colleague fine-tuned the model for one more step on a new batch of data, and then used it to classify a few images. They noticed that the probability given to the same image changes when it is classified together with other images.
case1_model = copy.deepcopy(model_bn)
optimizer = torch.optim.AdamW(case1_model.parameters(), lr=1e-4)
case1_model.train()
x, y = next(iter(train_loader))
optimizer.zero_grad()
F.cross_entropy(case1_model(x), y).backward()
optimizer.step()
@torch.no_grad()
def predict(model, images):
return model(images).softmax(dim=1)
image, label = val_x[:1], int(val_y[0])
same_class = val_x[val_y == label][1:8]
other_classes = val_x[val_y != label][:7]
print("Alone: ", predict(case1_model, image)[0, label].item())
print("With 7 of the same class: ", predict(case1_model, torch.cat([image, same_class]))[0, label].item())
print("With 7 of other classes: ", predict(case1_model, torch.cat([image, other_classes]))[0, label].item())
Case 2. Who changed my model? A second colleague wanted to quickly check how the model handles images with inverted colors (dark characters on a light background, the opposite of KMNIST), and wrote a short loop under torch.no_grad(). After that, the accuracy on the ordinary validation set is lower than before.
case2_model = copy.deepcopy(model_bn)
print("Validation accuracy before:", evaluate(case2_model, val_loader)[1])
with torch.no_grad():
case2_model.train()
for x, y in torch.utils.data.DataLoader(val_data, batch_size=500):
inverted = (1 - 2 * mean) / std - x # The standardized version of 1 - pixel.
accuracy = (case2_model(inverted).argmax(dim=1) == y).float().mean()
print("Validation accuracy after: ", evaluate(case2_model, val_loader)[1])
TODO (★★): explain what goes wrong in each case. Then write
safe_evaluate(model, x), which returns the predicted probabilities for a batchxin a way that avoids both bugs. It must (1) use inference mode, (2) check with anassertthat the call did not change any buffer of the model, and (3) leave the model in the mode (training or inference) it was in before the call.
def safe_evaluate(model, x: Float[torch.Tensor, "batch channels height width"]) -> Float[torch.Tensor, "batch n_classes"]:
# TODO: complete the code.
raise NotImplementedError("Optional exercise: safe_evaluate")
check_safe_evaluate(safe_evaluate, model_bn)
Optional C: data augmentation and MixUp ★★¶
The original version of this lab started with a question: which data augmentations make sense for this dataset?
TODO (★): choose a set of suitable augmentations from torchvision's transforms and complete
augmentbelow, which receives a batch of standardized images. Think about which transformations keep a character recognizable: a horizontal flip, for instance, would turn many of them into a different character (or into no character at all).
TODO (★★): complete
mixup(x, y, alpha). Sample $\lambda \sim \text{Beta}(\alpha, \alpha)$ once per batch and a random permutation of the batch, and return the mixed images $\lambda x + (1 - \lambda) x_\pi$ together with the mixed one-hot targets $\lambda\, \text{onehot}(y) + (1 - \lambda)\, \text{onehot}(y_\pi)$.F.cross_entropyaccepts these soft targets directly.
The cell after the checks trains the same residual network with no regularization, with your augmentations, and with MixUp, on 10,000 training images.
def augment(x: Float[torch.Tensor, "batch 1 height width"]) -> Float[torch.Tensor, "batch 1 height width"]:
# TODO: complete the code.
raise NotImplementedError("Optional exercise: augment")
def mixup(x: Float[torch.Tensor, "batch channels height width"], y: Int[torch.Tensor, "batch"], alpha: float = 0.4, n_classes: int = 10) -> tuple[torch.Tensor, torch.Tensor]:
# TODO: complete the code.
raise NotImplementedError("Optional exercise: mixup")
check_augment_mixup(augment, mixup)
fig, axes = plt.subplots(1, 8, figsize=(8, 1.3))
for ax, image in zip(axes, augment(xb[:8])):
ax.imshow(image[0], cmap="gray_r")
ax.axis("off")
plt.show()
class Regularized(torch.nn.Module):
# Augmentation as a layer of the model, active only in training mode (as in the lecture).
def __init__(self, network, mode):
super().__init__()
self.network, self.mode = network, mode
def forward(self, x):
if self.training and self.mode == "augment":
x = augment(x.cpu()).to(x.device)
return self.network(x)
def fit_mixup(model, loader, epochs, lr=1e-3):
# The same loop as fit, with mixed inputs and soft targets.
model.to(device)
optimizer = torch.optim.AdamW(model.parameters(), lr=lr)
history = {"train_loss": [], "val_loss": [], "val_accuracy": []}
for _ in range(epochs):
model.train()
for x, y in loader:
x, soft = mixup(x.to(device), y.to(device))
optimizer.zero_grad()
loss = F.cross_entropy(model(x), soft)
loss.backward()
optimizer.step()
history["train_loss"].append(loss.item())
val_loss, val_accuracy = evaluate(model, val_loader)
history["val_loss"].append(val_loss)
history["val_accuracy"].append(val_accuracy)
model.cpu()
return history
REGULARIZATION_EPOCHS = 6
regularization = {}
for mode in ["none", "augment", "mixup"]:
torch.manual_seed(0)
model = Regularized(deep_cnn(3, residual=True, batchnorm=True, channels=32), mode)
start = time.time()
if mode == "mixup":
regularization[mode] = fit_mixup(model, subset_loader, REGULARIZATION_EPOCHS)
else:
regularization[mode] = fit(model, loader=subset_loader, epochs=REGULARIZATION_EPOCHS, verbose=False)
print(f"{mode:<8}: validation loss {regularization[mode]['val_loss'][-1]:.3f}, "
f"accuracy {regularization[mode]['val_accuracy'][-1]:.3f} ({time.time() - start:.0f} s)")
fig, axes = plt.subplots(1, 2, figsize=(10, 3.5))
for mode, history in regularization.items():
epochs = range(1, len(history["val_loss"]) + 1)
axes[0].plot(epochs, history["val_loss"], "o-", label=mode)
axes[1].plot(epochs, history["val_accuracy"], "o-", label=mode)
axes[0].set(xlabel="Epoch", ylabel="Validation loss")
axes[1].set(xlabel="Epoch", ylabel="Validation accuracy")
axes[0].legend()
fig.tight_layout()
plt.show()
Discuss. Which variant has the lowest validation loss, and which the highest accuracy? With MixUp, the training loss is never close to zero, even for a perfect classifier. Why? Do you expect the ranking to change with more epochs, or with all 54,000 training images?
Sources¶
- Simone Scardapane, original Colab lab: Convolutional neural networks (from scratch).
- NNDS 2026 lecture on deeper models (normalization, residual connections, regularization).
- PT02 (the training loop) and PT04 (the dataset and the CNN layers).
- KMNIST: Clanuwat et al. (2018), Deep learning for classical Japanese literature, dataset at github.com/rois-codh/kmnist (CC BY-SA 4.0).
- Batch normalization: Ioffe and Szegedy (2015), ICML. Residual networks: He et al. (2016), CVPR. Dropout: Srivastava et al. (2014), JMLR. MixUp: Zhang et al. (2018), ICLR.