Convolution Layers
An MLP treats an image as a long list of numbers. Move a digit two pixels to the right and, as far as the first layer can tell, it is a completely different input: different weights see the stroke now. The MLP must learn "a vertical edge" separately at every position, with separate weights each time, and it pays for that in parameters and in data. A convolution layer makes the opposite assumption: the same small pattern detector is useful everywhere in the image, so it slides one small set of weights over all positions.
This lesson implements that layer. The Mathematics lesson on convolution shows why it is a linear operator with a structured matrix, and backpropagation through convolutions derives its gradients; here you write the forward pass twice in NumPy (with loops, then as one matrix product), add input and output channels, and check that PyTorch's nn.Conv2d computes exactly the same numbers.
One kernel sliding over one image
The lab shows a 12 12 image with integer grey levels 0 to 9 (a bright square, a diagonal line, a grey bar) and a 3 3 kernel. At each position the nine pixels under the window are multiplied by the nine kernel weights and summed; the sum is one value of the feature map. Pick Sobel x and watch where the map turns red (dark to bright, left to right) and blue (bright to dark). Then try box blur, sharpen and the Laplacian, and switch the padding to "same" to see the border.
With Sobel x and no padding the map is 10 10, its values run from -28 to 28, and it is zero wherever the image is flat: the kernel's weights sum to zero, so a constant patch gives nothing. That is the first job of a convolution layer: respond to a local pattern, ignore everything else.
The definition
Deep-learning libraries compute a cross-correlation: the kernel is not flipped (the mathematical convolution flips it, which only matters if you copy kernels between the two conventions; a learned kernel simply learns the flipped weights). For one input channel, a kernel , bias and stride 1:
so a valid convolution turns an image into an map. Real layers have input channels (three for RGB, or the maps of the previous layer) and output channels. Each output channel has its own kernel that spans all input channels and sums over them:
The weight is a 4-D array of shape and the layer has
parameters. The count does not depend on the image size at all: the same weights are reused at every position (weight sharing).
NumPy with loops
The lab's image and Sobel kernel, rebuilt in NumPy. The two inner loops slide the window; np.sum(window * w) is the nine products and their sum that the lab shows.
import numpy as np
# The 12 x 12 image of the convolution lab (0 = black, 9 = white)
img = np.ones((12, 12))
img[2:6, 1:5] = 8 # bright square
for k in range(5):
img[7 + k, 3 + k] = 9 # diagonal line
img[1:7, 8:10] = 5 # grey bar
sobel_x = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]], dtype=float)
def conv2d_loops(x, w):
"""Valid cross-correlation of one 2-D image with one 2-D kernel, stride 1."""
H, W = x.shape
k = w.shape[0]
out = np.zeros((H - k + 1, W - k + 1))
for i in range(out.shape[0]):
for j in range(out.shape[1]):
out[i, j] = np.sum(x[i:i + k, j:j + k] * w)
return out
fmap = conv2d_loops(img, sobel_x)
print("feature map shape:", fmap.shape)
print("min, max:", int(fmap.min()), int(fmap.max()))
print("output (0, 0):", int(fmap[0, 0]), " output (2, 2):", int(fmap[2, 2]))
print("row 2:", fmap[2].astype(int).tolist())feature map shape: (10, 10)
min, max: -28 28
output (0, 0): 7 output (2, 2): 0
row 2: [28, 0, 0, -28, -28, 0, 16, 16, -16, -16]
The numbers match the lab: a 10 10 map from -28 to 28. Output (0, 0) is 7 because the right column of the first window touches the bright square (the 8 at row 2, column 2) while the left column is background. Row 2 crosses the square and the grey bar: 28 at the square's left edge, -28 at its right edge, 16 and -16 at the two edges of the bar (5 against a background of 1, times the column weights 1 + 2 + 1).
Many channels, and im2col
Loops over output positions are slow in Python, and they are not how libraries work either. im2col ("image to columns") copies every patch into one column of a matrix. The convolution then becomes a single matrix product: the weights reshaped to times the patch matrix . The copy costs memory ( times the input), but the product runs as one fast BLAS call, which is the same trade many GPU kernels make. The function below builds the matrix with shifted slices instead of a loop over positions.
import numpy as np
def conv2d_loops(x, w, b):
"""x: (C_in, H, W), w: (C_out, C_in, k, k), b: (C_out,) -> (C_out, H-k+1, W-k+1)."""
C_out, C_in, k, _ = w.shape
Ho, Wo = x.shape[1] - k + 1, x.shape[2] - k + 1
out = np.zeros((C_out, Ho, Wo))
for o in range(C_out):
for i in range(Ho):
for j in range(Wo):
out[o, i, j] = np.sum(x[:, i:i + k, j:j + k] * w[o]) + b[o]
return out
def im2col(x, k):
"""Every k x k patch of every channel becomes one column: (C_in*k*k, Ho*Wo)."""
C, H, W = x.shape
Ho, Wo = H - k + 1, W - k + 1
cols = np.empty((C, k, k, Ho, Wo))
for a in range(k):
for c in range(k):
cols[:, a, c] = x[:, a:a + Ho, c:c + Wo] # one shifted view per kernel offset
return cols.reshape(C * k * k, Ho * Wo)
def conv2d_im2col(x, w, b):
C_out, C_in, k, _ = w.shape
Ho, Wo = x.shape[1] - k + 1, x.shape[2] - k + 1
out = w.reshape(C_out, -1) @ im2col(x, k) + b[:, None] # one matrix product
return out.reshape(C_out, Ho, Wo)
rng = np.random.default_rng(0)
x = rng.normal(size=(3, 10, 10)) # 3 input channels (e.g. RGB), 10 x 10
w = rng.normal(size=(4, 3, 3, 3)) # 4 filters, each 3 x 3 x 3
b = rng.normal(size=4)
y1 = conv2d_loops(x, w, b)
y2 = conv2d_im2col(x, w, b)
print("output shape:", y1.shape)
print("im2col matrix:", im2col(x, 3).shape, " weight matrix:", w.reshape(4, -1).shape)
print("same result:", np.allclose(y1, y2), "| max difference < 1e-12:", bool(np.abs(y1 - y2).max() < 1e-12))
print("parameters:", w.size + b.size, "= 4 * (3*3*3) + 4")
print("y[1, 0, :4]:", np.round(y1[1, 0, :4], 4).tolist())output shape: (4, 8, 8)
im2col matrix: (27, 64) weight matrix: (4, 27)
same result: True | max difference < 1e-12: True
parameters: 112 = 4 * (3*3*3) + 4
y[1, 0, :4]: [5.2255, 2.9633, 1.1824, -5.2626]
Three input channels, four filters of 3 3 3, a 10 10 input: the patch matrix is 27 64 (27 numbers per patch, 64 output positions), the reshaped weights 4 27, and the result equals the loop version to rounding. The layer has 112 parameters: 4 filters of 27 weights plus 4 biases.
The order of the 27 numbers in a patch must match the order of the reshaped weight: channel first, then kernel row, then kernel column. Get that wrong and the code still runs, still returns the right shape, and computes nonsense, which is why the next check compares against a library.
nn.Conv2d, matched exactly
nn.Conv2d(in_channels, out_channels, kernel_size) stores weight with the shape , the same layout as the NumPy array, and bias with shape . It expects a batch: input (N, C_in, H, W), output (N, C_out, H_out, W_out). Copy the NumPy weights in and the outputs must agree. This example is recorded (PyTorch does not run in the browser; it ran on a CPU).
import numpy as np
import torch
from torch import nn
def im2col(x, k):
C, H, W = x.shape
Ho, Wo = H - k + 1, W - k + 1
cols = np.empty((C, k, k, Ho, Wo))
for a in range(k):
for c in range(k):
cols[:, a, c] = x[:, a:a + Ho, c:c + Wo]
return cols.reshape(C * k * k, Ho * Wo)
torch.manual_seed(0)
conv = nn.Conv2d(in_channels=3, out_channels=4, kernel_size=3)
print("weight:", tuple(conv.weight.shape), " bias:", tuple(conv.bias.shape))
print("parameters:", sum(p.numel() for p in conv.parameters()))
rng = np.random.default_rng(0)
x = rng.normal(size=(3, 10, 10))
w = rng.normal(size=(4, 3, 3, 3))
b = rng.normal(size=4)
with torch.no_grad(): # copy the NumPy weights in
conv.weight.copy_(torch.tensor(w, dtype=torch.float32))
conv.bias.copy_(torch.tensor(b, dtype=torch.float32))
y_torch = conv(torch.tensor(x, dtype=torch.float32)[None]) # add a batch axis: (1, 3, 10, 10)
y_np = (w.reshape(4, -1) @ im2col(x, 3) + b[:, None]).reshape(4, 8, 8)
print("output:", tuple(y_torch.shape))
print("max |torch - numpy|:", f"{np.abs(y_torch[0].numpy() - y_np).max():.1e}")
print("y[1, 0, :4]:", [round(v, 4) for v in y_torch[0, 1, 0, :4].tolist()])
same = nn.Conv2d(3, 4, kernel_size=3, padding="same")
print("padding='same':", tuple(same(torch.zeros(2, 3, 10, 10)).shape))
lazy = nn.Conv2d(3, 4, 3, bias=False)
print("bias=False parameters:", sum(p.numel() for p in lazy.parameters()))weight: (4, 3, 3, 3) bias: (4,)
parameters: 112
output: (1, 4, 8, 8)
max |torch - numpy|: 2.0e-06
y[1, 0, :4]: [5.2255, 2.9633, 1.1824, -5.2626]
padding='same': (2, 4, 10, 10)
bias=False parameters: 108
The difference of about 2e-06 is float32 rounding (PyTorch's default dtype) against NumPy's float64; the printed values agree to four decimals. padding="same" adds a border of zeros so the map keeps the input size (for odd kernels and stride 1), and bias=False drops the four biases, which is usual when a batch normalisation layer follows and adds its own shift.
Equivariance and weight sharing, in numbers
Sliding the same kernel everywhere gives two properties. Translation equivariance: shift the input and the feature map shifts by the same amount, so a pattern is detected wherever it appears. Weight sharing: the parameter count depends on and the channels, never on the image size. The example checks the first and counts the second against a dense layer that maps the same input to an output of the same size.
import numpy as np
def conv2d(x, w): # one channel, valid, stride 1
k = w.shape[0]
Ho, Wo = x.shape[0] - k + 1, x.shape[1] - k + 1
return np.array([[np.sum(x[i:i + k, j:j + k] * w) for j in range(Wo)] for i in range(Ho)])
rng = np.random.default_rng(0)
x = np.zeros((16, 16)); x[3:7, 2:5] = 1.0 # a small blob
w = rng.normal(size=(3, 3))
shift = lambda a, di, dj: np.roll(np.roll(a, di, axis=0), dj, axis=1)
y = conv2d(x, w)
y_of_shifted = conv2d(shift(x, 5, 6), w) # move the blob, then convolve
shifted_y = shift(y, 5, 6) # convolve, then move the map
print("equivariant:", np.allclose(y_of_shifted, shifted_y))
peak = lambda a: tuple(int(v) for v in np.unravel_index(np.argmax(a), a.shape))
print("output shape:", y.shape, " peak at", peak(y), "-> after the shift", peak(y_of_shifted))
# Parameter count: 3 -> 16 channels on a 32 x 32 RGB image
H = W = 32; C_in, C_out, k = 3, 16, 3
conv = C_out * C_in * k * k + C_out
Ho = Wo = H - k + 1
dense = (C_in * H * W) * (C_out * Ho * Wo) + C_out * Ho * Wo # same input and output sizes
print(f"conv layer: {conv} parameters")
print(f"dense layer with the same input and output sizes: {dense:,} parameters")
print(f"ratio: {dense / conv:,.0f}")equivariant: True
output shape: (14, 14) peak at (1, 3) -> after the shift (6, 9)
conv layer: 448 parameters
dense layer with the same input and output sizes: 44,251,200 parameters
ratio: 98,775
Moving the blob by (5, 6) pixels moves the peak of the map from (1, 3) to (6, 9), and the whole map is exactly the shifted original (the blob stays away from the border, so the wrap-around of np.roll never touches it). For a 32 32 RGB image and 16 output channels of 3 3, the convolution has 448 parameters; a dense layer from the 3072 inputs to the same 16 30 30 outputs has 44,251,200, about 99,000 times more, and it would have to learn the same edge detector at each of the 900 positions separately.
Equivariance is not invariance: the map moves with the input; it does not stay the same. Pooling and a global average at the end (the next lesson) turn it into approximate invariance for classification. Padding and stride also break exact equivariance at the borders and for shifts that are not multiples of the stride.
Pitfalls
- Channel order. PyTorch is channels-first,
(N, C, H, W). Images from Matplotlib, OpenCV or PIL arrive as(H, W, C): permute them (x.permute(2, 0, 1)) before the layer, or the "channels" will be image rows. - Missing batch axis.
nn.Conv2daccepts an unbatched(C, H, W)input too, but most code after it (flattening,BatchNorm2d, losses) expects the batch axis. Add it withx[None]orx.unsqueeze(0). - Convolution vs cross-correlation. A hand-designed kernel taken from a signal-processing text may be written for the flipped convention: flip it with
w[::-1, ::-1]before using it in PyTorch. - im2col memory. The patch matrix is times larger than the input; for large images and batches, compute it in chunks or let the library choose the algorithm.
- Shapes that silently broadcast. A bias of shape
(C_out,)added to a(C_out, H*W)matrix needsb[:, None]; without it NumPy raises only when the sizes happen to differ.
Practice
- How many parameters does
nn.Conv2d(64, 128, kernel_size=3)have? And withkernel_size=1? - A layer maps a
(8, 3, 28, 28)batch withnn.Conv2d(3, 6, 5). What is the output shape? - Change
conv2d_im2colto accept a batch(N, C_in, H, W)with one matrix product for the whole batch. Which axis order of the patch array makes the final reshape simple? - In the lab, why does the box blur give 1.0 on the plain background, while Sobel x gives 0?
Answer
- . With : . A 1 1 convolution is a dense layer applied at every pixel, mixing channels only.
(8, 6, 24, 24): .- Build the patches as
(C_in*k*k, N*Ho*Wo)(or(N, C_in*k*k, Ho*Wo)and usenp.einsum/@with broadcasting). With columns ordered batch-first,out.reshape(C_out, N, Ho, Wo).transpose(1, 0, 2, 3)gives(N, C_out, Ho, Wo). - The box blur's weights are all and sum to 1, so a constant patch of 1 stays 1. Sobel x's weights sum to 0, so any constant patch gives 0.
Test yourself
What is the shape of the weight of nn.Conv2d(16, 32, kernel_size=5)?
- (16, 32, 5, 5)
- (32, 16, 5, 5)
- (5, 5, 16, 32)
- (32, 5, 5)
Why does a 3 3 conv layer from 3 to 16 channels have the same 448 parameters on a 32 32 and on a 224 224 image?
- PyTorch resizes the image first
- The same kernel weights are reused at every position (weight sharing)
- Padding removes the extra pixels
- The bias absorbs the size
In im2col for an input with 3 channels and a 3 3 kernel, how many rows does the patch matrix have?
- 9
- 3
- 27
- the number of output positions
You shift an image by 4 pixels to the right and apply a conv layer (stride 1, the object away from the borders). What happens to the feature map?
- It stays the same (invariance)
- It shifts 4 pixels to the right (equivariance)
- It shifts 4 pixels to the left
- It changes unpredictably