PT05: Training deeper networks: solutions¶

The solutions to the exercises of PT05. Each solution comes under the heading it has in the lab, with a short explanation followed by the code. If you fall behind during the lab, copy the solution cell into your notebook in place of your version and continue from there.

2. Activity 1: batch normalization ★★¶

register_buffer stores the running statistics in the module without making them trainable. In training mode we normalize with the mean and the variance over the batch and spatial axes (0, 2, 3), both of shape (C,); indexing with [:, None, None] broadcasts them over the height and width. lerp_(new, m) computes $(1 - m)\,\mu + m\,\widetilde\mu$ in place, inside torch.no_grad(). As in PyTorch, the running variance uses the unbiased estimate, var * n / (n - 1), with $n = BHW$. In inference mode we normalize with the running statistics instead.

In [ ]:
class MyBatchNorm2d(torch.nn.Module):
    def __init__(self, channels: int, eps: float = 1e-5, momentum: float = 0.1):
        super().__init__()
        self.eps, self.momentum = eps, momentum
        self.weight = Parameter(torch.ones(channels))
        self.bias = Parameter(torch.zeros(channels))
        self.register_buffer("running_mean", torch.zeros(channels))
        self.register_buffer("running_var", torch.ones(channels))

    def forward(self, xb: Float[torch.Tensor, "batch channels height width"]) -> Float[torch.Tensor, "batch channels height width"]:
        if self.training:
            mean = xb.mean(dim=(0, 2, 3))
            var = xb.var(dim=(0, 2, 3), correction=0)
            with torch.no_grad():
                n = xb.numel() / xb.shape[1]
                self.running_mean.lerp_(mean, self.momentum)
                self.running_var.lerp_(var * n / (n - 1), self.momentum)
        else:
            mean, var = self.running_mean, self.running_var
        normalized = (xb - mean[:, None, None]) / torch.sqrt(var[:, None, None] + self.eps)
        return self.weight[:, None, None] * normalized + self.bias[:, None, None]

3. Activity 2: residual blocks ★¶

norm creates a new layer each time it is called, so the two BN layers (or the two identities) are separate modules. The convolutions have a bias only without BN. In forward, the ReLU comes after the sum, so a block with $f(\mathbf{x}) = 0$ returns $\text{ReLU}(\mathbf{x})$, and a plain block returns $\text{ReLU}(f(\mathbf{x}))$.

In [ ]:
class ResidualBlock(torch.nn.Module):
    def __init__(self, channels: int, residual: bool = True, batchnorm: bool = True):
        super().__init__()
        self.residual = residual
        norm = (lambda: torch.nn.BatchNorm2d(channels)) if batchnorm else torch.nn.Identity
        self.conv1 = torch.nn.Conv2d(channels, channels, 3, padding=1, bias=not batchnorm)
        self.bn1 = norm()
        self.conv2 = torch.nn.Conv2d(channels, channels, 3, padding=1, bias=not batchnorm)
        self.bn2 = norm()

    def forward(self, xb: Float[torch.Tensor, "batch channels height width"]) -> Float[torch.Tensor, "batch channels height width"]:
        h = self.bn2(self.conv2(F.relu(self.bn1(self.conv1(xb)))))
        return F.relu(xb + h if self.residual else h)

In the recorded run, the plain network gets worse with depth on the training set itself, and from 18 layers on it does not learn at all (loss at chance level). This is an optimization problem, not overfitting. BN makes the deeper plain networks trainable, but at 34 layers their training loss is much worse than at 18. The residual network has the lowest training loss at every depth and still trains well at 34 layers. On validation accuracy, plain + BN is slightly ahead at 18 layers: with only two epochs on 10,000 images, deeper is not always better, and the deck's CIFAR-10 experiment trains for much longer.

4. Activity 3: dropout ★¶

In inference mode, or with $p = 0$, the layer returns its input. Otherwise torch.rand_like(xb) > self.p is a new mask at every call, with each entry kept with probability $1 - p$; multiplying by it and dividing by $1 - p$ keeps the expected value of every entry unchanged.

In [ ]:
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, "..."]:
        if not self.training or self.p == 0:
            return xb
        mask = (torch.rand_like(xb) > self.p).to(xb.dtype)
        return xb * mask / (1 - self.p)
  1. With the division during training (inverted dropout), inference is exactly the original network and needs no special code. The trained weights can be used, exported or fused (as in Optional A) without knowing that dropout was used.
  2. Batch normalization, which uses the statistics of the batch during training and the running statistics during inference (Activity 1 and Optional B), and dropout (Activity 3). An augmentation layer is a third example (Optional C).

Optional A: fusing batch normalization ★★¶

a has one entry per output channel. Multiplying the weight by a[:, None, None, None] scales every filter by its channel's $a_c$, and the new bias is $a_c b_c + \beta_c - a_c \mu_c$. Working on a deep copy, inside torch.no_grad(), leaves conv and bn untouched.

In [ ]:
def fuse_conv_bn(conv: torch.nn.Conv2d, bn: torch.nn.BatchNorm2d) -> torch.nn.Conv2d:
    fused = copy.deepcopy(conv)
    with torch.no_grad():
        a = bn.weight / torch.sqrt(bn.running_var + bn.eps)
        fused.weight.copy_(conv.weight * a[:, None, None, None])
        fused.bias.copy_(a * conv.bias + bn.bias - a * bn.running_mean)
    return fused

During training, BN uses the statistics of the current mini-batch, which change at every step and depend on the other examples in the batch. The layer is then not a fixed affine map of each input, and its gradient also flows through the mean and the variance.

Optional B: two bugs with batch normalization ★★¶

Case 1. The fine-tuning step put the model in training mode, and nothing switched it back (torch.no_grad() does not change the mode). In training mode, BN normalizes with the statistics of the current batch, so the output for one image depends on the other images, and on how many there are. A single image is normalized only with its own pixels. At inference we want the running statistics, which model.eval() selects.

Case 2. torch.no_grad() stops the gradients, but the running statistics are not computed with gradients: they are updated in the forward pass whenever the model is in training mode. The loop replaced the running averages with the statistics of inverted images, which are very different from those of the training images. Nothing was trained, but the model changed. The same happens if we "evaluate" in training mode on a batch of a single class.

safe_evaluate saves the mode and a copy of every buffer, switches to inference mode, and restores the previous mode in a finally block, so that it is restored even if the model raises an error. The assert then compares the buffers with their copies.

In [ ]:
@torch.no_grad()
def safe_evaluate(model, x: Float[torch.Tensor, "batch channels height width"]) -> Float[torch.Tensor, "batch n_classes"]:
    was_training = model.training
    before = {name: buffer.clone() for name, buffer in model.named_buffers()}
    model.eval()
    try:
        probabilities = model(x).softmax(dim=1)
    finally:
        model.train(was_training)
    for name, buffer in model.named_buffers():
        assert torch.equal(buffer, before[name]), f"Evaluation changed the buffer {name}"
    return probabilities

Optional C: data augmentation and MixUp ★★¶

Small rotations, translations and rescalings keep a character readable, so augment applies a random affine transformation to each image, filling the empty border with background. mixup samples one $\lambda$ for the batch and one permutation, and mixes the images and the one-hot targets with the same weights.

In [ ]:
augmentations = v2.RandomAffine(degrees=10, translate=(0.1, 0.1), scale=(0.9, 1.1), fill=background)

def augment(x: Float[torch.Tensor, "batch 1 height width"]) -> Float[torch.Tensor, "batch 1 height width"]:
    return torch.stack([augmentations(image) for image in x])

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]:
    lam = torch.distributions.Beta(alpha, alpha).sample()
    perm = torch.randperm(len(x))
    targets = F.one_hot(y, n_classes).float()
    return lam * x + (1 - lam) * x[perm], lam * targets + (1 - lam) * targets[perm]

In the recorded run, augmentation gives the lowest validation loss and the highest accuracy (0.214 and 93.9%), followed by MixUp (0.316, 92.3%) and by the unregularized model (0.560, 81.2%), which overfits the 10,000 images within a few epochs. With all 54,000 images the baseline overfits less, so the gaps should shrink. The targets of MixUp are soft, so their cross-entropy is at least the entropy of the target distribution, which is positive whenever $0 < \lambda < 1$. Small rotations, translations and rescalings keep the characters readable, which is why they are reasonable augmentations here.