Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Chapter 18: CNNs, RNNs and Transformers — Implementation

Open in Colab

This notebook builds the key operation of each architecture from scratch, checks it against PyTorch, and then runs small experiments that show why each architecture exists:

  1. Convolution and pooling from scratch

  2. A CNN against an MLP on digits: parameters, accuracy, shifted digits

  3. What the first CNN layer sees

  4. Transfer learning with a network pretrained on ImageNet

  5. Recurrent networks: how memory fades, and how the LSTM’s gate keeps it

  6. Attention from scratch, and a model that learns where to look

1. Convolution and Pooling from Scratch

A direct translation of the formula S(i,j)=∑m,nX(i+m,j+n)K(m,n)S(i,j) = \sum_{m,n} X(i+m, j+n)K(m,n), with padding and stride:

vertical-edge filter on the 5x5 image:
 [[30. 30.  0.]
 [30. 30.  0.]
 [30. 30.  0.]]
max pooling:
 [[6. 5.]
 [3. 7.]]
matches F.conv2d (padding 1, stride 2): True | output shape (5, 5)

The loops are slow, but they are exactly what nn.Conv2d computes, many times faster and for many channels at once.

2. A CNN Against an MLP

We train both on the 8×8 digits with the same budget. Pixel values are divided by 16, so they lie between 0 and 1.

MLP:  9610 parameters   test accuracy 0.967
CNN:  6090 parameters   test accuracy 0.976

The CNN is more accurate with fewer parameters. Now the test from the Chapter 15 assignment: move every test digit by one pixel, in each of the 8 directions.

MLP: centred 0.967   shifted by one pixel 0.328
CNN: centred 0.976   shifted by one pixel 0.453

The CNN tolerates shifts much better, but far from perfectly. Convolution is equivariant (a shifted input gives a shifted feature map), and pooling absorbs part of the shift; the final dense layer, however, still reads fixed positions, and on an 8×8 image one pixel is an eighth of the width. On real photos, CNNs are combined with data augmentation (shifted, cropped, flipped copies), exactly as in the Chapter 15 assignment.

3. What the First Layer Sees

Each of the 16 filters of the first layer produces a feature map. For one digit:

<Figure size 1200x300 with 18 Axes>

4. Transfer Learning with ImageNet Features

The task. Recognise 40 people from the Olivetti faces (10 photos each, 64×64 grey), when we have only one or five photos of each person to learn from.

Transfer learning. A ResNet-18 trained on ImageNet (1.2 million photos of objects, no faces among its classes) is used as a fixed feature extractor: we remove its last layer, and each face becomes 512 numbers. A simple logistic regression is then trained on those features. We compare it with a CNN trained from scratch on the same few photos.

features: (400, 512)
1 photo(s) per person: pretrained features 0.686   CNN from scratch 0.353   logistic regression on raw pixels 0.639
5 photo(s) per person: pretrained features 0.880   CNN from scratch 0.510   logistic regression on raw pixels 0.900

Reading the results.

  • With the same handful of photos, pretrained features beat a CNN trained from scratch by a wide margin. The scratch CNN has to learn what an edge, an eye or a nose is from 40 or 200 photos; the ResNet learnt general visual features from 1.2 million images, and they transfer to faces even though it never saw a face class.

  • A baseline on raw pixels does about as well here. Olivetti photos are carefully aligned: same framing, plain background, similar light, so even pixel-by-pixel comparison works. Real photos vary in pose, light and background, and raw pixels lose that advantage. This is the Chapter 8 lesson again: always compare with a simple baseline.

  • With more images per class, fine-tuning (unfreezing the later ResNet layers with a small learning rate) usually improves further.

5. Recurrent Networks: Memory and Gates

A simple RNN from scratch

h_t: [0.762 0.363 0.18  0.09 ]
matches nn.RNN: True

How far back can a network see?

The gradient ∣∂hT/∂x1∣\left|\partial h_T / \partial x_1\right| measures how much the first input still affects the last state, and therefore how much a training signal at the end can teach the network about the beginning. We measure it for freshly initialised networks with 32 hidden units, averaged over 5 initialisations:

  • a simple RNN;

  • an LSTM with PyTorch’s default initialisation (forget gate about 0.5);

  • an LSTM whose forget-gate bias is set to 3, so the gate starts at σ(3)≈0.95\sigma(3) \approx 0.95: the conveyor belt is open.

<Figure size 640x480 with 1 Axes>
simple RNN                T=10: 2.7e-03   T=80: 2.9e-17
LSTM, default init        T=10: 1.3e-03   T=80: 1.5e-16
LSTM, forget gate open    T=10: 1.1e-01   T=80: 7.8e-02

The simple RNN’s influence falls by a constant factor at every step: after 80 steps it is around 10-17, so nothing at the end can teach it about the start. The LSTM is no better as initialised; but when its forget gate is open, the cell state carries the information along and the influence stays around 10-1 even after 80 steps. The gate is a learnable weight: training can open it exactly where a long memory is needed. This is why LSTMs (and GRUs) replaced simple RNNs, and why a forget-gate bias of 1 or more is a common initialisation.

6. Attention

From scratch, checked against PyTorch

chapter example: weights [0.401 0.198 0.401]  output [0.602 0.398]
causal=False: matches PyTorch: True
causal=True: matches PyTorch: True
causal weights (row i may only look at columns j <= i):
 [[1.    0.    0.    0.   ]
 [0.678 0.322 0.    0.   ]
 [0.459 0.226 0.315 0.   ]
 [0.471 0.081 0.239 0.209]]

A model that learns where to look

The task. A sequence of 50 random numbers; the label is the sign of the first one (set to ±2\pm 2), and the other 49 are noise. A model must find position 1 and ignore the rest.

The model. Each number is embedded into 32 dimensions and gets a positional encoding (Section 18.11). One learned query vector asks “where is the information?”; attention over the 50 positions produces one summary vector, which a linear layer classifies.

epoch 1: test accuracy 0.522
epoch 2: test accuracy 0.806
epoch 3: test accuracy 0.996
epoch 4: test accuracy 1.000
epoch 5: test accuracy 1.000
epoch 6: test accuracy 1.000
epoch 7: test accuracy 1.000
epoch 8: test accuracy 1.000
<Figure size 900x280 with 1 Axes>

Nobody told the model which position matters: attention, trained only from the labels, learnt to look at position 1, wherever the sequence ends. The step from this model to a Transformer is to let every position ask its own query (self-attention), to run several heads in parallel, and to stack blocks with residual connections and feed-forward layers. PyTorch provides them ready-made as nn.TransformerEncoderLayer and nn.MultiheadAttention.

Summary

SectionWhat we saw
1conv2d and max_pool from scratch match PyTorch
2the CNN beats the MLP with fewer parameters, and tolerates shifts better (but augmentation is still needed)
3first-layer filters respond to stroke directions
4pretrained ImageNet features recognise faces from one photo per person far better than a CNN from scratch; a baseline still matters
5a simple RNN’s memory vanishes exponentially; an LSTM with an open forget gate keeps it
6attention from scratch matches PyTorch; a trained attention model learns where to look