{ "cells": [ { "cell_type": "markdown", "id": "solutions-intro", "metadata": {}, "source": [ "# PT04: Convolutional neural networks from scratch: solutions\n", "\n", "The solutions to the exercises of [PT04](https://colab.research.google.com/github/sscardapane/teaching-materials/blob/main/notebooks/PT04_Convolutional_neural_networks.ipynb). 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." ] }, { "cell_type": "markdown", "id": "heading-1", "metadata": {}, "source": [ "## 2. Layers are modules" ] }, { "cell_type": "markdown", "id": "cnn-conv2d-answer", "metadata": {}, "source": [ "The output has shape (64, 16, 14, 14), since $\\lfloor (28 + 2\\cdot 2 - 5)/2 \\rfloor + 1 = 14$. The weight has shape (16, 1, 5, 5) and the bias (16), for 416 parameters. The number of parameters does not depend on the size of the image." ] }, { "cell_type": "markdown", "id": "heading-3", "metadata": {}, "source": [ "## 3. Activity 1: a convolutional layer ★★" ] }, { "cell_type": "markdown", "id": "cnn-conv-explanation", "metadata": {}, "source": [ "The weight holds one $(C, s, s)$ filter per output channel, as in `torch.nn.Conv2d`, scaled by $\\sqrt{2/(Cs^2)}$ (He initialization). Both tensors are wrapped in `Parameter`, so that `model.parameters()` returns them. In `forward`, `F.unfold` returns the patches $U(X)$ with shape $(B, Cs^2, L)$, and `self.weight.view(C', -1)` flattens each filter in the same order, so one matrix product gives $(B, C', L)$. The bias is added to every position. With stride 1 there are $L = H'W'$ windows, where $H' = H + 2p - s + 1$, and a `view` restores the two spatial axes." ] }, { "cell_type": "code", "execution_count": null, "id": "cnn-conv-reference", "metadata": {}, "outputs": [], "source": [ "class MyConv2d(torch.nn.Module):\n", " def __init__(self, in_channels: int, out_channels: int, kernel_size: int, padding: int = 0):\n", " super().__init__()\n", " self.kernel_size, self.padding = kernel_size, padding\n", " fan_in = in_channels * kernel_size ** 2\n", " self.weight = Parameter(torch.randn(out_channels, in_channels, kernel_size, kernel_size) * math.sqrt(2 / fan_in))\n", " self.bias = Parameter(torch.zeros(out_channels))\n", "\n", " def forward(self, xb: Float[torch.Tensor, \"batch in_channels height width\"]) -> Float[torch.Tensor, \"batch out_channels new_height new_width\"]:\n", " B, _, H, W = xb.shape\n", " s, p = self.kernel_size, self.padding\n", " U = F.unfold(xb, s, padding=p) # (B, C s^2, L)\n", " Z = self.weight.view(self.weight.shape[0], -1) @ U # (B, C', L)\n", " Z = Z + self.bias[:, None]\n", " return Z.view(B, -1, H + 2 * p - s + 1, W + 2 * p - s + 1)" ] }, { "cell_type": "markdown", "id": "heading-6", "metadata": {}, "source": [ "## 4. Activity 2: pooling ★" ] }, { "cell_type": "markdown", "id": "cnn-pool-explanation", "metadata": {}, "source": [ "With `stride=k`, `F.unfold` returns the non-overlapping $k \\times k$ windows, with shape $(B, Ck^2, L)$. Its rows are ordered by channel first, so viewing the result as $(B, C, k^2, L)$ separates the channels from the positions inside each window. The maximum over the window axis gives $(B, C, L)$, which we reshape to $(B, C, H/k, W/k)$. (`H // k` also handles sizes that are not multiples of $k$: `unfold` drops the last rows and columns, as PyTorch's max-pooling does.)" ] }, { "cell_type": "code", "execution_count": null, "id": "cnn-pool-reference", "metadata": {}, "outputs": [], "source": [ "class MyMaxPool2d(torch.nn.Module):\n", " def __init__(self, kernel_size: int):\n", " super().__init__()\n", " self.kernel_size = kernel_size\n", "\n", " def forward(self, xb: Float[torch.Tensor, \"batch channels height width\"]) -> Float[torch.Tensor, \"batch channels reduced_height reduced_width\"]:\n", " B, C, H, W = xb.shape\n", " k = self.kernel_size\n", " patches = F.unfold(xb, k, stride=k).view(B, C, k * k, -1)\n", " return patches.max(dim=2).values.view(B, C, H // k, W // k)" ] }, { "cell_type": "markdown", "id": "cnn-pool-grad-answer", "metadata": {}, "source": [ "Only the maximum of each window gets a gradient, equal to 1; all other entries get 0. Like ReLU, max-pooling does not change the values that pass through it: it only routes the gradient to the entries that were selected in the forward pass." ] }, { "cell_type": "markdown", "id": "heading-10", "metadata": {}, "source": [ "## 5. Activity 3: building the network ★" ] }, { "cell_type": "markdown", "id": "cnn-model-explanation", "metadata": {}, "source": [ "Two stages of convolution, ReLU and max-pooling reduce the image from 28×28 to 7×7 while the channels grow to 64. A third convolution is followed by global average pooling, which gives one vector of 64 values per image, and a linear layer gives the 10 logits. The model has 56,394 parameters, about half those of the MLP below. Other choices of layers and channels work as well." ] }, { "cell_type": "code", "execution_count": null, "id": "cnn-model-reference", "metadata": {}, "outputs": [], "source": [ "class MyCNN(torch.nn.Module):\n", " def __init__(self, n_classes: int = 10):\n", " super().__init__()\n", " self.conv1 = MyConv2d(1, 32, 3, padding=1)\n", " self.conv2 = MyConv2d(32, 64, 3, padding=1)\n", " self.conv3 = MyConv2d(64, 64, 3, padding=1)\n", " self.pool = MyMaxPool2d(2)\n", " self.head = MyLinear(64, n_classes)\n", "\n", " def forward(self, xb: Float[torch.Tensor, \"batch channels height width\"]) -> Float[torch.Tensor, \"batch n_classes\"]:\n", " h = self.pool(F.relu(self.conv1(xb))) # (B, 32, 14, 14)\n", " h = self.pool(F.relu(self.conv2(h))) # (B, 64, 7, 7)\n", " h = F.relu(self.conv3(h)) # (B, 64, 7, 7)\n", " return self.head(global_avg_pool(h))" ] }, { "cell_type": "markdown", "id": "heading-13", "metadata": {}, "source": [ "## 6. Activity 4: what did the network learn? ★★" ] }, { "cell_type": "markdown", "id": "cnn-occlusion-explanation", "metadata": {}, "source": [ "We copy the image once for every position of the square, cover a different square in each copy with `background`, and classify the whole batch with one forward pass. `model.eval()` and `@torch.no_grad()` make the call an inference: layers such as dropout or batch normalization use their inference behavior, and no graph is recorded. The probabilities of `label` are reshaped to one row per vertical position and one column per horizontal position." ] }, { "cell_type": "code", "execution_count": null, "id": "cnn-occlusion-reference", "metadata": {}, "outputs": [], "source": [ "@torch.no_grad()\n", "def occlusion_map(model, image: Float[torch.Tensor, \"1 height width\"], label: int, patch: int = 7, stride: int = 3) -> Float[torch.Tensor, \"rows cols\"]:\n", " model.eval()\n", " H, W = image.shape[-2:]\n", " rows, cols = range(0, H - patch + 1, stride), range(0, W - patch + 1, stride)\n", " batch = image.repeat(len(rows) * len(cols), 1, 1, 1)\n", " for n, (i, j) in enumerate((i, j) for i in rows for j in cols):\n", " batch[n, :, i:i + patch, j:j + patch] = background\n", " probabilities = model(batch).softmax(dim=1)[:, label]\n", " return probabilities.view(len(rows), len(cols))" ] }, { "cell_type": "markdown", "id": "heading-16", "metadata": {}, "source": [ "## 7. The test set" ] }, { "cell_type": "markdown", "id": "cnn-test-answer", "metadata": {}, "source": [ "1. On KMNIST the test images are noticeably harder than images taken from the training set, so the validation set overestimates the accuracy on new data (in the recorded run, by 5 points for the CNN and 7 for the MLP). The gap is larger for the MLP: the CNN, with about half the parameters, uses the structure of images (locality and weight sharing) and generalizes better to new handwriting. Its advantage grows from about 3 points on validation to about 4.5 on test.\n", "2. Convolutions and pooling work for any spatial size, and global pooling always returns one vector per channel, so the classifier receives a vector of the same size. The MLP's first layer has a fixed number of inputs (784) and cannot be applied.\n", "3. For an image of $H \\times W$ pixels and $C$ channels, $U(X)$ has $s^2 C H W$ entries: for a 7×7 kernel, 49 times the input. Libraries never build it explicitly: they use specialized algorithms (direct, Winograd, FFT, or an \"implicit\" matrix product that loads the patches on the fly); see the NVIDIA guide linked in the lecture." ] }, { "cell_type": "markdown", "id": "heading-18", "metadata": {}, "source": [ "## Optional A: stride ★" ] }, { "cell_type": "markdown", "id": "cnn-opt-stride-explanation", "metadata": {}, "source": [ "The only changes from `MyConv2d` are the `stride` argument of `F.unfold`, which keeps one window every `stride` pixels, and the output size used to restore the spatial axes. The kernel size is read from the shape of the weight, so the code does not depend on how `MyConv2d` stores it." ] }, { "cell_type": "code", "execution_count": null, "id": "cnn-opt-stride-reference", "metadata": {}, "outputs": [], "source": [ "class MyStridedConv2d(MyConv2d):\n", " def __init__(self, in_channels: int, out_channels: int, kernel_size: int, stride: int = 1, padding: int = 0):\n", " super().__init__(in_channels, out_channels, kernel_size, padding=padding)\n", " self.stride, self.padding = stride, padding\n", "\n", " def forward(self, xb: Float[torch.Tensor, \"batch in_channels height width\"]) -> Float[torch.Tensor, \"batch out_channels new_height new_width\"]:\n", " B, _, H, W = xb.shape\n", " s, p, t = self.weight.shape[-1], self.padding, self.stride\n", " U = F.unfold(xb, s, padding=p, stride=t) # (B, C s^2, L)\n", " Z = self.weight.view(self.weight.shape[0], -1) @ U + self.bias[:, None]\n", " return Z.view(B, -1, (H + 2 * p - s) // t + 1, (W + 2 * p - s) // t + 1)" ] }, { "cell_type": "markdown", "id": "heading-21", "metadata": {}, "source": [ "## Optional B: depthwise convolutions ★★" ] }, { "cell_type": "markdown", "id": "cnn-depthwise-explanation", "metadata": {}, "source": [ "`F.unfold` orders its rows by channel first, so its output can be viewed as $(B, C, s^2, L)$: one set of patches per channel. Multiplying by the filters, viewed as $(C, s^2, 1)$, and summing over the $s^2$ positions of each window applies each filter to its own channel only, with no matrix product. The weight is initialized with $d = s^2$ inputs per output, since each output sees one channel." ] }, { "cell_type": "code", "execution_count": null, "id": "cnn-depthwise-reference", "metadata": {}, "outputs": [], "source": [ "class MyDepthwiseConv2d(torch.nn.Module):\n", " def __init__(self, channels: int, kernel_size: int, padding: int = 0):\n", " super().__init__()\n", " self.kernel_size, self.padding = kernel_size, padding\n", " self.weight = Parameter(torch.randn(channels, 1, kernel_size, kernel_size) * math.sqrt(2 / kernel_size ** 2))\n", " self.bias = Parameter(torch.zeros(channels))\n", "\n", " def forward(self, xb: Float[torch.Tensor, \"batch channels height width\"]) -> Float[torch.Tensor, \"batch channels new_height new_width\"]:\n", " B, C, H, W = xb.shape\n", " s, p = self.kernel_size, self.padding\n", " patches = F.unfold(xb, s, padding=p).view(B, C, s * s, -1)\n", " Z = (patches * self.weight.view(C, s * s, 1)).sum(dim=2) + self.bias[:, None]\n", " return Z.view(B, C, H + 2 * p - s + 1, W + 2 * p - s + 1)" ] }, { "cell_type": "markdown", "id": "cnn-separable-answer", "metadata": {}, "source": [ "The standard layer has $128 \\cdot 64 \\cdot 9 + 128 = 73{,}856$ parameters. The separable one has $64 \\cdot 9 + 64 = 640$ for the depthwise part and $128 \\cdot 64 + 128 = 8{,}320$ for the pointwise part, for $8{,}960$ in total: about 8 times fewer. Modern CNNs such as ConvNeXt are built around large depthwise convolutions for this reason." ] }, { "cell_type": "markdown", "id": "heading-25", "metadata": {}, "source": [ "## Optional C: translation equivariance ★★" ] }, { "cell_type": "markdown", "id": "cnn-equivariance-explanation", "metadata": {}, "source": [ "The two outputs are `layer(shift(x))` and `shift(layer(x))`; both shifts use `fill=0`, the value of zero-padding. Cropping `border` pixels from each side removes the regions near the edges where the two can differ. `@torch.no_grad()` avoids recording a graph we do not need, and `.item()` returns the largest absolute difference as a Python float." ] }, { "cell_type": "code", "execution_count": null, "id": "cnn-equivariance-reference", "metadata": {}, "outputs": [], "source": [ "@torch.no_grad()\n", "def equivariance_error(layer, x: Float[torch.Tensor, \"batch channels height width\"], dy: int, dx: int, border: int) -> float:\n", " difference = layer(shift(x, dy, dx)) - shift(layer(x), dy, dx)\n", " if border > 0:\n", " difference = difference[..., border:-border, border:-border]\n", " return difference.abs().max().item()" ] }, { "cell_type": "markdown", "id": "cnn-equivariance-answers", "metadata": {}, "source": [ "1. A border of 2, the size of the shift. Since zero-padding and the zeros entering with the shift are the same value, the two computations differ only in two places. In the strip emptied by the shift, `shift(layer(x))` contains the fill value, while `layer(shift(x))` contains the convolution of zeros (the bias). On the opposite side, one pixel wide (the radius of the kernel), the shifted input meets the padding where the original image still had pixels.\n", "2. A border of 3: the second layer spreads these differences by its own radius, one more pixel. Each additional 3×3 layer adds one, as the receptive field grows linearly with depth (see also Optional F).\n", "3. With a shift of 2, pooling commutes with the shift (by one position at the lower resolution). With a shift of 1 it does not: the windows now group different pairs of pixels. Pooling and striding make a CNN equivariant only to shifts that are multiples of the total stride." ] }, { "cell_type": "code", "execution_count": null, "id": "cnn-equivariance-answer-code", "metadata": {}, "outputs": [], "source": [ "for border in range(5):\n", " print(\"One layer, border\", border, \":\", equivariance_error(cnn.conv1, images, 2, 2, border))\n", "two_layers = lambda x: cnn.conv2(F.relu(cnn.conv1(x)))\n", "for border in range(5):\n", " print(\"Two layers, border\", border, \":\", equivariance_error(two_layers, images, 2, 2, border))\n", "pool = MyMaxPool2d(2)\n", "x0 = torch.randn(8, 1, 28, 28) # Random values, so that ties between pixels are unlikely.\n", "for d in [2, 1]:\n", " error = (pool(shift(x0, d, d)) - shift(pool(x0), d // 2, d // 2))[..., 2:-2, 2:-2].abs().max().item()\n", " print(f\"Max-pooling, shift {d}: error {error:.3f}\")" ] }, { "cell_type": "markdown", "id": "cnn-shift-accuracy-answer", "metadata": {}, "source": [ "The MLP collapses after a couple of pixels, since a shifted character activates completely different input weights. The CNN degrades much more slowly. It is not perfectly invariant either: zero-padding, the max-pooling layers (point 3 above) and a 28×28 frame that cuts the character all break the symmetry." ] }, { "cell_type": "markdown", "id": "heading-31", "metadata": {}, "source": [ "## Optional D: a locally-connected layer ★★★" ] }, { "cell_type": "markdown", "id": "cnn-opt-local-explanation", "metadata": {}, "source": [ "The layer has one kernel matrix of shape $(C', Cs^2)$ per window, stacked into a weight of shape $(L, C', Cs^2)$, and one bias vector per window. After `F.unfold`, `einsum(\"lod,bdl->bol\")` multiplies the patch of window $l$ by its own matrix, for every image of the batch. The result is reshaped to the output height and width as in `MyConv2d`." ] }, { "cell_type": "code", "execution_count": null, "id": "cnn-opt-local-reference", "metadata": {}, "outputs": [], "source": [ "class MyLocallyConnected2d(torch.nn.Module):\n", " def __init__(self, in_channels: int, out_channels: int, kernel_size: int, height: int, width: int, padding: int = 0):\n", " super().__init__()\n", " self.kernel_size, self.padding = kernel_size, padding\n", " self.new_height, self.new_width = height + 2 * padding - kernel_size + 1, width + 2 * padding - kernel_size + 1\n", " windows, fan_in = self.new_height * self.new_width, in_channels * kernel_size ** 2\n", " self.weight = Parameter(torch.randn(windows, out_channels, fan_in) * math.sqrt(2 / fan_in))\n", " self.bias = Parameter(torch.zeros(windows, out_channels))\n", "\n", " def forward(self, xb: Float[torch.Tensor, \"batch in_channels height width\"]) -> Float[torch.Tensor, \"batch out_channels new_height new_width\"]:\n", " U = F.unfold(xb, self.kernel_size, padding=self.padding) # (B, C s^2, L)\n", " Z = torch.einsum(\"lod,bdl->bol\", self.weight, U) + self.bias.T # (B, C', L)\n", " return Z.view(xb.shape[0], -1, self.new_height, self.new_width)" ] }, { "cell_type": "markdown", "id": "heading-34", "metadata": {}, "source": [ "## Optional E: patches without copies ★★★" ] }, { "cell_type": "markdown", "id": "cnn-opt-strided-explanation", "metadata": {}, "source": [ "The view has six axes. The first four (image, channel, row and column of the patch) move through memory like the corresponding axes of `x`. The last two (row and column inside the patch) move like the rows and columns of the image too, since moving one pixel down inside a patch and moving the patch one pixel down skip the same number of elements. So the strides are `(sB, sC, sH, sW, sH, sW)`, and `as_strided` builds the view without copying." ] }, { "cell_type": "code", "execution_count": null, "id": "cnn-opt-strided-reference", "metadata": {}, "outputs": [], "source": [ "def patches_view(x: Float[torch.Tensor, \"batch channels height width\"], kernel_size: int) -> Float[torch.Tensor, \"batch channels rows cols kernel kernel\"]:\n", " B, C, H, W = x.shape\n", " sB, sC, sH, sW = x.stride()\n", " s = kernel_size\n", " return x.as_strided((B, C, H - s + 1, W - s + 1, s, s), (sB, sC, sH, sW, sH, sW), x.storage_offset())" ] }, { "cell_type": "markdown", "id": "cnn-opt-strided-answer", "metadata": {}, "source": [ "`einsum` reshapes its inputs into a batched matrix product, and a non-contiguous view usually has to be copied into contiguous memory first, so the copy happens anyway, only later. `F.conv2d` calls specialized kernels (oneDNN on CPUs, cuDNN on GPUs) that choose an algorithm for the given shapes and never materialize the patches. The ranking between the first two depends on the hardware; there is no general rule." ] }, { "cell_type": "markdown", "id": "heading-38", "metadata": {}, "source": [ "## Optional F: measuring receptive fields ★★" ] }, { "cell_type": "markdown", "id": "cnn-opt-rf-explanation", "metadata": {}, "source": [ "The gradient of one output unit with respect to the input is nonzero exactly on the pixels that the unit depends on, because all the weights are positive and there is no ReLU or pooling that could zero it. `nonzero` lists the rows and columns of these pixels, and the size of the smallest rectangle around them is the difference between the largest and the smallest index, plus one." ] }, { "cell_type": "code", "execution_count": null, "id": "cnn-opt-rf-reference", "metadata": {}, "outputs": [], "source": [ "def receptive_field(network, size: int = 64) -> tuple[int, int]:\n", " x = torch.randn(1, 1, size, size, requires_grad=True)\n", " out = network(x)\n", " h, w = out.shape[-2:]\n", " out[0, 0, h // 2, w // 2].backward()\n", " rows, cols = (x.grad[0, 0] != 0).nonzero(as_tuple=True)\n", " return rows.max().item() - rows.min().item() + 1, cols.max().item() - cols.min().item() + 1" ] }, { "cell_type": "markdown", "id": "cnn-opt-rf-answer", "metadata": {}, "source": [ "With stride 1, every 3×3 layer adds 2 pixels: $r = 1 + 2L$ after $L$ layers. In general, layer $\\ell$ adds $(s_\\ell - 1)\\, j_{\\ell-1}$, where $j_{\\ell-1}$ is the product of the strides of the previous layers (the distance in input pixels between two neighboring units). After a stride-2 layer, every following 3×3 layer adds 4 pixels instead of 2. For the reference `MyCNN`: conv (3), pool (+1, $j=2$), conv (+4), pool (+2, $j=4$), conv (+8), for a receptive field of 18×18 pixels. Global pooling then covers the whole image." ] }, { "cell_type": "markdown", "id": "heading-42", "metadata": {}, "source": [ "## Optional G: causal convolutions ★★" ] }, { "cell_type": "markdown", "id": "cnn-opt-causal-explanation", "metadata": {}, "source": [ "`F.pad(x, (k - 1, 0))` adds $k - 1$ zeros at the start of the time axis only. `Tensor.unfold(-1, k, 1)` then returns, for every time step $t$, the window of the $k$ inputs ending at $t$, with shape $(B, C, T, k)$. The `einsum` multiplies each window by the filters and sums over the channels and the window, giving $(B, C', T)$." ] }, { "cell_type": "code", "execution_count": null, "id": "cnn-opt-causal-reference", "metadata": {}, "outputs": [], "source": [ "def causal_conv1d(x: Float[torch.Tensor, \"batch channels time\"], weight: Float[torch.Tensor, \"out_channels channels kernel\"], bias: Float[torch.Tensor, \"out_channels\"]) -> Float[torch.Tensor, \"batch out_channels time\"]:\n", " k = weight.shape[-1]\n", " windows = F.pad(x, (k - 1, 0)).unfold(-1, k, 1) # (B, C, T, k)\n", " return torch.einsum(\"bctk,ock->bot\", windows, weight) + bias[:, None]" ] }, { "cell_type": "markdown", "id": "cnn-opt-causal-answer", "metadata": {}, "source": [ "The model could copy the next token from its input instead of predicting it, so the training loss would go to almost zero, but the model would be useless at generation time, when the future is not available. A stack of $L$ causal layers with kernel $k$ sees $L(k - 1) + 1$ steps; *dilated* convolutions (skipping inputs, with dilation doubling at every layer, as in WaveNet) make it grow exponentially with depth." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.15" } }, "nbformat": 4, "nbformat_minor": 5 }