Chapter 17 — Lab: Convolutional Layers
Lab Overview¶
You will write the arithmetic and the operations of convolutional layers in NumPy, and check them against PyTorch.
| Exercise | Topic | Points |
|---|---|---|
| 1 | Output size | 10 |
| 2 | A 2D convolution with padding and stride | 20 |
| 3 | A convolutional layer with channels | 20 |
| 4 | Max pooling | 15 |
| 5 | Counting parameters: dense against convolutional | 10 |
| 6 | The receptive field | 15 |
| 7 | Equivariance and global pooling | 10 |
| Challenge | im2col | +10 |
How it works. Each exercise has a function to complete where you see # TODO. Run the check cell under it: ✅ means your function is right, ❌ tells you what is wrong. Use NumPy only; PyTorch appears only in the checks. Do not change the check cells.
import numpy as np
import torch
import torch.nn.functional as F
def check(name, test):
"""Run one self-check: test() must return True; any exception or False is reported."""
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')
rng = np.random.default_rng(0)
torch_conv = lambda x, W, b, s, p: F.conv2d(torch.tensor(x)[None], torch.tensor(W), torch.tensor(b), stride=s, padding=p)[0].numpy()
print('Setup complete')Exercise 1: Output Size (10 points)¶
out_size(n, k, p, s) is the output size of a convolution (or pooling) with kernel k, padding p and stride s on an input of size n: .
def out_size(n, k, p=0, s=1):
# TODO
raise NotImplementedErrorcheck('5x5 input, 3x3 kernel: 3', lambda: out_size(5, 3) == 3)
check('"same" padding keeps 32', lambda: out_size(32, 5, 2, 1) == 32)
check('ResNet first layer: 224 -> 112', lambda: out_size(224, 7, 3, 2) == 112)
check('AlexNet first layer: 224 -> 55', lambda: out_size(224, 11, 2, 4) == 55)
check('agrees with PyTorch', lambda: all(out_size(n, k, p, s) == F.conv2d(torch.zeros(1, 1, n, n), torch.zeros(1, 1, k, k), stride=s, padding=p).shape[-1]
for n in (7, 10, 13) for k in (1, 3, 5) for p in (0, 1, 2) for s in (1, 2, 3)))Exercise 2: A 2D Convolution (20 points)¶
conv2d(img, K, stride, padding) takes a 2D image and a square kernel, pads the image with padding zeros on every side, and returns (no kernel flip, as in deep learning libraries).
def conv2d(img, K, stride=1, padding=0):
# TODO
raise NotImplementedErroredge = np.array([[0, 0, 0, 1, 1]] * 5, dtype=float)
check('the edge example of the chapter', lambda: np.array_equal(conv2d(edge, np.array([[-1, 0, 1]] * 3, dtype=float)), np.array([[0, 3, 3]] * 3)))
check('a 2x2 kernel by hand', lambda: np.array_equal(conv2d(np.arange(1.0, 10).reshape(3, 3), np.array([[1.0, 0], [0, -1]])), np.array([[-4, -4], [-4, -4]])))
img, K = rng.normal(size=(9, 11)), rng.normal(size=(3, 3))
check('no flip: matches PyTorch', lambda: np.allclose(conv2d(img, K), torch_conv(img[None], K[None, None], np.zeros(1), 1, 0)[0]))
check('padding 1, stride 2: matches PyTorch', lambda: np.allclose(conv2d(img, K, 2, 1), torch_conv(img[None], K[None, None], np.zeros(1), 2, 1)[0]))Exercise 3: A Convolutional Layer (20 points)¶
conv_layer(x, W, b, stride, padding): x has shape (C_in, H, W), the filters W have shape (C_out, C_in, k, k) and the biases b shape (C_out,). Output channel o is the sum over the input channels c of conv2d(x[c], W[o, c]), plus b[o]. You may use your conv2d.
def conv_layer(x, W, b, stride=1, padding=0):
# TODO
raise NotImplementedErrorx3, W3, b3 = rng.normal(size=(3, 8, 8)), rng.normal(size=(4, 3, 3, 3)), rng.normal(size=4)
check('the shape: 4 channels of 8x8 with "same" padding', lambda: conv_layer(x3, W3, b3, 1, 1).shape == (4, 8, 8))
check('matches PyTorch', lambda: np.allclose(conv_layer(x3, W3, b3, 1, 1), torch_conv(x3, W3, b3, 1, 1)))
check('with stride 2 and no padding', lambda: np.allclose(conv_layer(x3, W3, b3, 2, 0), torch_conv(x3, W3, b3, 2, 0)))
check('a 1x1 convolution is a channel mix at each pixel', lambda: np.allclose(conv_layer(x3, W3[:, :, :1, :1], b3)[:, 2, 5], W3[:, :, 0, 0] @ x3[:, 2, 5] + b3))Exercise 4: Max Pooling (15 points)¶
max_pool(x, k, stride): x has shape (C, H, W); return the maximum of every k × k window, moved by stride, for each channel.
def max_pool(x, k=2, stride=2):
# TODO
raise NotImplementedErrorcheck('a 4x4 example', lambda: np.array_equal(max_pool(np.arange(16.0).reshape(1, 4, 4)), [[[5, 7], [13, 15]]]))
z = rng.normal(size=(3, 9, 9))
check('2x2, stride 2: matches PyTorch', lambda: np.allclose(max_pool(z), F.max_pool2d(torch.tensor(z)[None], 2)[0].numpy()))
check('3x3, stride 2 (overlapping windows): matches PyTorch', lambda: np.allclose(max_pool(z, 3, 2), F.max_pool2d(torch.tensor(z)[None], 3, 2)[0].numpy()))
check('negative values: the maximum, not the largest magnitude', lambda: max_pool(-np.ones((1, 2, 2)) * np.array([[1, 2], [3, 4]]))[0, 0, 0] == -1)Exercise 5: Counting Parameters (10 points)¶
dense_params(n_in, n_out) counts a dense layer’s weights and biases; conv_params(c_in, c_out, k) a convolutional layer’s.
def dense_params(n_in, n_out):
# TODO
raise NotImplementedError
def conv_params(c_in, c_out, k):
# TODO
raise NotImplementedErrorcheck('a dense layer on a 224x224x3 image, 1000 units: 150.5 million', lambda: dense_params(224 * 224 * 3, 1000) == 150_529_000)
check('ResNet first layer: 9 472', lambda: conv_params(3, 64, 7) == 9472)
check('a 1x1 convolution, 256 -> 64 channels', lambda: conv_params(256, 64, 1) == 16448)
check('matches PyTorch', lambda: conv_params(16, 32, 3) == sum(p.numel() for p in torch.nn.Conv2d(16, 32, 3).parameters()))Exercise 6: The Receptive Field (15 points)¶
receptive_field(layers) takes a list of (kernel, stride) pairs, from the input up, and returns the receptive field (in input pixels, along one side) of a unit after the last layer. Start from 1; each layer adds (kernel - 1) * jump, where jump is the product of the strides of the layers before it.
def receptive_field(layers):
# TODO
raise NotImplementedErrorcheck('one 3x3 convolution sees 3x3', lambda: receptive_field([(3, 1)]) == 3)
check('three 3x3 convolutions see 7x7, like one 7x7', lambda: receptive_field([(3, 1)] * 3) == 7 == receptive_field([(7, 1)]))
check('the chapter\'s network: conv, pool, conv, pool, conv sees 18', lambda: receptive_field([(3, 1), (2, 2), (3, 1), (2, 2), (3, 1)]) == 18)
check('a stride only affects the layers after it', lambda: receptive_field([(3, 2)]) == 3 and receptive_field([(3, 2), (3, 1)]) == 7)Exercise 7: Equivariance and Global Pooling (10 points)¶
global_max_pool(x) takes feature maps (C, H, W) and returns a vector of length C: each channel’s maximum. Then run the check: shifting an image shifts a convolution’s output (equivariance), and the global maximum does not change (invariance).
def global_max_pool(x):
# TODO
raise NotImplementedErrorimg = np.zeros((1, 12, 12)); img[0, 3:6, 2:4] = 1
moved = np.roll(img, (2, 3), axis=(1, 2))
Wq, bq = rng.normal(size=(5, 1, 3, 3)), np.zeros(5)
fa, fb = conv_layer(img, Wq, bq, 1, 1), conv_layer(moved, Wq, bq, 1, 1)
check('equivariance: the feature maps shift with the image', lambda: np.allclose(np.roll(fa, (2, 3), axis=(1, 2)), fb))
check('invariance: global pooling gives the same vector', lambda: global_max_pool(fa).shape == (5,) and np.allclose(global_max_pool(fa), global_max_pool(fb)))
check('but stride-2 pooling changes with a 1-pixel shift', lambda: not np.allclose(max_pool(fa), max_pool(conv_layer(np.roll(img, (0, 1), axis=(1, 2)), Wq, bq, 1, 1))))Challenge: im2col (+10 points)¶
im2col(x, k) takes (C, H, W) and returns a matrix with one row per output position (row by row, stride 1, no padding), each row the flattened C × k × k patch. Then the whole layer is im2col(x, k) @ W.reshape(C_out, -1).T + b.
def im2col(x, k):
# TODO
raise NotImplementedErrorcols = im2col(x3, 3)
check('one row per position, C*k*k columns', lambda: cols.shape == (36, 27))
check('the layer as one matrix product', lambda: np.allclose((cols @ W3.reshape(4, -1).T + b3).T.reshape(4, 6, 6), torch_conv(x3, W3, b3, 1, 0)))Lab Report¶
Submit this notebook with:
every check cell showing ✅,
one paragraph: Exercise 7’s last check shows that stride-2 pooling gives a different result when the image moves by one pixel. Explain why, and what it means for a network that uses stride-2 pooling.