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 — Lab: CNNs, RNNs and Attention

Open in Colab

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.

ExerciseTopicPoints
1Convolution with padding and stride20
2Output sizes and parameter counts10
3Max pooling10
4A CNN for handwritten digits20
5A recurrent network, step by step20
6Scaled dot-product attention, with a causal mask20
ChallengeSinusoidal positional encoding+10

Complete the code where you see # TODO, then run the check cell under it.


Exercise 1: Convolution (20 points)

Complete conv2d(X, K, padding=0, stride=1) for one channel: X is an n×nn \times n array, K an f×ff \times f filter. Pad X with padding rows and columns of zeros on every side (np.pad helps), then slide K with step stride, computing ∑m,nX(i+m,j+n) K(m,n)\sum_{m,n} X(i+m, j+n)\,K(m,n) at each position. The output size is ⌊(n+2p−f)/s⌋+1\lfloor (n + 2p - f)/s \rfloor + 1.


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


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.


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.


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 h0=0\mathbf{h}_0 = \mathbf{0}:

ht=tanh⁡(Wxhxt+Whhht−1+b)\mathbf{h}_t = \tanh(W_{xh}\mathbf{x}_t + W_{hh}\mathbf{h}_{t-1} + \mathbf{b})

and returns all the hidden states, shape (T, hidden). W_xh has shape (hidden, d) and W_hh shape (hidden, hidden), as in PyTorch.

Question. Run rnn_forward on the one-dimensional input 1,0,0,…1, 0, 0, \dots (20 steps) with whh=0.5w_{hh} = 0.5 and with whh=0.95w_{hh} = 0.95. Print the last state in each case. What does this tell you about simple RNNs and long sequences?

Your 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)):

softmax ⁣(QK⊤d)V\text{softmax}\!\left(\frac{QK^\top}{\sqrt{d}}\right)V

Return the output and the weight matrix. When causal=True (then n=mn = m), position ii may only attend to positions j≤ij \le i: set the scores above the diagonal to −∞-\infty before the softmax.

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 PE(pos,2i)=sin⁡(pos/100002i/d)PE(pos, 2i) = \sin(pos / 10000^{2i/d}) and PE(pos,2i+1)=cos⁡(pos/100002i/d)PE(pos, 2i+1) = \cos(pos / 10000^{2i/d}) (sines in the even columns, cosines in the odd ones).


Lab Report

Submit this notebook with every check cell showing ✅ and your answers to the two questions.