Chapter 18: CNNs, RNNs and Transformers
Attention Is All You Need.
Title of the paper by Vaswani et al. that introduced the Transformer, 2017
18.1 Structure in Data¶
The multilayer perceptron of Chapter 15 treats its input as a list of unrelated numbers. That works for tabular data, but much of the world’s data has structure:
| Data | Structure | Architecture |
|---|---|---|
| Images, video frames, spectrograms | a grid: nearby pixels belong together; a cat is a cat anywhere in the picture | Convolutional network (CNN) |
| Text, speech, sensor readings, prices | a sequence: order matters, and lengths vary | Recurrent network (RNN, LSTM, GRU) |
| Long texts, and today almost everything | a sequence where any element may depend on any other, however far | Transformer (attention) |
| Molecules, road and social networks | a graph of linked items | graph neural network (beyond this course) |
Ignoring the structure has two costs:
Too many parameters. A 224×224 colour image has inputs; a first hidden layer of 1000 neurons already needs 150 million weights.
Nothing carries over between positions. In the Chapter 15 assignment, an MLP that read centred digits with 97.8% accuracy fell to 28.9% when the digits moved one pixel: the weights that learnt a stroke in one place know nothing about the next column.
A good architecture builds the structure in. This built-in assumption is called an inductive bias: it is why a CNN needs far less data than an MLP to learn to see.
18.2 Convolution¶
A convolutional layer slides a small grid of weights, the filter (or kernel), over the image. At each position it multiplies the filter by the patch under it, element by element, and adds everything up:
(Mathematicians would call this a cross-correlation; deep learning calls it convolution.) The result is a new grid, a feature map, that is large wherever the patch looks like the filter.
Worked example: finding a vertical edge¶
A 5×5 image, bright (10) on the left and dark (0) on the right, and a 3×3 vertical-edge filter:
Top-left position (rows 1–3, columns 1–3): the left column gives , the middle column is multiplied by 0, the right column gives . So .
One step right (columns 2–4): .
Columns 3–5: all zeros, so .
The feature map lights up exactly where the edge is. A 5×5 image and a 3×3 filter give a 3×3 map: the filter fits in positions each way.
Two ideas that make CNNs work¶
Local connectivity: each output looks only at a small patch, because nearby pixels are what matter for edges, corners and textures.
Weight sharing: the same filter is used at every position. An edge detector learnt in one corner works everywhere, and the layer has only weights (plus a bias) however large the image is.
Together they give translation equivariance: move the input, and the feature map moves with it.
Source
import numpy as np
import matplotlib.pyplot as plt
img = np.zeros((24, 40))
img[6:19, 3:16] = 1 # a square
yy, xx = np.mgrid[:24, :40]
img[(yy - 12) ** 2 + (xx - 28) ** 2 <= 49] = 1 # a disk
filters = {'vertical edges': np.array([[1, 0, -1]] * 3, float),
'horizontal edges': np.array([[1, 1, 1], [0, 0, 0], [-1, -1, -1]], float)}
def conv2d(X, K):
f = K.shape[0]
return np.array([[np.sum(X[i:i + f, j:j + f] * K) for j in range(X.shape[1] - f + 1)] for i in range(X.shape[0] - f + 1)])
fig, axes = plt.subplots(1, 3, figsize=(12, 2.9))
axes[0].imshow(img, cmap='gray_r'); axes[0].set_title('image (24×40)')
for ax, (name, K) in zip(axes[1:], filters.items()):
ax.imshow(conv2d(img, K), cmap='RdBu', vmin=-3, vmax=3); ax.set_title(f'{name} (22×38 map)')
for ax in axes: ax.axis('off')
plt.suptitle('One image through two 3×3 filters: white is 0; red and blue mark the two sides of each edge', y=1.02); plt.tight_layout(); plt.show()
Channels¶
A colour image has 3 channels (red, green, blue). A filter then spans all of them: a 3×3 filter on an RGB image has weights. A layer uses many filters, each producing its own feature map; the maps are stacked as the channels of the output, and the next layer’s filters span all of them.
Example. 16 filters of size 3×3 on an RGB image: parameters, compared with millions for a dense layer on the same image.
18.3 Padding and Stride¶
Padding adds a border of zeros around the input, so that the filter can also be centred on edge pixels and the map does not shrink at every layer:
valid convolution: no padding (); the map shrinks by ;
same convolution: (for example for a 3×3 filter); the map keeps its size.
Stride is the step of the filter: skips every other position and halves the map.
| Input | Filter | Padding | Stride | Output |
|---|---|---|---|---|
| 5 | 3 | 0 | 1 | |
| 32 | 5 | 0 | 1 | 28 |
| 32 | 3 | 1 | 1 | 32 (same) |
| 32 | 3 | 1 | 2 | |
| 224 | 7 | 3 | 2 | 112 (the first layer of ResNet) |
18.4 Pooling¶
A pooling layer shrinks each feature map by summarising small windows, usually 2×2 with stride 2:
max pooling keeps the largest value (“is the feature present somewhere here?”);
average pooling keeps the mean.
Pooling has no parameters. It reduces computation, and makes the network less sensitive to small shifts: a feature that moves by one pixel usually stays in the same window. Global average pooling averages each whole map into one number, and is how modern CNNs end before the final classifier.
18.5 A Complete CNN¶
A classic CNN repeats a block, then classifies:
As we go deeper, the maps get smaller and more numerous (for example 32×32×3 → 16×16×32 → 8×8×64), and each value sees a larger part of the image. This region is its receptive field: two stacked 3×3 convolutions see a 5×5 patch, three see 7×7. Early layers learn edges and colours; middle layers, textures and parts; late layers, whole objects.
In PyTorch, a small CNN for the 8×8 digits:
model = nn.Sequential(
nn.Conv2d(1, 16, kernel_size=3, padding=1), nn.ReLU(), # 1×8×8 -> 16×8×8
nn.MaxPool2d(2), # -> 16×4×4
nn.Conv2d(16, 32, kernel_size=3, padding=1), nn.ReLU(), # -> 32×4×4
nn.MaxPool2d(2), # -> 32×2×2
nn.Flatten(), # -> 128
nn.Linear(128, 10))The two convolutional layers have and parameters.
18.6 Landmark Architectures¶
| Network | Year | Depth | Parameters | What it introduced |
|---|---|---|---|---|
| LeNet-5 (LeCun) | 1998 | 7 layers | about 60 thousand | the conv–pool–dense pattern; read bank cheques |
| AlexNet (Krizhevsky, Sutskever, Hinton) | 2012 | 8 layers | about 60 million | ReLU, dropout, training on GPUs; won ImageNet with 15.3% top-5 error against 26.2% for the runner-up |
| VGG-16 | 2014 | 16 layers | about 138 million | only 3×3 filters, stacked deep |
| ResNet (He et al.) | 2015 | up to 152 layers | 25 million (ResNet-50) | residual connections; 3.57% top-5 error on ImageNet |
AlexNet’s victory in 2012 is often taken as the start of the deep learning era.
Residual connections¶
Simply stacking more layers eventually makes training worse, not better: the gradient fades on its way down. ResNet adds a shortcut around every pair of layers:
The layers only have to learn the change to their input, and doing nothing () is easy. The shortcut is also a highway for the gradient: never vanishes. Residual connections are now everywhere, including in every Transformer.
18.7 Transfer Learning¶
Training a large CNN needs millions of labelled images. Most projects have a few hundred. Transfer learning reuses a network already trained on a large dataset, such as ImageNet (1.2 million images in 1000 classes):
Take the pretrained network and remove its last layer (the 1000-class classifier).
Add a new last layer for your classes.
Either freeze the pretrained layers and train only the new one (little data), or fine-tune everything with a small learning rate (more data).
It works because the early layers learn general features (edges, textures, shapes) that are useful for almost any images.
from torchvision import models
model = models.resnet18(weights='IMAGENET1K_V1') # downloaded once
for p in model.parameters():
p.requires_grad = False # freeze the features
model.fc = nn.Linear(model.fc.in_features, 5) # a new head for 5 classes
optimizer = torch.optim.Adam(model.fc.parameters(), lr=1e-3)| Your data | Similar to the pretraining data | Different |
|---|---|---|
| Small | freeze; train the new head | freeze the early layers; train the later ones |
| Large | fine-tune everything | fine-tune everything, or train from scratch |
The implementation notebook tries it on 40 people’s faces, with one photo of each to learn from: features from an ImageNet ResNet-18 recognise 69% of the other photos, against 35% for a CNN trained from scratch on the same photos.
18.8 Recurrent Neural Networks¶
A sentence, a sound or a series of prices is a sequence whose length varies and whose order matters. A recurrent neural network reads it one step at a time and keeps a hidden state , its memory of what it has read so far:
The same weights are used at every step: weight sharing again, this time in time. Drawn unrolled, an RNN is a deep network with one layer per time step:
| Shape | Example |
|---|---|
| many-to-one | sentiment of a review; is this heartbeat abnormal? |
| many-to-many (same length) | a part-of-speech tag for every word |
| one-to-many | a caption for an image |
| sequence-to-sequence | translation (an encoder reads, a decoder writes) |
Worked example: memory fades¶
Take a scalar RNN with , , no bias, and the input :
| 1 | 1 | |
| 2 | 0 | |
| 3 | 0 | |
| 4 | 0 |
The trace of the first input roughly halves at each step. After 20 steps it is about a millionth.
Backpropagation through time¶
Training unrolls the network and applies ordinary backpropagation (BPTT). The gradient from step back to step 1 is a product of factors, each involving and a slope. If those factors are below 1 the gradient vanishes (the network cannot learn long-range dependencies); above 1 it explodes (the fix is gradient clipping: rescale the gradient when its norm is too large).
18.9 LSTM and GRU¶
The Long Short-Term Memory (Hochreiter & Schmidhuber, 1997) adds a second memory, the cell state , which runs along the sequence like a conveyor belt and is changed only through gates: sigmoid layers whose outputs, between 0 and 1, decide how much passes.
Why it works. The cell state is updated by addition, not by squeezing through a weight matrix and a . When the forget gate is close to 1, and the gradient flows back almost unchanged: the network can remember for hundreds of steps, and it learns when to.
The Gated Recurrent Unit (Cho et al., 2014) merges the gates into two and drops the separate cell state:
| Simple RNN | GRU | LSTM | |
|---|---|---|---|
| weight blocks | 1 | 3 | 4 |
| long-range memory | poor | good | good |
| typical use | teaching, very short sequences | a lighter LSTM | the long-standing default before Transformers |
A bidirectional RNN runs one RNN forwards and another backwards and joins their states, so each position sees both its past and its future (useful for tagging words, not for predicting the next one).
18.10 Attention¶
An early sequence-to-sequence translator read the whole source sentence into one final hidden state, then generated the translation from it. Long sentences do not fit in one vector, and quality fell with length. Attention (Bahdanau, Cho and Bengio, 2014) lets the decoder look back at every encoder state and decide, at each word it writes, which ones matter.
Queries, keys and values¶
Attention is a soft dictionary lookup. Each item to look at has a key (what it is about) and a value (what it contains). A query (what we are looking for) is compared with every key; the better the match, the more of that item’s value we take:
The scores are dot products (similarities); dividing by , the square root of the key length, stops them from growing with the dimension and saturating the softmax; the softmax turns each row of scores into weights that sum to 1.
Worked example¶
One query and three items, with :
| item | key | value | score | weight (softmax) |
|---|---|---|---|---|
| 1 | 0.707 | 0.401 | ||
| 2 | 0 | 0.198 | ||
| 3 | 0.707 | 0.401 |
The query matches items 1 and 3 equally well, and item 2 less: the output is mostly their values. Every step is differentiable, so the network learns what to look for.
Source
q = np.array([1.0, 0.0]); K = np.array([[1.0, 0.0], [0.0, 1.0], [1.0, 1.0]]); V = np.array([[1.0, 0.0], [0.0, 1.0], [0.5, 0.5]])
scores = K @ q / np.sqrt(2)
weights = np.exp(scores) / np.exp(scores).sum()
print('scores :', scores.round(3))
print('weights:', weights.round(3))
print('output :', (weights @ V).round(3))scores : [0.707 0. 0.707]
weights: [0.401 0.198 0.401]
output : [0.602 0.398]
18.11 Transformers¶
The Transformer (Vaswani et al., 2017) drops recurrence altogether: it is built from attention.
Self-attention¶
In self-attention the queries, keys and values all come from the same sequence. Each token’s vector is projected three ways, , , , and every token attends to every other. In “The animal didn’t cross the street because it was too tired”, the representation of it can draw directly on animal, however many words lie between.
Compared with an RNN:
any distance in one step: no information has to survive a long chain of updates;
parallel: all positions are computed at once, which suits GPUs and made very large models possible;
but the cost grows with the square of the sequence length ( scores).
Multi-head attention¶
One attention looks for one kind of relation. Multi-head attention runs attentions in parallel, each with its own (one head may track grammar, another meaning, another position), concatenates their outputs and mixes them with a matrix .
Positional encoding¶
Attention ignores order: shuffle the words and each one receives the same weighted sum. The order is put back by adding a positional encoding to each token’s vector. The original Transformer uses waves of different frequencies:
Many recent models learn the encodings instead, or encode relative positions.
Source
d, n = 64, 100
pos = np.arange(n)[:, None]; i = np.arange(d // 2)[None, :]
angles = pos / 10000 ** (2 * i / d)
PE = np.hstack([np.sin(angles), np.cos(angles)]) # shown as all sines, then all cosines
plt.figure(figsize=(9, 3.2)); plt.imshow(PE.T, aspect='auto', cmap='RdBu', vmin=-1, vmax=1); plt.colorbar()
plt.axhline(d // 2 - 0.5, color='k', lw=0.8)
plt.xlabel('position in the sequence'); plt.ylabel('sines (top), cosines (bottom)')
plt.title('Positional encoding: fast waves in the first dimensions, slow ones in the last; each column is unique')
plt.tight_layout(); plt.show()
The Transformer block¶
Each block has a residual connection around its attention and around its feed-forward network (Section 18.6), followed by layer normalisation. A model stacks many blocks: 12 in BERT-base, 96 in GPT-3.
| Family | Attention | Trained to | Good at |
|---|---|---|---|
| Encoder (BERT, 2018) | every token sees every token | fill in hidden words | understanding: classification, search, tagging |
| Decoder (GPT, 2018–) | a causal mask: each token sees only the ones before it | predict the next token | generating text: the large language models of Chapter 21 |
| Encoder–decoder (original Transformer, T5) | encoder reads; decoder attends to it | map a sequence to another | translation, summarisation |
Transformers now go well beyond text: the Vision Transformer cuts an image into 16×16 patches and treats them as tokens; similar models handle speech, music, code and protein structures.
18.12 Choosing an Architecture¶
| Your data | First choice | Notes |
|---|---|---|
| Tabular features | gradient boosting or an MLP (Ch. 8, 15) | deep architectures rarely help |
| Images | a pretrained CNN (ResNet, EfficientNet), fine-tuned | or a Vision Transformer with enough data |
| Short sequences, sensors, small data | a 1-D CNN, GRU or LSTM | cheap and effective |
| Text | a pretrained Transformer | fine-tune, or use a large language model (Ch. 21) |
| Long time series | LSTM, temporal CNN or Transformer | always compare with a simple baseline |
The rule from Chapter 8 still holds: start with a baseline, and reuse a pretrained model whenever one exists.
18.13 Summary¶
Structured data deserves a structured network: the inductive bias saves parameters and data.
A convolution slides a shared filter over the image; output size ; parameters .
Pooling shrinks maps and adds tolerance to small shifts; residual connections let networks go hundreds of layers deep.
Transfer learning reuses pretrained features when data is scarce.
An RNN carries a hidden state through time, but its memory fades; LSTM and GRU gates keep it with additive updates.
Attention lets every position look directly at every other; Transformers stack self-attention and feed-forward blocks, with positional encodings for order.
Exercises¶
Compute the output of the 3×3 filter on the 5×5 image of Section 18.2. What does the result tell you?
An input of 64×64×3 goes through a 5×5 convolution with 32 filters, padding 2 and stride 1, then 2×2 max pooling. Give the output shape and the number of parameters.
Why does a CNN need far fewer parameters than an MLP on the same image? Name the two ideas.
Continue the memory-fading table of Section 18.8 with . What changes, and why could that be a problem in the other direction?
In the attention example, change the query to . Compute the weights and the output.
Why does a Transformer need positional encodings, when an RNN does not?
You have 300 labelled X-ray images in 3 classes. Describe a sensible approach, and the first baseline you would compare with.
Further Reading¶
I. Goodfellow, Y. Bengio, A. Courville, Deep Learning, MIT Press, 2016, Chapters 9 (CNNs) and 10 (RNNs).
A. Zhang, Z. Lipton, M. Li, A. Smola, Dive into Deep Learning (free online, with PyTorch code): Chapters 7–11.
C. Olah, “Understanding LSTM Networks”, blog post, 2015.
J. Alammar, “The Illustrated Transformer”, blog post, 2018.
A. Vaswani et al., “Attention Is All You Need”, NeurIPS 2017.
C. C. Aggarwal, Artificial Intelligence: A Textbook, Springer, 2021, Chapter 8.