Chapter 18: CNNs, RNNs and Transformers — Implementation
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:
Convolution and pooling from scratch
A CNN against an MLP on digits: parameters, accuracy, shifted digits
What the first CNN layer sees
Transfer learning with a network pretrained on ImageNet
Recurrent networks: how memory fades, and how the LSTM’s gate keeps it
Attention from scratch, and a model that learns where to look
import copy, math
import numpy as np
import matplotlib.pyplot as plt
import torch
from torch import nn
import torch.nn.functional as F
from torch.utils.data import TensorDataset, DataLoader
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
torch.manual_seed(0)
np.set_printoptions(precision=3, suppress=True)1. Convolution and Pooling from Scratch¶
A direct translation of the formula , with padding and stride:
def conv2d(X, K, padding=0, stride=1):
"""One-channel convolution (deep-learning style: no kernel flip)."""
Xp = np.pad(X, padding)
f = K.shape[0]
n_out = (Xp.shape[0] - f) // stride + 1
out = np.zeros((n_out, n_out))
for i in range(n_out):
for j in range(n_out):
r, c = i * stride, j * stride
out[i, j] = np.sum(Xp[r:r + f, c:c + f] * K)
return out
def max_pool(X, size=2):
n, m = X.shape
return X.reshape(n // size, size, m // size, size).max(axis=(1, 3))
# the chapter's worked examples
X = np.array([[10, 10, 0, 0, 0]] * 5, float)
K = np.array([[1, 0, -1]] * 3, float)
print('vertical-edge filter on the 5x5 image:\n', conv2d(X, K))
print('max pooling:\n', max_pool(np.array([[1, 3, 2, 1], [4, 6, 5, 0], [3, 1, 1, 2], [0, 2, 7, 4]], float)))
# and the same result as PyTorch on random data, with padding and stride
R, RK = np.random.default_rng(0).normal(size=(9, 9)), np.random.default_rng(1).normal(size=(3, 3))
ref = F.conv2d(torch.tensor(R)[None, None], torch.tensor(RK)[None, None], padding=1, stride=2)[0, 0].numpy()
print('matches F.conv2d (padding 1, stride 2):', np.allclose(conv2d(R, RK, 1, 2), ref), '| output shape', ref.shape)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.
digits = load_digits()
X_tr, X_te, y_tr, y_te = train_test_split(digits.images / 16.0, digits.target, test_size=0.25, stratify=digits.target, random_state=0)
to_t = lambda A: torch.tensor(A, dtype=torch.float32).unsqueeze(1) # (N, 8, 8) -> (N, 1, 8, 8)
def train(model, X, y, epochs=40, lr=1e-3, params=None):
torch.manual_seed(0)
opt = torch.optim.Adam(params if params is not None else model.parameters(), lr=lr)
loader = DataLoader(TensorDataset(to_t(X), torch.tensor(y)), batch_size=64, shuffle=True)
for _ in range(epochs):
model.train()
for xb, yb in loader:
loss = F.cross_entropy(model(xb), yb)
opt.zero_grad(); loss.backward(); opt.step()
model.eval()
return model
def accuracy(model, X, y):
with torch.no_grad():
return (model(to_t(X)).argmax(1).numpy() == y).mean()
def n_params(model):
return sum(p.numel() for p in model.parameters())
mlp = nn.Sequential(nn.Flatten(), nn.Linear(64, 128), nn.ReLU(), nn.Linear(128, 10))
cnn = nn.Sequential(
nn.Conv2d(1, 16, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2), # 16 x 4 x 4
nn.Conv2d(16, 32, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2), # 32 x 2 x 2
nn.Flatten(), nn.Linear(128, 10))
torch.manual_seed(0); mlp = train(mlp, X_tr, y_tr)
torch.manual_seed(0); cnn = train(cnn, X_tr, y_tr)
for name, m in [('MLP', mlp), ('CNN', cnn)]:
print(f'{name}: {n_params(m):5d} parameters test accuracy {accuracy(m, X_te, y_te):.3f}')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.
def shift_images(X, dx, dy):
out = np.zeros_like(X)
out[:, max(0, dy):8 - max(0, -dy), max(0, dx):8 - max(0, -dx)] = X[:, max(0, -dy):8 - max(0, dy), max(0, -dx):8 - max(0, dx)]
return out
DIRECTIONS = [(dx, dy) for dx in (-1, 0, 1) for dy in (-1, 0, 1) if (dx, dy) != (0, 0)]
for name, m in [('MLP', mlp), ('CNN', cnn)]:
shifted = np.mean([accuracy(m, shift_images(X_te, dx, dy), y_te) for dx, dy in DIRECTIONS])
print(f'{name}: centred {accuracy(m, X_te, y_te):.3f} shifted by one pixel {shifted:.3f}')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:
digit = to_t(X_te[:1])
with torch.no_grad():
maps = F.relu(cnn[0](digit))[0] # the 16 maps after the first conv + ReLU
fig, axes = plt.subplots(2, 9, figsize=(12, 3))
axes[0, 0].imshow(X_te[0], cmap='gray_r'); axes[0, 0].set_title(f'digit {y_te[0]}')
axes[1, 0].axis('off')
for k in range(16):
ax = axes[k // 8, 1 + k % 8]
ax.imshow(maps[k], cmap='viridis'); ax.set_title(f'map {k}', fontsize=8)
for ax in axes.ravel(): ax.set_xticks([]); ax.set_yticks([])
plt.suptitle('First-layer feature maps: each filter responds to a different stroke direction or side'); plt.tight_layout(); plt.show()
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.
import warnings
from torchvision import models
from sklearn.datasets import fetch_olivetti_faces
warnings.filterwarnings('ignore', message='The number of unique classes') # one photo per class is intended here
from sklearn.linear_model import LogisticRegression
faces = fetch_olivetti_faces()
FX, Fy = faces.images, faces.target # 400 photos, 40 people
resnet = models.resnet18(weights=models.ResNet18_Weights.IMAGENET1K_V1)
resnet.fc = nn.Identity() # remove the 1000-class layer
resnet.eval()
mean = torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1) # ImageNet's normalisation
std = torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1)
with torch.no_grad():
x = torch.tensor(FX).unsqueeze(1).repeat(1, 3, 1, 1) # grey -> 3 channels
x = F.interpolate(x, size=112, mode='bilinear') # closer to ImageNet sizes
features = resnet((x - mean) / std).numpy()
print('features:', features.shape)features: (400, 512)
F32 = F.avg_pool2d(torch.tensor(FX).unsqueeze(1), 2) # 32x32, for the small CNN
def face_cnn():
return nn.Sequential(
nn.Conv2d(1, 16, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
nn.Conv2d(16, 32, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
nn.Conv2d(32, 64, 3, padding=1), nn.ReLU(), nn.AdaptiveAvgPool2d(1),
nn.Flatten(), nn.Linear(64, 40))
rows = []
for k in [1, 5]:
train_idx = np.concatenate([np.where(Fy == person)[0][:k] for person in range(40)])
test_idx = np.setdiff1d(np.arange(400), train_idx)
transfer = LogisticRegression(max_iter=2000).fit(features[train_idx], Fy[train_idx]).score(features[test_idx], Fy[test_idx])
torch.manual_seed(0)
model = face_cnn(); opt = torch.optim.Adam(model.parameters(), lr=1e-3)
for _ in range(200):
model.train()
loss = F.cross_entropy(model(F32[train_idx]), torch.tensor(Fy[train_idx]))
opt.zero_grad(); loss.backward(); opt.step()
model.eval()
with torch.no_grad():
scratch = (model(F32[test_idx]).argmax(1).numpy() == Fy[test_idx]).mean()
raw = LogisticRegression(max_iter=2000).fit(F32[train_idx].flatten(1).numpy(), Fy[train_idx]).score(F32[test_idx].flatten(1).numpy(), Fy[test_idx])
rows.append((k, transfer, scratch, raw))
print(f'{k} photo(s) per person: pretrained features {transfer:.3f} CNN from scratch {scratch:.3f} logistic regression on raw pixels {raw:.3f}')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.
def rnn_forward(X, W_xh, W_hh, b):
h = np.zeros(W_hh.shape[0])
states = []
for x in X:
h = np.tanh(W_xh @ x + W_hh @ h + b)
states.append(h)
return np.array(states)
# the chapter's example: memory fades
print('h_t:', rnn_forward(np.array([[1.], [0.], [0.], [0.]]), np.array([[1.]]), np.array([[0.5]]), np.zeros(1)).ravel())
# the same computation as nn.RNN
rnn = nn.RNN(3, 5, batch_first=True)
seq = torch.randn(7, 3)
with torch.no_grad():
ref = rnn(seq[None])[0][0].numpy()
mine = rnn_forward(seq.numpy(), rnn.weight_ih_l0.detach().numpy(), rnn.weight_hh_l0.detach().numpy(),
(rnn.bias_ih_l0 + rnn.bias_hh_l0).detach().numpy())
print('matches nn.RNN:', np.allclose(mine, ref, atol=1e-5))h_t: [0.762 0.363 0.18 0.09 ]
matches nn.RNN: True
How far back can a network see?¶
The gradient 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 : the conveyor belt is open.
def influence(cell, T, forget_bias=None, seeds=5):
values = []
for seed in range(seeds):
torch.manual_seed(seed)
net = cell(1, 32, batch_first=True)
if forget_bias is not None: # PyTorch orders the LSTM gates: input, forget, cell, output
with torch.no_grad():
net.bias_ih_l0[32:64] = forget_bias
net.bias_hh_l0[32:64] = 0.0
x = torch.randn(1, T, 1, requires_grad=True)
last_state = net(x)[0][0, -1].sum()
values.append(torch.autograd.grad(last_state, x)[0][0, 0, 0].abs().item())
return np.mean(values)
lengths = [1, 5, 10, 20, 40, 60, 80]
curves = {'simple RNN': [influence(nn.RNN, T) for T in lengths],
'LSTM, default init': [influence(nn.LSTM, T) for T in lengths],
'LSTM, forget gate open': [influence(nn.LSTM, T, forget_bias=3.0) for T in lengths]}
for name, vals in curves.items():
plt.semilogy(lengths, vals, 'o-', label=name)
plt.xlabel('sequence length T'); plt.ylabel('|d h_T / d x_1| (log scale)'); plt.legend()
plt.title('How much the first input still matters at the end'); plt.show()
for name, vals in curves.items():
print(f'{name:24} T=10: {vals[2]:.1e} T=80: {vals[-1]:.1e}')
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.
def attention(Q, K, V, causal=False):
scores = Q @ K.T / np.sqrt(Q.shape[1])
if causal:
scores = np.where(np.triu(np.ones_like(scores), k=1) == 1, -np.inf, scores)
W = np.exp(scores - scores.max(axis=1, keepdims=True))
W = W / W.sum(axis=1, keepdims=True)
return W @ V, W
q, Kc, Vc = np.array([[1., 0.]]), np.array([[1., 0.], [0., 1.], [1., 1.]]), np.array([[1., 0.], [0., 1.], [.5, .5]])
out, w = attention(q, Kc, Vc)
print('chapter example: weights', w.ravel(), ' output', out.ravel())
rng = np.random.default_rng(3)
Q, K, V = rng.normal(size=(4, 8)), rng.normal(size=(4, 8)), rng.normal(size=(4, 5))
for causal in [False, True]:
ref = F.scaled_dot_product_attention(*(torch.tensor(a) for a in (Q, K, V)), is_causal=causal).numpy()
print(f'causal={causal}: matches PyTorch: {np.allclose(attention(Q, K, V, causal)[0], ref)}')
print('causal weights (row i may only look at columns j <= i):\n', attention(Q, K, V, causal=True)[1])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 ), 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.
def make_sequences(n, T, seed):
rng = np.random.default_rng(seed)
X = rng.normal(0, 1, (n, T, 1)).astype(np.float32)
y = (rng.random(n) > 0.5).astype(np.int64)
X[:, 0, 0] = np.where(y == 1, 2.0, -2.0) # the signal: the first number only
return torch.tensor(X), torch.tensor(y)
def positional_encoding(n, d):
pos = torch.arange(n)[:, None]
i = torch.arange(d // 2)[None, :]
angles = pos / 10000 ** (2 * i / d)
pe = torch.zeros(n, d)
pe[:, 0::2], pe[:, 1::2] = torch.sin(angles), torch.cos(angles)
return pe
class AttentionClassifier(nn.Module):
def __init__(self, T, d=32):
super().__init__()
self.embed = nn.Linear(1, d)
self.register_buffer('pe', positional_encoding(T, d))
self.query = nn.Parameter(torch.randn(d) / math.sqrt(d)) # "what am I looking for?"
self.key = nn.Linear(d, d)
self.value = nn.Linear(d, d)
self.out = nn.Linear(d, 2)
def forward(self, x, return_weights=False):
h = self.embed(x) + self.pe # (N, T, d)
scores = self.key(h) @ self.query / math.sqrt(h.shape[-1]) # (N, T)
weights = torch.softmax(scores, dim=1)
summary = (weights.unsqueeze(-1) * self.value(h)).sum(dim=1) # weighted sum of the values
logits = self.out(summary)
return (logits, weights) if return_weights else logits
T = 50
Xs_tr, ys_tr = make_sequences(2000, T, seed=0)
Xs_te, ys_te = make_sequences(500, T, seed=1)
torch.manual_seed(0)
model = AttentionClassifier(T)
opt = torch.optim.Adam(model.parameters(), lr=3e-3)
for epoch in range(8):
perm = torch.randperm(len(Xs_tr))
for k in range(0, len(Xs_tr), 64):
idx = perm[k:k + 64]
loss = F.cross_entropy(model(Xs_tr[idx]), ys_tr[idx])
opt.zero_grad(); loss.backward(); opt.step()
with torch.no_grad():
acc = (model(Xs_te).argmax(1) == ys_te).float().mean().item()
print(f'epoch {epoch + 1}: test accuracy {acc:.3f}')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
with torch.no_grad():
_, weights = model(Xs_te, return_weights=True)
mean_w = weights.mean(0).numpy()
plt.figure(figsize=(9, 2.8))
plt.bar(np.arange(1, T + 1), mean_w, color=['C3'] + ['C0'] * (T - 1))
plt.xlabel('position in the sequence'); plt.ylabel('mean attention weight')
plt.title(f'Where the trained model looks: {mean_w[0]:.0%} of its attention on position 1 (uniform would be {1 / T:.0%})'); plt.tight_layout(); plt.show()
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¶
| Section | What we saw |
|---|---|
| 1 | conv2d and max_pool from scratch match PyTorch |
| 2 | the CNN beats the MLP with fewer parameters, and tolerates shifts better (but augmentation is still needed) |
| 3 | first-layer filters respond to stroke directions |
| 4 | pretrained ImageNet features recognise faces from one photo per person far better than a CNN from scratch; a baseline still matters |
| 5 | a simple RNN’s memory vanishes exponentially; an LSTM with an open forget gate keeps it |
| 6 | attention from scratch matches PyTorch; a trained attention model learns where to look |