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

Open in Colab

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:

DataStructureArchitecture
Images, video frames, spectrogramsa grid: nearby pixels belong together; a cat is a cat anywhere in the pictureConvolutional network (CNN)
Text, speech, sensor readings, pricesa sequence: order matters, and lengths varyRecurrent network (RNN, LSTM, GRU)
Long texts, and today almost everythinga sequence where any element may depend on any other, however farTransformer (attention)
Molecules, road and social networksa graph of linked itemsgraph neural network (beyond this course)

Ignoring the structure has two costs:

  1. Too many parameters. A 224×224 colour image has 224×224×3=150 528224 \times 224 \times 3 = 150\,528 inputs; a first hidden layer of 1000 neurons already needs 150 million weights.

  2. 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:

S(i,j)=∑m∑nX(i+m, j+n) K(m,n)+bS(i, j) = \sum_{m}\sum_{n} X(i + m,\ j + n)\, K(m, n) + b

(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:

X=(10100001010000101000010100001010000),K=(10−110−110−1)X = \begin{pmatrix} 10 & 10 & 0 & 0 & 0 \\ 10 & 10 & 0 & 0 & 0 \\ 10 & 10 & 0 & 0 & 0 \\ 10 & 10 & 0 & 0 & 0 \\ 10 & 10 & 0 & 0 & 0 \end{pmatrix}, \qquad K = \begin{pmatrix} 1 & 0 & -1 \\ 1 & 0 & -1 \\ 1 & 0 & -1 \end{pmatrix}
  • Top-left position (rows 1–3, columns 1–3): the left column gives 3×10×1=303 \times 10 \times 1 = 30, the middle column is multiplied by 0, the right column gives 3×0×(−1)=03 \times 0 \times (-1) = 0. So S(1,1)=30S(1,1) = 30.

  • One step right (columns 2–4): 3×10−3×0=303 \times 10 - 3 \times 0 = 30.

  • Columns 3–5: all zeros, so S=0S = 0.

S=(303003030030300)S = \begin{pmatrix} 30 & 30 & 0 \\ 30 & 30 & 0 \\ 30 & 30 & 0 \end{pmatrix}

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 5−3+1=35 - 3 + 1 = 3 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 3×3=93 \times 3 = 9 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
<Figure size 1200x290 with 3 Axes>

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 3×3×3=273 \times 3 \times 3 = 27 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.

parameters of a conv layer=(f×f×Cin+1)×Cout\text{parameters of a conv layer} = (f \times f \times C_{in} + 1) \times C_{out}

Example. 16 filters of size 3×3 on an RGB image: (3⋅3⋅3+1)×16=448(3 \cdot 3 \cdot 3 + 1) \times 16 = 448 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 (p=0p = 0); the map shrinks by f−1f - 1;

  • same convolution: p=(f−1)/2p = (f - 1)/2 (for example p=1p = 1 for a 3×3 filter); the map keeps its size.

Stride ss is the step of the filter: s=2s = 2 skips every other position and halves the map.

Input nnFilter ffPadding ppStride ssOutput
5301(5−3)/1+1=3(5 - 3)/1 + 1 = 3
3250128
3231132 (same)
32312⌊31/2⌋+1=16\lfloor 31/2 \rfloor + 1 = 16
224732112 (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.

(1321465031120274)→max pool 2×2(6537)\begin{pmatrix} 1 & 3 & 2 & 1 \\ 4 & 6 & 5 & 0 \\ 3 & 1 & 1 & 2 \\ 0 & 2 & 7 & 4 \end{pmatrix} \xrightarrow{\text{max pool } 2\times 2} \begin{pmatrix} 6 & 5 \\ 3 & 7 \end{pmatrix}

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 (9⋅1+1)⋅16=160(9 \cdot 1 + 1) \cdot 16 = 160 and (9⋅16+1)⋅32=4640(9 \cdot 16 + 1) \cdot 32 = 4640 parameters.

18.6 Landmark Architectures

NetworkYearDepthParametersWhat it introduced
LeNet-5 (LeCun)19987 layersabout 60 thousandthe conv–pool–dense pattern; read bank cheques
AlexNet (Krizhevsky, Sutskever, Hinton)20128 layersabout 60 millionReLU, dropout, training on GPUs; won ImageNet with 15.3% top-5 error against 26.2% for the runner-up
VGG-16201416 layersabout 138 milliononly 3×3 filters, stacked deep
ResNet (He et al.)2015up to 152 layers25 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:

y=F(x)+x\mathbf{y} = F(\mathbf{x}) + \mathbf{x}

The layers only have to learn the change F(x)F(\mathbf{x}) to their input, and doing nothing (F=0F = 0) is easy. The shortcut is also a highway for the gradient: ∂y/∂x=∂F/∂x+I\partial \mathbf{y} / \partial \mathbf{x} = \partial F / \partial \mathbf{x} + I 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):

  1. Take the pretrained network and remove its last layer (the 1000-class classifier).

  2. Add a new last layer for your classes.

  3. 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 dataSimilar to the pretraining dataDifferent
Smallfreeze; train the new headfreeze the early layers; train the later ones
Largefine-tune everythingfine-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 x1,x2,…,xT\mathbf{x}_1, \mathbf{x}_2, \dots, \mathbf{x}_T whose length varies and whose order matters. A recurrent neural network reads it one step at a time and keeps a hidden state ht\mathbf{h}_t, its memory of what it has read so far:

ht=tanh⁡(Whhht−1+Wxhxt+bh),y^t=Whyht+by\mathbf{h}_t = \tanh\big(W_{hh}\mathbf{h}_{t-1} + W_{xh}\mathbf{x}_t + \mathbf{b}_h\big), \qquad \hat{\mathbf{y}}_t = W_{hy}\mathbf{h}_t + \mathbf{b}_y

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:

ShapeExample
many-to-onesentiment of a review; is this heartbeat abnormal?
many-to-many (same length)a part-of-speech tag for every word
one-to-manya caption for an image
sequence-to-sequencetranslation (an encoder reads, a decoder writes)

Worked example: memory fades

Take a scalar RNN with whh=0.5w_{hh} = 0.5, wxh=1w_{xh} = 1, no bias, and the input 1,0,0,01, 0, 0, 0:

ttxtx_tht=tanh⁡(0.5 ht−1+xt)h_t = \tanh(0.5\,h_{t-1} + x_t)
11tanh⁡(1)=0.762\tanh(1) = 0.762
20tanh⁡(0.381)=0.363\tanh(0.381) = 0.363
30tanh⁡(0.182)=0.180\tanh(0.182) = 0.180
40tanh⁡(0.090)=0.090\tanh(0.090) = 0.090

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 TT back to step 1 is a product of TT factors, each involving WhhW_{hh} and a tanh⁡′\tanh' 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 ct\mathbf{c}_t, 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.

ft=σ(Wf[ht−1,xt]+bf)forget gate: how much old memory to keepit=σ(Wi[ht−1,xt]+bi)input gate: how much new information to writec~t=tanh⁡(Wc[ht−1,xt]+bc)the candidate new informationct=ft⊙ct−1+it⊙c~tupdate the memoryot=σ(Wo[ht−1,xt]+bo)output gateht=ot⊙tanh⁡(ct)what the cell shows\begin{aligned} \mathbf{f}_t &= \sigma(W_f[\mathbf{h}_{t-1}, \mathbf{x}_t] + \mathbf{b}_f) && \text{forget gate: how much old memory to keep} \\ \mathbf{i}_t &= \sigma(W_i[\mathbf{h}_{t-1}, \mathbf{x}_t] + \mathbf{b}_i) && \text{input gate: how much new information to write} \\ \tilde{\mathbf{c}}_t &= \tanh(W_c[\mathbf{h}_{t-1}, \mathbf{x}_t] + \mathbf{b}_c) && \text{the candidate new information} \\ \mathbf{c}_t &= \mathbf{f}_t \odot \mathbf{c}_{t-1} + \mathbf{i}_t \odot \tilde{\mathbf{c}}_t && \text{update the memory} \\ \mathbf{o}_t &= \sigma(W_o[\mathbf{h}_{t-1}, \mathbf{x}_t] + \mathbf{b}_o) && \text{output gate} \\ \mathbf{h}_t &= \mathbf{o}_t \odot \tanh(\mathbf{c}_t) && \text{what the cell shows} \end{aligned}

Why it works. The cell state is updated by addition, not by squeezing through a weight matrix and a tanh⁡\tanh. When the forget gate is close to 1, ct≈ct−1\mathbf{c}_t \approx \mathbf{c}_{t-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:

zt=σ(Wz[ht−1,xt]),rt=σ(Wr[ht−1,xt]),h~t=tanh⁡(W[rt⊙ht−1,xt]),ht=(1−zt)⊙ht−1+zt⊙h~t\mathbf{z}_t = \sigma(W_z[\mathbf{h}_{t-1}, \mathbf{x}_t]), \quad \mathbf{r}_t = \sigma(W_r[\mathbf{h}_{t-1}, \mathbf{x}_t]), \quad \tilde{\mathbf{h}}_t = \tanh(W[\mathbf{r}_t \odot \mathbf{h}_{t-1}, \mathbf{x}_t]), \quad \mathbf{h}_t = (1 - \mathbf{z}_t) \odot \mathbf{h}_{t-1} + \mathbf{z}_t \odot \tilde{\mathbf{h}}_t
Simple RNNGRULSTM
weight blocks134
long-range memorypoorgoodgood
typical useteaching, very short sequencesa lighter LSTMthe 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:

Attention(Q,K,V)=softmax ⁣(QK⊤dk)V\text{Attention}(Q, K, V) = \text{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right) V

The scores QK⊤QK^\top are dot products (similarities); dividing by dk\sqrt{d_k}, 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 q=(1,0)\mathbf{q} = (1, 0) and three items, with dk=2d_k = 2:

itemkey k\mathbf{k}value v\mathbf{v}score q⋅k/2\mathbf{q}\cdot\mathbf{k}/\sqrt{2}weight (softmax)
1(1,0)(1, 0)(1,0)(1, 0)0.7070.401
2(0,1)(0, 1)(0,1)(0, 1)00.198
3(1,1)(1, 1)(0.5,0.5)(0.5, 0.5)0.7070.401
output=0.401 (1,0)+0.198 (0,1)+0.401 (0.5,0.5)=(0.602, 0.398)\text{output} = 0.401\,(1, 0) + 0.198\,(0, 1) + 0.401\,(0.5, 0.5) = (0.602,\ 0.398)

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
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 xi\mathbf{x}_i is projected three ways, Q=XWQQ = XW_Q, K=XWKK = XW_K, V=XWVV = XW_V, 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 (n2n^2 scores).

Multi-head attention

One attention looks for one kind of relation. Multi-head attention runs hh attentions in parallel, each with its own WQ,WK,WVW_Q, W_K, W_V (one head may track grammar, another meaning, another position), concatenates their outputs and mixes them with a matrix WOW_O.

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:

PE(pos,2i)=sin⁡ ⁣(pos100002i/d),PE(pos,2i+1)=cos⁡ ⁣(pos100002i/d)PE(pos, 2i) = \sin\!\left(\frac{pos}{10000^{2i/d}}\right), \qquad PE(pos, 2i + 1) = \cos\!\left(\frac{pos}{10000^{2i/d}}\right)

Many recent models learn the encodings instead, or encode relative positions.

Source
<Figure size 900x320 with 2 Axes>

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.

FamilyAttentionTrained toGood at
Encoder (BERT, 2018)every token sees every tokenfill in hidden wordsunderstanding: classification, search, tagging
Decoder (GPT, 2018–)a causal mask: each token sees only the ones before itpredict the next tokengenerating text: the large language models of Chapter 21
Encoder–decoder (original Transformer, T5)encoder reads; decoder attends to itmap a sequence to anothertranslation, 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 dataFirst choiceNotes
Tabular featuresgradient boosting or an MLP (Ch. 8, 15)deep architectures rarely help
Imagesa pretrained CNN (ResNet, EfficientNet), fine-tunedor a Vision Transformer with enough data
Short sequences, sensors, small dataa 1-D CNN, GRU or LSTMcheap and effective
Texta pretrained Transformerfine-tune, or use a large language model (Ch. 21)
Long time seriesLSTM, temporal CNN or Transformeralways 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 ⌊(n+2p−f)/s⌋+1\lfloor (n + 2p - f)/s \rfloor + 1; parameters (f2Cin+1) Cout(f^2 C_{in} + 1)\,C_{out}.

  • 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 softmax(QK⊤/dk)V\text{softmax}(QK^\top/\sqrt{d_k})V lets every position look directly at every other; Transformers stack self-attention and feed-forward blocks, with positional encodings for order.

Exercises

  1. Compute the output of the 3×3 filter (111000−1−1−1)\begin{pmatrix} 1 & 1 & 1 \\ 0 & 0 & 0 \\ -1 & -1 & -1 \end{pmatrix} on the 5×5 image of Section 18.2. What does the result tell you?

  2. 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.

  3. Why does a CNN need far fewer parameters than an MLP on the same image? Name the two ideas.

  4. Continue the memory-fading table of Section 18.8 with whh=0.9w_{hh} = 0.9. What changes, and why could that be a problem in the other direction?

  5. In the attention example, change the query to (0,1)(0, 1). Compute the weights and the output.

  6. Why does a Transformer need positional encodings, when an RNN does not?

  7. 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.