Convolutions: Filters, Strides and Shapes
Compute a convolution by hand with an edge filter and check it with PyTorch, predict output sizes for padding, stride, pooling and dilation with one formula, count the weights of convolutional and dense layers, trace the shapes of a small VGG-style network, and measure how the receptive field grows layer by layer.
Contentsand lesson path
On this page
- Why it matters
- What a filter computes
- Output shapes: padding, stride, pooling and dilation
- Counting parameters
- How far each output can see
- Check your understanding
- Apply it
- Review prompt
Lessons of CNNs & Computer Vision
- Convolutions: Filters, Strides and Shapes Concept · 20 min
- Lab: Train a Small CNN with Augmentation Lab · 30 min
- Why Residual Networks Train Deeper Concept · 15 min
- Lab: Transfer Learning with a Pretrained Backbone Lab · 30 min
- Beyond Classification: Detection and Segmentation at a Glance Concept · 15 min
- Check: Reading and Adapting a CNN Knowledge check · 8 questions
What you will learn
- Explain convolution, padding, stride, pooling, receptive fields and residual connections, and compute a CNN's output shapes and parameter count.
Prerequisites: Deep Learning Fundamentals
01. Why it matters
In the first PyTorch training loop an 8 × 8 digit was flattened into 64 numbers and fed to a multilayer perceptron (MLP). Flattening throws away the layout of the image: the network is not told that pixel 9 sits just below pixel 1. A convolutional neural network (CNN) keeps the layout. Its layers slide small grids of weights over the image and look at one neighbourhood at a time.
Most practical problems with CNNs are bookkeeping problems: a shape that does not match the next layer, a feature map that shrank to 1 × 1 too early, or a model that is far larger than expected. This lesson gives you the arithmetic to predict all three, and five short scripts to check it. You need Python 3.12 and PyTorch 2 (CPU build); each script runs in about a second.
02. What a filter computes
A filter (or kernel) is a small grid of weights, here 3 × 3. To compute one output value, place the filter on a 3 × 3 window of the image, multiply each pixel by the weight on top of it and add the nine products. Then slide the window one pixel and repeat. The grid of results is a feature map: it shows where in the image the pattern of the filter appears.
The filter below has −1 in its left column and +1 in its right column. On a flat region the two columns cancel and the output is 0. Where dark pixels are on the left and bright ones on the right, the right column wins and the output is positive. It is a vertical-edge detector. A CNN learns its filter weights by gradient descent instead of having them written by hand, but the first layer of a trained network often ends up with edge filters much like this one.
import torch
import torch.nn.functional as F
# A 5 x 6 greyscale image: dark (0) on the left, bright (1) on the right
img = torch.zeros(1, 1, 5, 6) # (batch, channels, height, width)
img[..., 3:] = 1.0
kernel = torch.tensor([[-1.0, 0.0, 1.0],
[-1.0, 0.0, 1.0],
[-1.0, 0.0, 1.0]]).view(1, 1, 3, 3) # (out, in, kh, kw)
print("image:")
print(img[0, 0].int())
# by hand: the 3 x 3 window whose top-left corner is at row 0, column 1
window = img[0, 0, 0:3, 1:4]
print("window at column 1:", window[0].int().tolist(), "(each row)")
print("sum of window * kernel:", (window * kernel[0, 0]).sum().item())
out = F.conv2d(img, kernel) # no padding, stride 1
print("conv2d output shape:", tuple(out.shape))
print(out[0, 0].int())
# move the edge one pixel to the right: the response moves with it
shifted = torch.zeros(1, 1, 5, 6)
shifted[..., 4:] = 1.0
print("edge shifted right by 1:")
print(F.conv2d(shifted, kernel)[0, 0].int())
# a horizontal edge: this filter does not respond at all
flat = torch.zeros(1, 1, 5, 6)
flat[:, :, 3:, :] = 1.0
print("horizontal edge, max |response|:", F.conv2d(flat, kernel).abs().max().item())python edge.pyimage:
tensor([[0, 0, 0, 1, 1, 1],
[0, 0, 0, 1, 1, 1],
[0, 0, 0, 1, 1, 1],
[0, 0, 0, 1, 1, 1],
[0, 0, 0, 1, 1, 1]], dtype=torch.int32)
window at column 1: [0, 0, 1] (each row)
sum of window * kernel: 3.0
conv2d output shape: (1, 1, 3, 4)
tensor([[0, 3, 3, 0],
[0, 3, 3, 0],
[0, 3, 3, 0]], dtype=torch.int32)
edge shifted right by 1:
tensor([[0, 0, 3, 3],
[0, 0, 3, 3],
[0, 0, 3, 3]], dtype=torch.int32)
horizontal edge, max |response|: 0.0The hand calculation for the window at column 1 gives 0 × (−1) + 0 × 0 + 1 × 1 = 1 per row, so 3 for the three rows, which is exactly the value F.conv2d puts at that position. Strictly, PyTorch computes a cross-correlation: it does not flip the kernel first, as the textbook definition of convolution does. For learned filters this does not matter: the network simply learns flipped weights.
Two properties are visible in the output. When the edge moves one pixel to the right, the response moves one pixel to the right too. This is called translation equivariance: the same filter is applied at every position, so a pattern produces the same response wherever it appears. And the filter does not react at all to a horizontal edge, so a layer needs several filters, each looking for a different pattern. Each filter produces one output channel, which is why the number of filters sets the number of output channels.
03. Output shapes: padding, stride, pooling and dilation
The 5 × 6 image above gave a 3 × 4 output, because a 3 × 3 window fits in only three rows and four columns. Four settings change this. Padding p adds p rows and columns of zeros around the input; with a 3 × 3 kernel, padding=1 keeps the size unchanged. Stride s moves the window s pixels at a time, so stride 2 roughly halves the height and width. Dilation d spreads the taps of the kernel d pixels apart, so a 3 × 3 kernel with dilation=2 covers a 5 × 5 area with nine weights. Pooling slides a window without weights: MaxPool2d(2) keeps the largest value in each 2 × 2 block, which halves the size and keeps the strongest response.
One formula covers all of them, applied separately to height and width: output = floor((n + 2p − d(k − 1) − 1) / s) + 1. With d = 1 it reduces to the common form floor((n + 2p − k) / s) + 1. The script prints the shape PyTorch produces next to the formula. Shapes are (batch, channels, height, width), the order PyTorch uses.
import torch
from torch import nn
def out_size(n, k, s=1, p=0, d=1):
"""Output size along one axis: floor((n + 2p - d(k - 1) - 1) / s) + 1."""
return (n + 2 * p - d * (k - 1) - 1) // s + 1
x = torch.randn(1, 3, 32, 32) # one RGB image of 32 x 32 pixels
layers = [
("Conv2d(3, 16, 3)", nn.Conv2d(3, 16, 3), (32, 3, 1, 0, 1)),
("Conv2d(3, 16, 3, padding=1)", nn.Conv2d(3, 16, 3, padding=1), (32, 3, 1, 1, 1)),
("Conv2d(3, 16, 3, stride=2, padding=1)",
nn.Conv2d(3, 16, 3, stride=2, padding=1), (32, 3, 2, 1, 1)),
("Conv2d(3, 8, 5, stride=2)", nn.Conv2d(3, 8, 5, stride=2), (32, 5, 2, 0, 1)),
("Conv2d(3, 16, 3, dilation=2)", nn.Conv2d(3, 16, 3, dilation=2), (32, 3, 1, 0, 2)),
("MaxPool2d(2)", nn.MaxPool2d(2), (32, 2, 2, 0, 1)),
]
for name, layer, args in layers:
y = layer(x)
print(f"{name:38s} -> {tuple(y.shape)} formula: {out_size(*args)}")
odd = torch.randn(1, 16, 7, 7)
print(f"{'MaxPool2d(2) on 7 x 7':38s} -> {tuple(nn.MaxPool2d(2)(odd).shape)}"
f" formula: {out_size(7, 2, 2)}")python shapes.pyConv2d(3, 16, 3) -> (1, 16, 30, 30) formula: 30
Conv2d(3, 16, 3, padding=1) -> (1, 16, 32, 32) formula: 32
Conv2d(3, 16, 3, stride=2, padding=1) -> (1, 16, 16, 16) formula: 16
Conv2d(3, 8, 5, stride=2) -> (1, 8, 14, 14) formula: 14
Conv2d(3, 16, 3, dilation=2) -> (1, 16, 28, 28) formula: 28
MaxPool2d(2) -> (1, 3, 16, 16) formula: 16
MaxPool2d(2) on 7 x 7 -> (1, 16, 3, 3) formula: 3Every row agrees with the formula. Take the 5 × 5 kernel with stride 2 and no padding: (32 − 5) / 2 = 13.5, rounded down to 13, plus 1 gives 14. The floor matters: a window that would hang over the edge is not computed. That is also why the 7 × 7 map pools to 3 × 3. If you would rather keep partial windows, pooling layers accept ceil_mode=True. Notice too that pooling leaves the channel count alone (3 stays 3), while each convolution replaces it with its own number of filters.
04. Counting parameters
A convolution has one filter per output channel, and each filter spans all input channels. A layer with kernel k × k, C_in input channels and C_out output channels therefore has k · k · C_in · C_out weights plus C_out biases, one per filter. The count does not depend on the image size, because the same weights are reused at every position. This reuse is called weight sharing.
from torch import nn
def n_params(module):
return sum(p.numel() for p in module.parameters())
conv1 = nn.Conv2d(3, 16, kernel_size=3)
conv2 = nn.Conv2d(16, 32, kernel_size=3)
print("Conv2d(3, 16, 3):", n_params(conv1), "=", 3 * 3 * 3 * 16, "+", 16)
print("Conv2d(16, 32, 3):", n_params(conv2), "=", 3 * 3 * 16 * 32, "+", 32)
print("weight tensor shape:", tuple(conv2.weight.shape), "(out, in, kh, kw)")
# a dense layer that maps the same 3 x 32 x 32 input to a 16 x 30 x 30 output
dense_weights = (3 * 32 * 32) * (16 * 30 * 30)
print(f"dense layer with the same input and output sizes: {dense_weights:,} weights")
c = 64 # two 3 x 3 layers vs one 5 x 5, no bias
two_3x3 = nn.Sequential(nn.Conv2d(c, c, 3, bias=False), nn.Conv2d(c, c, 3, bias=False))
one_5x5 = nn.Conv2d(c, c, 5, bias=False)
print(f"64 -> 64 channels: two 3x3 = {n_params(two_3x3):,},",
f"one 5x5 = {n_params(one_5x5):,}")python params.pyConv2d(3, 16, 3): 448 = 432 + 16
Conv2d(16, 32, 3): 4640 = 4608 + 32
weight tensor shape: (32, 16, 3, 3) (out, in, kh, kw)
dense layer with the same input and output sizes: 44,236,800 weights
64 -> 64 channels: two 3x3 = 73,728, one 5x5 = 102,400The first layer has 3 × 3 × 3 × 16 = 432 weights and 16 biases. A dense (fully connected) layer that produced the same 16 × 30 × 30 output from the same input would need about 44 million weights, roughly 100,000 times more, and it would have to learn the edge pattern separately at each of the 900 positions. The last line shows the argument behind VGG-style networks: two stacked 3 × 3 layers see the same 5 × 5 area as one 5 × 5 layer (you will measure that below), with 2 × 9 = 18 instead of 25 weights per channel pair and an extra non-linearity between them.
The next script traces a small network in that style: blocks of two 3 × 3 convolutions with padding 1, each followed by a 2 × 2 max-pool. The usual pattern is that the height and width shrink while the number of channels grows. At the end, global average pooling (AdaptiveAvgPool2d(1)) averages each channel over all positions, so the classifier gets one number per channel whatever the input size.
import torch
from torch import nn
# A small VGG-style network: blocks of two 3x3 convolutions, then a 2x2 max-pool
net = nn.Sequential(
nn.Conv2d(3, 32, 3, padding=1), nn.ReLU(),
nn.Conv2d(32, 32, 3, padding=1), nn.ReLU(),
nn.MaxPool2d(2),
nn.Conv2d(32, 64, 3, padding=1), nn.ReLU(),
nn.Conv2d(64, 64, 3, padding=1), nn.ReLU(),
nn.MaxPool2d(2),
nn.AdaptiveAvgPool2d(1), # global average: one value per channel
nn.Flatten(),
nn.Linear(64, 10),
)
x = torch.randn(1, 3, 32, 32)
print(f"{'input':18s} {tuple(x.shape)}")
for layer in net:
x = layer(x)
n = sum(p.numel() for p in layer.parameters())
if n or isinstance(layer, (nn.MaxPool2d, nn.AdaptiveAvgPool2d)):
print(f"{type(layer).__name__:18s} {str(tuple(x.shape)):18s} params {n:6d}")
print("total parameters:", sum(p.numel() for p in net.parameters()))python trace.pyinput (1, 3, 32, 32)
Conv2d (1, 32, 32, 32) params 896
Conv2d (1, 32, 32, 32) params 9248
MaxPool2d (1, 32, 16, 16) params 0
Conv2d (1, 64, 16, 16) params 18496
Conv2d (1, 64, 16, 16) params 36928
MaxPool2d (1, 64, 8, 8) params 0
AdaptiveAvgPool2d (1, 64, 1, 1) params 0
Linear (1, 10) params 650
total parameters: 66218Check two rows by hand. The second convolution has 3 × 3 × 32 × 32 + 32 = 9,248 parameters. The last linear layer has 64 × 10 + 10 = 650. The whole network has 66,218 parameters, under a six-hundredth of what the single dense layer of the previous script would need. Most weights sit in the deeper convolutions, where the channel counts are largest.
05. How far each output can see
The receptive field of an output value is the area of the input image that can influence it. One 3 × 3 layer sees 3 × 3 pixels. A second 3 × 3 layer looks at a 3 × 3 window of the first layer's outputs, and each of those saw 3 × 3 pixels, so together they see 5 × 5. The last layers need to see most of the object; otherwise the network can only judge by local texture.
You can measure the receptive field instead of reasoning about it. The script below sets every weight to 1, picks the centre output, and calls backward(). The input pixels with a non-zero gradient are exactly those that can affect that output. Average pooling is used rather than max-pooling because max-pooling sends the gradient only to the largest value in each window, which would hide part of the area.
import torch
from torch import nn
def receptive_field(layers, size=21):
"""Backpropagate from the centre output pixel and measure the input area it sees."""
net = nn.Sequential(*layers)
for m in net.modules():
if isinstance(m, nn.Conv2d):
nn.init.constant_(m.weight, 1.0) # positive weights: nothing cancels out
nn.init.zeros_(m.bias)
x = torch.zeros(1, 1, size, size, requires_grad=True)
y = net(x)
h, w = y.shape[-2:]
y[0, 0, h // 2, w // 2].backward()
rows = x.grad[0, 0].abs().sum(dim=1).nonzero()
return int(rows.max() - rows.min() + 1)
def conv(k=3, stride=1, dilation=1):
pad = dilation * (k // 2) # keeps the size at stride 1
return nn.Conv2d(1, 1, k, stride=stride, padding=pad, dilation=dilation)
stacks = {
"one 3x3": [conv()],
"two 3x3": [conv(), conv()],
"three 3x3": [conv(), conv(), conv()],
"one 5x5": [conv(5)],
"3x3, 3x3 stride 2, 3x3": [conv(), conv(stride=2), conv()],
"3x3, avg-pool 2, 3x3": [conv(), nn.AvgPool2d(2), conv()],
"one 3x3, dilation 2": [conv(dilation=2)],
}
for name, layers in stacks.items():
r = receptive_field(layers)
print(f"{name:24s} receptive field {r} x {r}")python rf.pyone 3x3 receptive field 3 x 3
two 3x3 receptive field 5 x 5
three 3x3 receptive field 7 x 7
one 5x5 receptive field 5 x 5
3x3, 3x3 stride 2, 3x3 receptive field 9 x 9
3x3, avg-pool 2, 3x3 receptive field 8 x 8
one 3x3, dilation 2 receptive field 5 x 5With stride 1, each extra 3 × 3 layer adds k − 1 = 2 pixels: 3, 5, 7. Stride and pooling change the rate. After a stride-2 layer, neighbouring outputs sit two input pixels apart, so every later 3 × 3 layer adds 2 × 2 = 4 pixels instead of 2. In general, layer l adds (k − 1) times the product of all earlier strides. This is why real networks downsample early: ResNet-18 halves the resolution five times, so its last layers see a large part of a 224 × 224 image. Dilation reaches 5 × 5 with only nine weights, at the cost of skipping the pixels between its taps.
06. Check your understanding
07. Apply it
The practice project for this skill trains a CNN from scratch on a small image dataset and compares it with a fine-tuned pretrained backbone. Before training anything, plan the from-scratch model on paper.
- Choose an input size for your images and write a table with the output shape and parameter count of every layer, as
trace.pyprints it. Check your table by running the network on a random tensor. - Use the receptive-field rule to check that the last convolution sees at least half of the image; if it does not, add a stride-2 stage.
- Record the total parameter count. You will compare it with the trainable parameters of the fine-tuned model later.
08. Review prompt
Without looking back, explain what one output value of a convolution is; write the output-size formula and use it for a 3 × 3 kernel with padding 1 and stride 2 on a 64 × 64 input; give the parameter count of a convolution with k, C_in and C_out; explain why that count does not depend on the image size; and describe how stacking layers and adding stride make the receptive field grow.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.