CodeRigor

LESSON

Scanning for patterns: the convolution layer

A convolution is one small detector scanned across the input with shared weights. Compute output sizes for any stride and padding and match F.conv2d in NumPy.

A pattern in an image, such as an edge or a letter, can appear anywhere. A dense layer would have to learn it again at every position. A convolution layer scans one small detector over every position and reuses its weights. This lesson pairs with Lectures 9 and 10 of CMU's 11-785 (Fall 2026), linked under Watch & read. You build the scan, the output-size arithmetic and max pooling in NumPy, and check them against PyTorch.

Start with the shapes. The input is (N, C_in, H, W): a batch of N images with C_in channels. The weights are a kernel of shape (C_out, C_in, kH, kW): C_out detectors, each looking at a kH × kW window across all input channels. The output is (N, C_out, H_out, W_out). One output value is the sum, over every input channel and every offset inside the window, of window × kernel, plus the bias of that output channel. The same kernel is used at every position. That is the weight sharing.

One kernel, four windows
start / 4
A 5 × 5 input, a 3 × 3 kernel and stride 2. The highlighted window is multiplied by the kernel and summed to give one output value.
One kernel, four windows
A 5 × 5 input, a 3 × 3 kernel and stride 2. The highlighted window is multiplied by the kernel and summed to give one output value.

The kernel in the figure is [[1, 0, -1], [2, 0, -2], [1, 0, -1]]. It subtracts the right column of the window from the left one, so it fires on a vertical edge. At the top left the three rows contribute 6, 16 and 8, a total of 30. Reproduce it:

Python
import numpy as np

x = np.array([[8, 9, 2, 1, 1], [9, 9, 1, 1, 0], [9, 8, 1, 2, 1], [8, 9, 2, 1, 1], [9, 9, 1, 0, 1]])
k = np.array([[1, 0, -1], [2, 0, -2], [1, 0, -1]])
window = x[0:3, 0:3]
print((window * k).sum(), (window * k[::-1, ::-1]).sum())

The second number is the same sum with the kernel flipped. We return to it below.

How many positions are there? With padding zeros on each side a row has size + 2 × padding cells. A window of kernel cells can start at 0, stride, 2 × stride, and so on, as long as it still fits. So

output size = floor((size + 2 × padding - kernel) / stride) + 1

Two examples. Size 7, kernel 3, stride 2, padding 1 gives (7 + 2 - 3) // 2 + 1 = 4. Size 8, kernel 3, stride 2, no padding gives (8 - 3) // 2 + 1 = 3. The windows start at 0, 2 and 4 and cover columns 0 to 6, so column 7 is never read. The floor discards the remainder. Rows and columns are computed separately, each from its own size and kernel size.

Size 7, kernel 3, stride 2, padding 1
start / 4
One padded row. The first and last cell are the zero padding. Four windows fit; a fifth would start at cell 8 and run off the end.
Size 7, kernel 3, stride 2, padding 1
One padded row. The first and last cell are the zero padding. Four windows fit; a fifth would start at cell 8 and run off the end.
Python
def out_size(size, kernel, stride=1, padding=0):
    return (size + 2 * padding - kernel) // stride + 1

print(out_size(7, 3, 2, 1), out_size(8, 3, 2, 0))
conv = 16 * 3 * 3 * 3 + 16
dense = (3 * 32 * 32) * (16 * 32 * 32) + 16 * 32 * 32
print(conv, dense, dense // conv)

The second pair of numbers is the cost of sharing. A convolution with C_out filters has C_out × C_in × kH × kW weights plus C_out biases, whatever the image size. Sixteen 3 × 3 filters over a 3-channel image have 448 parameters. A dense layer that maps a 3 × 32 × 32 image to a 16 × 32 × 32 map, the shape a padded 3 × 3 convolution produces, has 50,348,032, which is 112,384 times more. It would also need to learn the same detector separately at every position.

Now the flip. Textbook convolution flips the kernel before sliding it. Deep learning libraries skip the flip and still call the layer convolution; the operation is cross-correlation. A network that learns its kernels would learn the flipped one equally well, so training does not care, but any hand-built kernel or comparison with another implementation does:

Python
import numpy as np

print(np.correlate([1, 4, 2, 3], [1, 0, -1], "valid"), np.convolve([1, 4, 2, 3], [1, 0, -1], "valid"))

For a kernel that is not symmetric under the flip the two give different numbers. The edge kernel above is antisymmetric, so flipping it negates every output: 30 becomes -30.

Max pooling has no weights. It takes the maximum over each window, per example and channel, and its stride defaults to the window size, so windows do not overlap and a 2 × 2 pool halves each even spatial size. It gives tolerance to small shifts, but only partly:

Python
import numpy as np

def pool(a):
    return np.array(a).reshape(-1, 2).max(axis=1).tolist()

print(pool([0, 5, 0, 0]), pool([5, 0, 0, 0]), pool([0, 0, 5, 0]))

Moving the 5 within its window changes nothing. Moving it across a window boundary moves it to the neighbouring output cell.

These are the mistakes this lesson's tests are built to catch:

  • Starting the window at (i, j) instead of (i × stride, j × stride). Stride 1 is right, so a first test passes, and the shapes are right, so nothing crashes.
  • Flipping the kernel, which computes true convolution.
  • Padding one side only, or leaving out the factor 2 in the size formula.
  • Treating the bias as one number for the whole layer instead of one per output channel, or summing only some of the input channels.

The tests compare your functions with F.conv2d and F.max_pool2d in float64 for strides 1 to 3, paddings 0 to 2, several channels, non-square inputs and kernels, with and without bias, plus one case checked by hand. Agreement to 1e-10 shows your loops compute the same numbers as PyTorch for those cases. It does not show that the layer is useful, and it does not cover dilation, groups or different strides per axis. Plain loops are also slow, and real libraries use much faster algorithms for the same result.

Watch & read

Free lectures, talks and readings that cover this skill from another angle. All resources →

Builds convolution as a sliding weighted sum and shows it on images. Use it for the picture of a window moving over data, before you worry about channels and strides.