Convolution, Pooling & Receptive Fields
Filters, feature maps, stride, padding and how far each neuron can see.
Every feature map in a convolutional network comes from one operation with four knobs: kernel size, padding, stride and dilation. Master their arithmetic (output shapes, parameter and FLOP counts, receptive fields) and you can read any CNN architecture at a glance, and you will see why the backward pass of a convolution is itself a convolution.
What you’ll learn
- Write a multi-channel convolutional layer exactly as frameworks compute it (a cross-correlation with padding, stride, dilation and groups), and prove that stride-1 convolution is translation equivariant.
- Derive the output size and the parameter and multiply–add counts of a layer, including and grouped convolutions.
- Explain max, average and global average pooling, and when a CNN is exactly or only approximately shift-invariant.
- Derive the receptive-field recursion and contrast it with the effective receptive field.
- Show that the gradient of a convolution with respect to its input is a transposed convolution.
Convolution, as frameworks compute it
In signal processing, the convolution of an image with a kernel flips the kernel before sliding it: . Deep learning libraries compute the cross-correlation instead and still call it convolution; PyTorch's documentation names its operator "the valid 2D cross-correlation operator". The two differ only by a rotation of the kernel, with .
For learned kernels the difference is invisible: training simply learns the flipped kernel. It matters when you import hand-designed filters, and in proofs, since convolution is commutative and associative while cross-correlation is neither.
Output size: padding, stride and dilation
Padding adds zeros on each side of the input, so border pixels get full windows. A stride moves the window pixels between outputs, subsampling the map. A dilation spaces the kernel's taps pixels apart, an "à trous" kernel that covers a wider area with the same weights. One formula covers all three:
A dilated kernel has taps spaced apart, so along one axis it spans
The padded input has rows, indexed . Output row places the first tap at row and the last at , which must still lie inside:
Counting the valid gives the formula frameworks use (PyTorch documents the same expression):
Two special cases are worth remembering. For odd , "same" padding with keeps the size, and with stride it gives , exactly half for even at :
| Layer | Input | Output | Where you meet it |
|---|---|---|---|
| , , | the workhorse of VGG and ResNet | ||
| , , | ResNet's stem: | ||
| max pool, , | right after ResNet's stem | ||
| , , , | dilated layers for segmentation | ||
| , , | channel mixing and bottlenecks |
A convolution with dilation , stride and padding is applied to a input. How wide is the output?
Show the answer
31 pixels
. The dilated kernel spans 5 pixels, but padding 1 is less than the "same" padding , so the map loses a column before halving. With the answer would be exactly .
Parameters, FLOPs and 1×1 convolutions
Each of the filters holds weights and one bias, whatever the image size:
Each output value is one dot product of length , and there are of them. Counting a multiply–add (MAC) as 2 FLOPs:
With groups , the channels are split into independent groups and each filter reads only of them, so both counts divide by . The extreme is a depthwise convolution, one filter per channel (Efficient ConvNets builds networks from it):
A worked example. A convolution from 256 to 256 channels on a map has parameters and costs MACs, about GFLOPs per image. A fully connected layer between the same two tensors would need weights, a million times more. That factor is what locality and weight sharing buy. Notice the asymmetry: parameters do not depend on the image size, while compute and activation memory grow with . Early, high-resolution layers therefore cost many FLOPs and much activation memory per parameter, while late, wide layers hold most of the parameters; halving the map while doubling the channels, as VGG and ResNet do at each stage, keeps the FLOPs per stage roughly constant.
convolutions. With a layer is a matrix applied at every pixel independently: a fully connected layer across channels, shared over positions (Lin, Chen & Yan, 2014). It changes the number of channels cheaply. Shrinking 256 channels to 64 at costs million MACs, a ninth of a layer doing the same, which is the trick inside Inception modules and ResNet bottlenecks (CNN Architectures: LeNet to ConvNeXt).
How it runs. Many libraries lower a convolution to one large matrix product: unfold every receptive-field patch into a column (im2col), giving a matrix, and multiply by the weight matrix. This uses fast matrix-multiply kernels at the price of copying each input pixel up to times; FFT and Winograd algorithms are faster for some shapes.
import torch
import torch.nn as nn
conv = nn.Conv2d(in_channels=256, out_channels=256, kernel_size=3, stride=1, padding=1)
x = torch.randn(8, 256, 56, 56) # (batch, channels, height, width)
print(conv(x).shape) # torch.Size([8, 256, 56, 56])
print(conv.weight.shape) # torch.Size([256, 256, 3, 3])
print(sum(p.numel() for p in conv.parameters())) # 590080 = 256 * (256*9 + 1)
# dilation 2 with "same" padding 2, stride 2, and 4 groups of channels
down = nn.Conv2d(64, 128, kernel_size=3, stride=2, padding=2, dilation=2, groups=4)
print(down(torch.randn(1, 64, 64, 64)).shape) # torch.Size([1, 128, 32, 32])
print(down.weight.shape) # torch.Size([128, 16, 3, 3]): 64/4 inputs per filternn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True) is the whole design space of this lesson. With groups, the stored weight has shape .
Pooling, equivariance and invariance
A pooling layer summarizes each window of a feature map, channel by channel, with no learned parameters. Max pooling keeps the largest value, so a feature survives if it fired anywhere in the window; average pooling keeps the mean. Their gradients differ accordingly: max pooling routes the whole upstream gradient to the winning position, average pooling spreads it evenly. A stride-2 convolution can do the same downsampling job with learned weights, and replacing max pooling by strided convolutions costs no accuracy on several benchmarks (Springenberg et al., 2015).
Global average pooling averages each channel over all positions, turning into a -vector (Lin, Chen & Yan, 2014). It replaced the huge fully connected layers of early CNNs: in VGG-16, the first fully connected layer alone holds 103 of its 138 million parameters.
A network applies a stride-2 convolution with circular padding to an image of even size, then stride-1 convolutions and ReLUs, then global average pooling. For which circular shifts of the input is its output guaranteed to be exactly unchanged?
- Every shift, because convolution is equivariant
- No nonzero shift: strides destroy all symmetry
- Only shifts by exactly one pixel
- Shifts by an even number of pixels in each direction
Show the answer
D. Shifts by an even number of pixels in each direction
Shifting the input by shifts the stride-2 output by exactly ; the stride-1 layers carry that shift along and the global average removes it. An odd shift moves the image against the stride-2 sampling grid, so the first layer computes genuinely different samples, and nothing guarantees the same output.
Receptive fields
The receptive field of a unit is the set of input pixels that can influence it. Along one axis it is an interval of width for every unit of layer , and the stride compounds: adjacent units of layer sit input pixels apart, the layer's jump.
Start from the input itself: one pixel sees itself, and neighbors are one pixel apart.
A unit of layer reads units of layer spaced apart, so the first and last of them are units, that is input pixels, apart. Each brings its own field of width :
Unrolling the recursion gives the closed form. Pooling layers count too, with their window and their stride:
Three regimes follow. Stride-1, undilated layers grow the field linearly, by per layer. A stride multiplies the growth of every later layer. Dilations with kernels grow it exponentially with no downsampling at all (Yu & Koltun, 2016):
In ResNet-50, the stride-2 stem gives with jump 2; the stride-2 max pool adds for with jump 4; the first convolution of the next stage adds for . Carried through all fifty layers of the original design (whose strides sit in the convolutions), the recursion gives a theoretical field of 483 pixels, more than twice the -pixel input.
The theoretical field says which pixels can matter, not how much they do. Luo et al. (2016) measured the effective receptive field, the magnitude of over input positions, and found it roughly Gaussian. In their analysis of stacked linear layers with uniform weights its width grows like with depth , while the theoretical field grows like , so the effective field occupies a shrinking fraction of it. It widens during training, and subsampling and dilation enlarge it, but in deep CNNs it stays far smaller than the theoretical numbers suggest.
The widget makes this exact for plain stacks. With layers of and equal weights, the gradient's profile has standard deviation pixels while the field is wide, and the central quarter of the field (the square of side ) receives 58% of the gradient for three layers, 79% for six and 87% for eight. Doubling dilations such as 1, 2, 4, 8 spread their paths unevenly, so their effective fields are lumpy rather than Gaussian.
Why is the effective receptive field concentrated in the middle of the theoretical one?
- Zero padding darkens the outer pixels of every layer
- A central pixel reaches the output through many more paths through the layers than a pixel near the edge of the field, and the path counts pile up like a sum of random offsets
- Pooling discards the outer pixels of each window
- Kernels are always initialized with larger weights in the middle
Show the answer
B. A central pixel reaches the output through many more paths through the layers than a pixel near the edge of the field, and the path counts pile up like a sum of random offsets
Every route from input pixel to output picks one tap per layer, so the offsets add up like a sum of independent steps. The number of routes ending at each input position is then a repeated convolution of the kernels, which by the central limit theorem tends to a Gaussian of width proportional to .
The backward pass is a convolution too
To train a CNN, backpropagation needs the gradient of the loss with respect to a layer's weights and to its input, given the upstream gradient . In one dimension, with one channel and stride 1, both turn out to be correlations of things you already have.
Weight multiplies in every output , so its gradient sums over all positions: a cross-correlation of the input with the upstream gradient.
Input appears in output with weight (zero outside the kernel). Summing over the outputs that see it gives a full convolution of with : zero-pad by and cross-correlate with the flipped kernel .
With stride , output reads , so the same sum runs only over positions divisible by . That equals inserting zeros between consecutive entries of and then convolving: a transposed convolution, which maps the small output grid back onto the large input grid.
import torch
import torch.nn.functional as F
x = torch.randn(1, 3, 32, 32, requires_grad=True)
w = torch.randn(8, 3, 3, 3)
y = F.conv2d(x, w, stride=2, padding=1) # (1, 8, 16, 16)
g = torch.randn_like(y) # upstream gradient dL/dy
(gx,) = torch.autograd.grad(y, x, grad_outputs=g) # (1, 3, 32, 32)
# the same gradient, computed as a transposed convolution with the same weights
gx_t = F.conv_transpose2d(g, w, stride=2, padding=1, output_padding=1)
print(torch.allclose(gx, gx_t, atol=1e-5)) # Trueoutput_padding=1 resolves the ambiguity that a stride creates: inputs of width 31 and 32 both give 16 outputs, so the transposed convolution must be told which width to restore.
Used as a layer in its own right, the transposed convolution upsamples, which is why segmentation decoders and image generators use it; older papers call it "deconvolution", although it does not invert the convolution. Deriving Backward Passes derives these vector–Jacobian products for every channel, group and stride, alongside those of matrix products, softmax and normalization.
Key takeaways
- Frameworks compute cross-correlation, , with weights shaped ; at stride 1 it commutes with every shift.
- Output size is ; a layer has parameters and multiply–adds; convolutions mix channels per pixel.
- Max, average and global average pooling summarize windows without parameters; stride-1 circular convolutions plus global averaging are exactly shift-invariant, while strides keep exact invariance only for multiples of the total stride.
- The receptive field obeys : linear growth without stride, faster after strides, exponential with doubling dilations; the effective receptive field is roughly Gaussian and much smaller.
- The weight gradient is a correlation of the input with the upstream gradient, and the input gradient is a transposed convolution with the same weights.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A convolution with stride 2 and padding 2 is applied to a input. What is the output size?
Show the answer
B.
. Padding is "same" padding, so with stride 2 the result is .
A convolution maps 128 channels to 256 channels with groups=4 and biases. How many parameters does it have?
Show the answer
D.
Each of the 256 filters reads channels: , a quarter of the ungrouped layer's weights.
Three convolutions with stride 1 have dilations 1, 2 and 4. How wide is the receptive field of a unit in the third layer?
- 7 pixels
- 17 pixels
- 15 pixels
- 135 pixels
Show the answer
C. 15 pixels
. Each layer adds pixels when there is no stride.
Which design makes a network's output exactly invariant to every circular shift of the input?
- Stride-1 circular convolutions with ReLUs, followed by global average pooling
- Stride-2 convolutions followed by global max pooling
- Convolutions followed by flattening and a fully connected layer
- Any CNN at all, because convolution is equivariant
Show the answer
A. Stride-1 circular convolutions with ReLUs, followed by global average pooling
Stride-1 circular convolutions and pointwise nonlinearities commute with every shift, and the global average discards where each value sits. Any stride restricts exact invariance to multiples of the total stride.
How does a framework compute the gradient of the loss with respect to the input of a stride-2 convolution?
- By dividing the upstream gradient by the kernel's Fourier transform
- By applying the same stride-2 cross-correlation to the upstream gradient
- With a transposed convolution: zeros inserted between the upstream gradient's entries, then a convolution with the same weights
- It cannot: a strided convolution is not invertible, so it has no input gradient
Show the answer
C. With a transposed convolution: zeros inserted between the upstream gradient's entries, then a convolution with the same weights
Each input pixel collects from every output that read it. Spreading back onto the input grid (the inserted zeros) and convolving with does exactly that. Frameworks expose the same operation as conv_transpose2d.
Go deeper
- Rotation-Equivariant & Steerable CNNs · Building rotations and reflections into convolution, from group convolutions to steerable filters.
- Visualizing What CNNs Learn · Feature visualization, deconvolution, network dissection and their caveats.
- Scattering Transforms · Wavelet cascades with provable stability to deformations: a mathematical model of CNNs.
Further reading
- V. Dumoulin & F. Visin, "A guide to convolution arithmetic for deep learning," arXiv:1603.07285 (2016).
- W. Luo, Y. Li, R. Urtasun & R. Zemel, "Understanding the effective receptive field in deep convolutional neural networks," NeurIPS (2016).
- F. Yu & V. Koltun, "Multi-scale context aggregation by dilated convolutions," ICLR (2016).
- A. Zhang, Z. C. Lipton, M. Li & A. J. Smola, Dive into Deep Learning, ch. 7 "Convolutional Neural Networks" (Cambridge University Press, 2023), free at d2l.ai.