Simple Algorithm
Deep Learning · Representation · 22 min

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 ⌊(H+2p−d(k−1)−1)/s⌋+1\big\lfloor (H+2p-d(k-1)-1)/s\big\rfloor+1 and the parameter and multiply–add counts of a layer, including 1×11\times1 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 rℓ=rℓ−1+(kℓ−1) dℓ∏i<ℓsir_\ell=r_{\ell-1}+(k_\ell-1)\,d_\ell\prod_{i<\ell}s_i 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 xx with a kernel ww flips the kernel before sliding it: (x∗w)[i,j]=∑u,vx[i−u, j−v] w[u,v](x * w)[i,j]=\sum_{u,v}x[i-u,\,j-v]\,w[u,v]. Deep learning libraries compute the cross-correlation (x⋆w)[i,j]=∑u,vx[i+u, j+v] w[u,v](x\star w)[i,j]=\sum_{u,v}x[i+u,\,j+v]\,w[u,v] instead and still call it convolution; PyTorch's documentation names its operator "the valid 2D cross-correlation operator". The two differ only by a 180∘180^\circ rotation of the kernel, x⋆w=x∗wˉx\star w=x*\bar w with wˉ[u,v]=w[−u,−v]\bar w[u,v]=w[-u,-v].

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.

Y[o,i,j]  =  bo+∑c=1Cin∑u=0k−1∑v=0k−1W[o,c,u,v]  X~[c,  s i+d u,  s j+d v],o=1,…,CoutY[o,i,j]\;=\;b_o+\sum_{c=1}^{C_{\text{in}}}\sum_{u=0}^{k-1}\sum_{v=0}^{k-1}W[o,c,u,v]\;\tilde X\big[c,\;s\,i+d\,u,\;s\,j+d\,v\big],\qquad o=1,\dots,C_{\text{out}}
A convolutional layer. X~\tilde X is the input X∈RCin×H×WX\in\R^{C_{\text{in}}\times H\times W} padded with pp zeros on every side, ss is the stride and dd the dilation. The weight tensor W∈RCout×Cin×k×kW\in\R^{C_{\text{out}}\times C_{\text{in}}\times k\times k} has exactly the shape PyTorch stores, and each output channel oo has its own kernel spanning all input channels.

Output size: padding, stride and dilation

Padding adds pp zeros on each side of the input, so border pixels get full windows. A stride ss moves the window ss pixels between outputs, subsampling the map. A dilation dd spaces the kernel's taps dd pixels apart, an "à trous" kernel that covers a wider area with the same k2k^2 weights. One formula covers all three:

DerivationThe output-size formula
  1. keff=d(k−1)+1  input pixels.k_{\text{eff}}=d(k-1)+1\ \text{ input pixels.}

    A dilated kernel has kk taps spaced dd apart, so along one axis it spans

  2. s i+d(k−1)  ≤  H+2p−1⟺i  ≤  H+2p−d(k−1)−1ss\,i+d(k-1)\;\le\;H+2p-1\quad\Longleftrightarrow\quad i\;\le\;\frac{H+2p-d(k-1)-1}{s}

    The padded input has H+2pH+2p rows, indexed 0,…,H+2p−10,\dots,H+2p-1. Output row ii places the first tap at row s is\,i and the last at s i+d(k−1)s\,i+d(k-1), which must still lie inside:

  3. Hout=⌊H+2p−d(k−1)−1s⌋+1H_{\text{out}}=\Big\lfloor\frac{H+2p-d(k-1)-1}{s}\Big\rfloor+1

    Counting the valid i=0,1,2,…i=0,1,2,\dots gives the formula frameworks use (PyTorch documents the same expression):

  4. p=d(k−1)2:Hout=⌊H−1s⌋+1=⌈Hs⌉p=\tfrac{d(k-1)}{2}:\qquad H_{\text{out}}=\Big\lfloor\frac{H-1}{s}\Big\rfloor+1=\Big\lceil\frac{H}{s}\Big\rceil

    Two special cases are worth remembering. For odd kk, "same" padding p=d(k−1)/2p=d(k-1)/2 with s=1s=1 keeps the size, and with stride ss it gives ⌈H/s⌉\lceil H/s\rceil, exactly half for even HH at s=2s=2:

LayerInputOutputWhere you meet it
3×33\times3, p=1p=1, s=1s=156565656the workhorse of VGG and ResNet
7×77\times7, p=3p=3, s=2s=2224224112112ResNet's stem: ⌊(224+6−6−1)/2⌋+1\lfloor(224+6-6-1)/2\rfloor+1
3×33\times3 max pool, p=1p=1, s=2s=21121125656right after ResNet's stem
3×33\times3, d=2d=2, p=2p=2, s=1s=156565656dilated layers for segmentation
1×11\times1, p=0p=0, s=1s=156565656channel mixing and bottlenecks
Pooling windows obey the same formula, with kk the window size. When the division is not exact, the last rows of the input are simply never visited.
Predict before you look

A 3×33\times3 convolution with dilation 22, stride 22 and padding 11 is applied to a 64×6464\times64 input. How wide is the output?

Show the answer

31 pixels

⌊(64+2−2⋅2−1)/2⌋+1=⌊61/2⌋+1=31\lfloor(64+2-2\cdot2-1)/2\rfloor+1=\lfloor61/2\rfloor+1=31. The dilated kernel spans 5 pixels, but padding 1 is less than the "same" padding d(k−1)/2=2d(k-1)/2=2, so the map loses a column before halving. With p=2p=2 the answer would be exactly 3232.

Parameters, FLOPs and 1×1 convolutions

DerivationWhat a layer costs
  1. #params=Cout (Cink2+1)\#\text{params}=C_{\text{out}}\,(C_{\text{in}}k^2+1)

    Each of the CoutC_{\text{out}} filters holds Cink2C_{\text{in}}k^2 weights and one bias, whatever the image size:

  2. #MACs=Cout Cin k2 HoutWout,#FLOPs≈2 #MACs\#\text{MACs}=C_{\text{out}}\,C_{\text{in}}\,k^2\,H_{\text{out}}W_{\text{out}},\qquad\#\text{FLOPs}\approx2\,\#\text{MACs}

    Each output value is one dot product of length Cink2C_{\text{in}}k^2, and there are CoutHoutWoutC_{\text{out}}H_{\text{out}}W_{\text{out}} of them. Counting a multiply–add (MAC) as 2 FLOPs:

  3. #params=Cout(Cingk2+1),#MACs=CoutCink2HoutWoutg\#\text{params}=C_{\text{out}}\Big(\frac{C_{\text{in}}}{g}k^2+1\Big),\qquad\#\text{MACs}=\frac{C_{\text{out}}C_{\text{in}}k^2H_{\text{out}}W_{\text{out}}}{g}

    With groups gg, the channels are split into gg independent groups and each filter reads only Cin/gC_{\text{in}}/g of them, so both counts divide by gg. The extreme g=Cing=C_{\text{in}} is a depthwise convolution, one filter per channel (Efficient ConvNets builds networks from it):

A worked example. A 3×33\times3 convolution from 256 to 256 channels on a 56×5656\times56 map has 256 (256⋅9+1)=590,080256\,(256\cdot9+1)=590{,}080 parameters and costs 562⋅2562⋅9≈1.85×10956^2\cdot256^2\cdot9\approx1.85\times10^9 MACs, about 3.73.7 GFLOPs per image. A fully connected layer between the same two 56×56×25656\times56\times256 tensors would need (56⋅56⋅256)2≈6.4×1011(56\cdot56\cdot256)^2\approx6.4\times10^{11} 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 H×WH\times W. 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.

1×11\times1 convolutions. With k=1k=1 a layer is a Cout×CinC_{\text{out}}\times C_{\text{in}} 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 56×5656\times56 costs 5151 million MACs, a ninth of a 3×33\times3 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 Cink2×HoutWoutC_{\text{in}}k^2\times H_{\text{out}}W_{\text{out}} matrix, and multiply by the Cout×Cink2C_{\text{out}}\times C_{\text{in}}k^2 weight matrix. This uses fast matrix-multiply kernels at the price of copying each input pixel up to k2k^2 times; FFT and Winograd algorithms are faster for some shapes.

python
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 filter

nn.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 Cout×Cin/g×k×kC_{\text{out}}\times C_{\text{in}}/g\times k\times k.

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 C×H×WC\times H\times W into a CC-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.

Check your understanding

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?

  1. Every shift, because convolution is equivariant
  2. No nonzero shift: strides destroy all symmetry
  3. Only shifts by exactly one pixel
  4. 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 2t2\mathbf t shifts the stride-2 output by exactly t\mathbf t; 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 rℓr_\ell for every unit of layer ℓ\ell, and the stride compounds: adjacent units of layer ℓ\ell sit Jℓ=∏i≤ℓsiJ_\ell=\prod_{i\le\ell}s_i input pixels apart, the layer's jump.

DerivationThe receptive-field recursion
  1. r0=1,J0=1r_0=1,\qquad J_0=1

    Start from the input itself: one pixel sees itself, and neighbors are one pixel apart.

  2. rℓ=rℓ−1+(kℓ−1) dℓ Jℓ−1,Jℓ=Jℓ−1 sℓr_\ell=r_{\ell-1}+(k_\ell-1)\,d_\ell\,J_{\ell-1},\qquad J_\ell=J_{\ell-1}\,s_\ell

    A unit of layer ℓ\ell reads kℓk_\ell units of layer ℓ−1\ell-1 spaced dℓd_\ell apart, so the first and last of them are dℓ(kℓ−1)d_\ell(k_\ell-1) units, that is dℓ(kℓ−1)Jℓ−1d_\ell(k_\ell-1)J_{\ell-1} input pixels, apart. Each brings its own field of width rℓ−1r_{\ell-1}:

  3. rL=1+∑ℓ=1L(kℓ−1) dℓ∏i<ℓsir_L=1+\sum_{\ell=1}^{L}(k_\ell-1)\,d_\ell\prod_{i<\ell}s_i

    Unrolling the recursion gives the closed form. Pooling layers count too, with kℓk_\ell their window and sℓs_\ell their stride:

  4. dℓ=2ℓ−1, kℓ=3, sℓ=1:rL=1+2 (2L−1)=2L+1−1d_\ell=2^{\ell-1},\ k_\ell=3,\ s_\ell=1:\qquad r_L=1+2\,(2^L-1)=2^{L+1}-1

    Three regimes follow. Stride-1, undilated layers grow the field linearly, by k−1k-1 per layer. A stride multiplies the growth of every later layer. Dilations dℓ=2ℓ−1d_\ell=2^{\ell-1} with 3×33\times3 kernels grow it exponentially with no downsampling at all (Yu & Koltun, 2016):

In ResNet-50, the 7×77\times7 stride-2 stem gives r=7r=7 with jump 2; the 3×33\times3 stride-2 max pool adds 2⋅22\cdot2 for r=11r=11 with jump 4; the first 3×33\times3 convolution of the next stage adds 2⋅42\cdot4 for r=19r=19. Carried through all fifty layers of the original design (whose strides sit in the 1×11\times1 convolutions), the recursion gives a theoretical field of 483 pixels, more than twice the 224224-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 ∂ycenter/∂x\partial y_{\text{center}}/\partial x over input positions, and found it roughly Gaussian. In their analysis of stacked linear layers with uniform weights its width grows like n\sqrt{n} with depth nn, while the theoretical field grows like nn, so the effective field occupies a shrinking fraction O(1/n)\order{1/\sqrt n} 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 LL layers of 3×33\times3 and equal weights, the gradient's profile has standard deviation σ=2L/3\sigma=\sqrt{2L/3} pixels while the field is 2L+12L+1 wide, and the central quarter of the field (the square of side r/2r/2) 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.

Check your understanding

Why is the effective receptive field concentrated in the middle of the theoretical one?

  1. Zero padding darkens the outer pixels of every layer
  2. 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
  3. Pooling discards the outer pixels of each window
  4. 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 nn 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 n\sqrt n.

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 g=∂L/∂yg=\partial\loss/\partial y. In one dimension, with one channel and stride 1, both turn out to be correlations of things you already have.

DerivationGradients of $y[i]=sum_u w[u],x[i+u]$
  1. ∂L∂w[u]=∑ig[i] x[i+u]=(x⋆g)[u]\frac{\partial\loss}{\partial w[u]}=\sum_i g[i]\,x[i+u]=(x\star g)[u]

    Weight w[u]w[u] multiplies x[i+u]x[i+u] in every output ii, so its gradient sums over all positions: a cross-correlation of the input with the upstream gradient.

  2. ∂L∂x[j]=∑ig[i] w[j−i]=(g∗w)[j]\frac{\partial\loss}{\partial x[j]}=\sum_i g[i]\,w[j-i]=(g*w)[j]

    Input x[j]x[j] appears in output ii with weight w[j−i]w[j-i] (zero outside the kernel). Summing over the outputs that see it gives a full convolution of gg with ww: zero-pad gg by k−1k-1 and cross-correlate with the flipped kernel wˉ\bar w.

  3. ∂L∂x=ConvTranspose⁡s(g; w)\frac{\partial\loss}{\partial x}=\operatorname{ConvTranspose}_s(g;\,w)

    With stride ss, output ii reads x[s i+u]x[s\,i+u], so the same sum runs only over positions j−uj-u divisible by ss. That equals inserting s−1s-1 zeros between consecutive entries of gg and then convolving: a transposed convolution, which maps the small output grid back onto the large input grid.

python
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))         # True

output_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, Y[o,i,j]=bo+∑c,u,vW[o,c,u,v] X~[c,si+du,sj+dv]Y[o,i,j]=b_o+\sum_{c,u,v}W[o,c,u,v]\,\tilde X[c,si+du,sj+dv], with weights shaped Cout×Cin/g×k×kC_{\text{out}}\times C_{\text{in}}/g\times k\times k; at stride 1 it commutes with every shift.
  • Output size is ⌊(H+2p−d(k−1)−1)/s⌋+1\lfloor(H+2p-d(k-1)-1)/s\rfloor+1; a layer has Cout(Cink2/g+1)C_{\text{out}}(C_{\text{in}}k^2/g+1) parameters and CoutCink2HoutWout/gC_{\text{out}}C_{\text{in}}k^2H_{\text{out}}W_{\text{out}}/g multiply–adds; 1×11\times1 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 rℓ=rℓ−1+(kℓ−1)dℓ∏i<ℓsir_\ell=r_{\ell-1}+(k_\ell-1)d_\ell\prod_{i<\ell}s_i: 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.

Question 1

A 5×55\times5 convolution with stride 2 and padding 2 is applied to a 33×3333\times33 input. What is the output size?

  1. 16×1616\times16
  2. 17×1717\times17
  3. 15×1515\times15
  4. 33×3333\times33
Show the answer

B. 17×1717\times17

⌊(33+4−4−1)/2⌋+1=⌊32/2⌋+1=17\lfloor(33+4-4-1)/2\rfloor+1=\lfloor32/2\rfloor+1=17. Padding 2=(k−1)/22=(k-1)/2 is "same" padding, so with stride 2 the result is ⌈33/2⌉=17\lceil33/2\rceil=17.

Question 2

A 3×33\times3 convolution maps 128 channels to 256 channels with groups=4 and biases. How many parameters does it have?

  1. 295,168295{,}168
  2. 1,179,9041{,}179{,}904
  3. 289289
  4. 73,98473{,}984
Show the answer

D. 73,98473{,}984

Each of the 256 filters reads 128/4=32128/4=32 channels: 256 (32⋅9+1)=256⋅289=73,984256\,(32\cdot9+1)=256\cdot289=73{,}984, a quarter of the ungrouped layer's weights.

Question 3

Three 3×33\times3 convolutions with stride 1 have dilations 1, 2 and 4. How wide is the receptive field of a unit in the third layer?

  1. 7 pixels
  2. 17 pixels
  3. 15 pixels
  4. 135 pixels
Show the answer

C. 15 pixels

r=1+(3−1)(1+2+4)=15r=1+(3-1)(1+2+4)=15. Each layer adds (k−1) d(k-1)\,d pixels when there is no stride.

Question 4

Which design makes a network's output exactly invariant to every circular shift of the input?

  1. Stride-1 circular convolutions with ReLUs, followed by global average pooling
  2. Stride-2 convolutions followed by global max pooling
  3. Convolutions followed by flattening and a fully connected layer
  4. 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.

Question 5

How does a framework compute the gradient of the loss with respect to the input of a stride-2 convolution?

  1. By dividing the upstream gradient by the kernel's Fourier transform
  2. By applying the same stride-2 cross-correlation to the upstream gradient
  3. With a transposed convolution: zeros inserted between the upstream gradient's entries, then a convolution with the same weights
  4. 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 g[i] w[j−s i]g[i]\,w[j-s\,i] from every output ii that read it. Spreading gg back onto the input grid (the inserted zeros) and convolving with ww does exactly that. Frameworks expose the same operation as conv_transpose2d.

Go deeper

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.