Chapter 18 — Lab: CNNs, RNNs and Attention
Lab Overview¶
You will write the core operation of each architecture yourself (a convolution, a pooling layer, a recurrent step and attention), check each one against PyTorch, and then train a small CNN.
| Exercise | Topic | Points |
|---|---|---|
| 1 | Convolution with padding and stride | 20 |
| 2 | Output sizes and parameter counts | 10 |
| 3 | Max pooling | 10 |
| 4 | A CNN for handwritten digits | 20 |
| 5 | A recurrent network, step by step | 20 |
| 6 | Scaled dot-product attention, with a causal mask | 20 |
| Challenge | Sinusoidal positional encoding | +10 |
Complete the code where you see # TODO, then run the check cell under it.
import numpy as np
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
def check(name, test):
try:
ok = test()
except NotImplementedError:
print(f'❌ {name}: not implemented yet'); return
except Exception as e:
print(f'❌ {name}: {type(e).__name__}: {e}'); return
print(f'✅ {name}' if ok else f'❌ {name}: wrong result')
print('Setup complete.')Exercise 1: Convolution (20 points)¶
Complete conv2d(X, K, padding=0, stride=1) for one channel: X is an array, K an filter. Pad X with padding rows and columns of zeros on every side (np.pad helps), then slide K with step stride, computing at each position. The output size is .
def conv2d(X, K, padding=0, stride=1):
raise NotImplementedError # TODO_X = np.array([[10, 10, 0, 0, 0]] * 5, float)
_K = np.array([[1, 0, -1]] * 3, float)
def _torch_conv(X, K, p, s):
return F.conv2d(torch.tensor(X)[None, None], torch.tensor(K)[None, None], padding=p, stride=s)[0, 0].numpy()
check('the chapter example: a vertical edge', lambda: np.array_equal(conv2d(_X, _K), [[30, 30, 0]] * 3))
_R, _RK = np.random.default_rng(0).normal(size=(9, 9)), np.random.default_rng(1).normal(size=(3, 3))
check('padding 1, stride 1 matches PyTorch', lambda: np.allclose(conv2d(_R, _RK, 1, 1), _torch_conv(_R, _RK, 1, 1)))
check('padding 1, stride 2 matches PyTorch', lambda: np.allclose(conv2d(_R, _RK, 1, 2), _torch_conv(_R, _RK, 1, 2)))Exercise 2: Sizes and Parameters (10 points)¶
Complete output_size(n, f, p, s) and conv_params(f, c_in, c_out) (weights and biases of a convolutional layer).
def output_size(n, f, p=0, s=1):
raise NotImplementedError # TODO
def conv_params(f, c_in, c_out):
raise NotImplementedError # TODOcheck('output sizes from the chapter table', lambda: [output_size(32, 5), output_size(32, 3, 1), output_size(32, 3, 1, 2), output_size(224, 7, 3, 2)] == [28, 32, 16, 112])
check('16 filters of 3×3 on RGB: 448 parameters', lambda: conv_params(3, 3, 16) == 448)
check('agrees with nn.Conv2d', lambda: conv_params(5, 32, 64) == sum(p.numel() for p in nn.Conv2d(32, 64, 5).parameters()))Exercise 3: Max Pooling (10 points)¶
Complete max_pool(X, size=2): split X (whose sides are multiples of size) into size × size windows with stride size, and keep the maximum of each.
def max_pool(X, size=2):
raise NotImplementedError # TODO_P = np.array([[1, 3, 2, 1], [4, 6, 5, 0], [3, 1, 1, 2], [0, 2, 7, 4]], float)
check('the chapter example', lambda: np.array_equal(max_pool(_P), [[6, 5], [3, 7]]))
_Q = np.random.default_rng(2).normal(size=(6, 6))
check('matches F.max_pool2d with size 3', lambda: np.allclose(max_pool(_Q, 3), F.max_pool2d(torch.tensor(_Q)[None, None], 3)[0, 0].numpy()))Exercise 4: A CNN for Digits (20 points)¶
Complete make_cnn(): an nn.Sequential that takes a batch of shape (N, 1, 8, 8) and returns 10 scores. Use at least two Conv2d layers with ReLU, and at least one MaxPool2d. The training loop is given. Target: test accuracy ≥ 0.96.
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 make_cnn():
raise NotImplementedError # TODO
def train_cnn(model, epochs=40):
torch.manual_seed(0)
opt = torch.optim.Adam(model.parameters(), lr=1e-3)
loader = DataLoader(TensorDataset(to_t(X_tr), torch.tensor(y_tr)), 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 modeldef _cnn_ok():
torch.manual_seed(0)
model = make_cnn()
convs = sum(isinstance(m, nn.Conv2d) for m in model.modules())
pools = sum(isinstance(m, nn.MaxPool2d) for m in model.modules())
model = train_cnn(model)
with torch.no_grad():
acc = (model(to_t(X_te)).argmax(1).numpy() == y_te).mean()
print(f' {convs} conv layers, {pools} pooling layers, {sum(p.numel() for p in model.parameters())} parameters, test accuracy {acc:.3f}')
return convs >= 2 and pools >= 1 and acc >= 0.96
check('a CNN with test accuracy ≥ 0.96', _cnn_ok)Exercise 5: A Recurrent Network, Step by Step (20 points)¶
Complete rnn_forward(X, W_xh, W_hh, b), which runs a simple RNN over one sequence X of shape (T, d) from :
and returns all the hidden states, shape (T, hidden). W_xh has shape (hidden, d) and W_hh shape (hidden, hidden), as in PyTorch.
def rnn_forward(X, W_xh, W_hh, b):
raise NotImplementedError # TODOcheck('the chapter example: memory fades', lambda: np.allclose(rnn_forward(np.array([[1.], [0.], [0.], [0.]]), np.array([[1.]]), np.array([[0.5]]), np.zeros(1)).ravel(), [0.762, 0.363, 0.180, 0.090], atol=1e-3))
def _rnn_ok():
torch.manual_seed(0)
rnn = nn.RNN(3, 5, batch_first=True)
X = torch.randn(7, 3)
with torch.no_grad():
ref = rnn(X[None])[0][0].numpy()
W_xh, W_hh = rnn.weight_ih_l0.detach().numpy(), rnn.weight_hh_l0.detach().numpy()
b = (rnn.bias_ih_l0 + rnn.bias_hh_l0).detach().numpy()
return np.allclose(rnn_forward(X.numpy(), W_xh, W_hh, b), ref, atol=1e-5)
check('matches nn.RNN with the same weights', _rnn_ok)Question. Run rnn_forward on the one-dimensional input (20 steps) with and with . Print the last state in each case. What does this tell you about simple RNNs and long sequences?
# TODOYour answer:
Exercise 6: Scaled Dot-Product Attention (20 points)¶
Complete attention(Q, K, V, causal=False) for NumPy arrays Q (shape (n, d)), K ((m, d)) and V ((m, d_v)):
Return the output and the weight matrix. When causal=True (then ), position may only attend to positions : set the scores above the diagonal to before the softmax.
def attention(Q, K, V, causal=False):
raise NotImplementedError # TODO_q, _k, _v = np.array([[1., 0.]]), np.array([[1., 0.], [0., 1.], [1., 1.]]), np.array([[1., 0.], [0., 1.], [.5, .5]])
check('the chapter example', lambda: np.allclose(attention(_q, _k, _v)[0], [[0.602, 0.398]], atol=1e-3))
_rng = np.random.default_rng(3); _Q, _K, _V = _rng.normal(size=(4, 8)), _rng.normal(size=(4, 8)), _rng.normal(size=(4, 5))
_sdpa = lambda c: F.scaled_dot_product_attention(*(torch.tensor(a) for a in (_Q, _K, _V)), is_causal=c).numpy()
check('matches PyTorch', lambda: np.allclose(attention(_Q, _K, _V)[0], _sdpa(False)))
check('the causal mask matches PyTorch', lambda: np.allclose(attention(_Q, _K, _V, causal=True)[0], _sdpa(True)))
check('causal weights are zero above the diagonal', lambda: np.allclose(np.triu(attention(_Q, _K, _V, causal=True)[1], 1), 0))Question. Which Transformer family uses the causal mask, and why must it?
Your answer:
Challenge: Positional Encoding (+10 points)¶
Complete positional_encoding(n, d), returning an (n, d) array with and (sines in the even columns, cosines in the odd ones).
def positional_encoding(n, d):
raise NotImplementedError # TODOcheck('shape, and position 0 is (0, 1, 0, 1, ...)', lambda: positional_encoding(10, 16).shape == (10, 16) and np.allclose(positional_encoding(10, 16)[0], [0, 1] * 8))
check('one value from the formula', lambda: np.isclose(positional_encoding(50, 16)[7, 5], np.cos(7 / 10000 ** (4 / 16))))
check('every position is different', lambda: len({tuple(r.round(6)) for r in positional_encoding(100, 16)}) == 100)Lab Report¶
Submit this notebook with every check cell showing ✅ and your answers to the two questions.