A neuron in the first layer of a CNN looks at 9 pixels, a patch. A photo has hundreds of thousands of pixels, and the network has to decide whether it shows a dog. How can a layer that sees 9 pixels at a time lead to an answer about the whole picture?
Two things make it possible. First, the maps shrink as they go deeper, so a later window covers more of the picture. The shrinking is done by pooling (or by a strided convolution). Second, each layer builds on the one before, so what a deep neuron sees is the union of many small views. How much it sees is its receptive field. This lesson builds both.
Pooling: one number for each window
A pooling layer slides a window over a feature map like a convolution does, but it does not multiply by weights. It replaces the values in the window by one number.
- Max pooling keeps the largest value in the window.
- Average pooling keeps the mean of the values in the window.
Take a map and a window that moves 2 pixels at a time (stride 2), so the windows do not overlap:
The top-left window holds . Its maximum is 6 and its mean is . The top-right window holds : maximum 5, mean 2. The two windows at the bottom give 7 and 3.25 (left), 9 and 6.75 (right). So
A map has become : a quarter of the values. PyTorch’s F.max_pool2d and F.avg_pool2d give exactly these numbers.
Four facts about the layer:
- Window and stride. The usual choice is a window with stride 2, which halves the height and the width. In PyTorch the stride is the window size unless you say otherwise.
- Output size. It is the formula of P5.4 with no padding and no dilation, . A map with , gives . When the numerator is not a multiple of the stride, the floor drops the last rows and columns, as in P5.4: a map with , gives and the last row and column are never read.
- No parameters. The rule is fixed, so there is nothing to learn:
nn.MaxPool2d(2)has 0 parameters. Pooling saves compute and memory, because every later layer works on a smaller map. - One channel at a time. A feature map with several channels (P5.5) is pooled channel by channel. The height and width shrink and the number of channels stays the same.
See it: pool, shift, and watch the gradient
The widget pools a small image. Pick the image, the kind of pooling, the window and the stride. The output grid shows the result, and you can pick one output cell to see its window (dashed frame) and, for max pooling, the cell that won (the diamond).
Things to try:
- Choose A stroke, Max pooling, , stride 2. The output is . Shift the image right by 1: about half of the outputs change (the readout counts 8 of 16). Shift it by 2, the stride: the readout says the output is the unshifted output moved by one cell.
- Switch to Average pooling and shift by 1: 11 of 16 outputs change (it does change the outputs by smaller amounts).
- Press Gradient of the sum of the outputs with max pooling, , stride 2: only some pixels are orange 1s and the others are 0. With average pooling every pixel gets 0.25. Both are explained below.
What max pooling gives you, and what it does not
Choose One bright pixel in the widget. A bright pixel at column 2 sits in the window of columns 2 and 3. If the pixel moves to column 3, it is still in that window, and the max-pooled output is identical. So the output tolerates a small shift: the exact position inside the window stops mattering. That is useful for recognition, because a feature a little to the left or right is still the same feature.
Two limits matter.
- Only inside the window. If the pixel crosses a window border, the bright value moves to a neighbouring output cell: on the stroke, a one-pixel shift changed 8 of the 16 outputs of the max pool.
- A shift by the stride moves the output. Shifting by exactly the stride (2) moves every output by one cell. This is equivariance (P5.2), now on a coarser grid.
So pooling turns “exactly where” into “roughly where”. Together with the layers after it, this builds a tolerance to small shifts, but not invariance to shifts, rotation or size.
Go deeper Padding, ceil mode and ties in pooling layers
Pooling layers accept padding, but it is used less than in convolutions, and it behaves differently. For max pooling PyTorch pads with , so a padded cell never wins. For average pooling the padded zeros count by default (count_include_pad=True). On the map with , , , max pooling gives , average pooling gives (the zeros count in the divisor 9), and with count_include_pad=False it gives . PyTorch requires the padding to be at most half the window size and raises an error otherwise.
By default the floor is used (ceil_mode=False). With ceil_mode=True a window that is only partly inside the map still produces an output: a map with , gives instead of .
When two cells of a window tie for the maximum, the gradient still goes to one cell. In PyTorch 2.9.1 on a CPU it goes to the first of them, reading the window row by row. Ties are common where a ReLU has produced windows of zeros.
The gradient of pooling
Training sends a gradient back through every layer (P4.8), and pooling has no weights to update, so the question is only how the gradient reaches the input of the layer.
Max pooling. The output equals one input cell of the window, so a small change of that cell changes the output by the same amount, and a small change of any other cell changes nothing. The gradient of the output with respect to the input is 1 for the winning cell and 0 for the others. The upstream gradient (the gradient that arrives from the layer after, P4.8) goes whole to the winner. For the matrix above and upstream gradients , (top row) and , (bottom row), one for each window, the input gradient has four non-zero entries:
The 0.4 sits at the cell that held the 6, the at the 5, the 0.8 at the 7 and the 0.1 at the 9. Twelve of the 16 cells get nothing: they did not take part in the output. With overlapping windows (stride smaller than the window) one cell can win several windows and collect several gradients. On this with , the cell holding 9 wins all four windows, and the gradient of the sum of the outputs there is 4.
Average pooling. The output is the mean of cells, so each cell moves it by of its own change. The upstream gradient is shared equally: each cell of a window gets a quarter. With the same upstream gradients the input gradient is
Both results come from the chain rule of P4.8, and autograd gives the same matrices. Max pooling routes the gradient like a switch, and average pooling spreads it like a sprinkler.
Global average pooling
The last feature map of a CNN has channels of size , for instance channels of . To classify, a layer must turn it into a vector. One way is to flatten it into numbers and use a dense layer (P4.5) to 10 classes, which has parameters.
Global average pooling takes the average of each whole channel. It is average pooling with a window as large as the map, so becomes a vector of length 64: one number per channel. The dense layer to 10 classes then has parameters, about 48 times fewer. (F.adaptive_avg_pool2d(x, 1) does it and equals x.mean((2, 3)).)
Each number says how much of this feature is present on average over the picture, and it ignores where in the last map the feature was. P5.7 builds a network that ends this way.
Strided convolution instead of pooling
P5.4 showed that a convolution with stride 2 also halves the map. So a strided convolution can do the job of pooling, with the difference that its weights are learned.
With a kernel whose four weights are all and stride 2, a convolution is average pooling (PyTorch confirms the outputs are equal). With other weights, the layer learns its own way of combining the window. The price is parameters and compute: by the formula of P5.4 a convolution with stride 2 from 64 to 64 channels has parameters, where pooling has 0. Max pooling cannot be written as a convolution, because taking a maximum is not a weighted sum.
The receptive field
Pooling shrinks the map. Now the second question: how much of the image does one neuron look at?
The receptive field of a neuron is the set of input pixels that can change its value. A neuron in the first layer of a convolution has a receptive field of : it reads 9 pixels.
Take a second layer on top. Use one axis (a row) to count. A neuron of layer 2 at position 3 reads layer-1 cells 3, 4 and 5. Layer-1 cell 3 read input pixels 3, 4, 5, and cell 5 read pixels 5, 6, 7. Together the neuron depends on pixels 3 to 7, which is 5 pixels, and in two dimensions . A third layer gives . With stride 1, each layer adds :
So grows by 2 per layer. To see pixels across, you would need 50 of them. Stride and pooling do better.
The jump
With a stride, neighbours in a deeper layer are further apart in the picture. Define the jump as the number of input pixels between two neighbouring cells of layer . The input has . If layer has stride , moving one cell in layer moves cells in layer , which is input pixels:
Now the field. Layer has window size (from now on, a dilated kernel uses its effective size of P5.4 in place of ). A neuron reads cells of layer , spaced input pixels apart. Each of those cells already has a field of pixels. The first and the last of the cells are pixels apart, so the union of their fields is plus that distance:
A worked stack, a image through convolution , pooling (stride 2), convolution , pooling . The sizes follow P5.4: . The recursion gives
- layer 1, conv : ,
- layer 2, pool , stride 2: ,
- layer 3, conv : ,
- layer 4, pool , stride 2: ,
A neuron of the last map sees pixels of the image. The second convolution is also , but it adds 8 pixels, twice as many as the first, because its neighbours are 2 pixels apart. Pooling needs no weights for this: it adds a little itself, and mostly it raises the jump, so every later layer adds more. The same arithmetic holds for convolution, max pooling and average pooling. Padding does not change the size of the field, but at the border part of it is cut off.
The recursion gives the width of the field. A dilated kernel can leave holes in it (P5.4), so fewer pixels than the width squared may count. The widget shows both.
See it: click a neuron
The widget draws the input () and three layers as grids. Each layer is a convolution, a max pooling or an average pooling, with its window , stride and (for a convolution) dilation . Pick a neuron in any layer, and every earlier grid highlights the cells that can influence it. The recursion is shown below the controls, with your numbers put in.
Things to try:
- Start with Conv, pool, conv. The neuron of layer 3 sees of the input: and the jump doubles at the pool. Select a neuron in layer 2: it sees .
- Press Stride 2 each time: the maps are , and , and the single neuron of layer 3 sees all pixels. The jump is , so .
- Press Pool first: a pool at layer 1 sees , but later layers add 4 per layer, and layer 3 reaches , bigger than three layers can reach.
- From Stride 2 each time, set the stride of layer 1 to 3: layer 3 no longer fits and a red message says why (the maps would be 5, 2 and then a window on a map).
Why small kernels in a stack
Two stacked convolutions see , the same as one convolution. Three see , like one . Which is cheaper? Take channels in and out. A layer has weights and two layers have , which is 28% fewer. A layer has and three layers have , about 45% fewer. With , counting biases, three layers have 110,784 parameters and one layer has 200,768 (PyTorch confirms both).
This is the argument that Simonyan and Zisserman made for the VGG networks (ICLR 2015): the stack has the field of the larger kernel with fewer parameters, and it has a non-linearity between the layers, three instead of one in the case. The two are not the same function: with one channel and no non-linearity, two layers have 18 free numbers and cannot produce every kernel, which has 25.
Growing the field fast
Three ways, and they combine:
- More layers. Each layer with stride 1 adds 2. Slow and linear.
- Stride or pooling. The jump doubles at every stride-2 layer, so each later layer adds more. Four layers with stride 1 see , and with stride 2 in all four they see . The cost is resolution: the position of a feature is known less precisely.
- Dilation (P5.4). The same weights cover a larger window. Three layers with see , and in general gives after layers, with no loss of resolution and (for this choice) no holes: the offsets cover every integer from to .
Go deeper The effective receptive field is smaller than the theoretical one
The recursion gives the theoretical field: the pixels that can change a neuron. Not all of them change it by the same amount. Luo, Li, Urtasun and Zemel (2016) studied how strongly each input pixel influences a neuron. They call this the effective receptive field, and report that it has a Gaussian distribution and occupies only a fraction of the theoretical field. One way to measure the influence is the gradient of the neuron with respect to each pixel.
A simple case shows why. Stack ten layers whose weights are all , with no non-linearity. The theoretical field is . Along one row the gradient is the 3-tap average convolved with itself ten times: it peaks at in the middle and falls to at the outermost pixel. In two dimensions the central pixels, about 27% of the 441, hold 94% of the gradient, and the central already hold 44%. The shape is close to a bell curve, because the repeated averaging adds independent steps (the central limit theorem of P1.D8): the profile is the distribution of a sum of ten independent steps of , 0 or , with standard deviation pixels.
So a neuron mostly looks at the middle of its theoretical field. With a ReLU and random weights the shape is close to Gaussian but less regular. In trained networks the paper reports that the effective field is still smaller than the theoretical one, and that it grows during training. The practical lesson is to treat the theoretical field as an upper limit and not as the area a neuron really uses.
Pooling and receptive fields: three ways to see it
Intuition
Pooling is like making a mosaic. Cover a photo with a grid of tiles and paint each tile in one colour, the brightest spot in it (max pooling) or the average (average pooling). The picture is smaller, and you can still tell what it shows, but not where inside a tile something sat.
The receptive field is like a rumour passing along a chain of people, where each person hears only from three neighbours. After one step you know what three people said, and after ten steps you could have heard from people ten places away. If every second person skipped ahead (a stride), the rumour would cover the distance faster.
The pictures break in two places. A mosaic tile is one colour but still has a place in the picture, while a pooling output forgets where inside the window the value came from. And in a chain, a far person has a weaker say than a near one, which is the effective receptive field of the Go-deeper box: reaching a pixel and being influenced strongly by it are not the same.
Math
Pooling. For a window and stride ,
with outputs per axis. Gradients. Let be the upstream gradient, let be the position of the maximum of window , and write for the set of windows that contain the pixel . Then the first line is for max pooling and the second for average pooling:
For max pooling the sum is empty (the gradient is 0) when the pixel wins no window. With stride equal to the window, each pixel is in one window and each sum has at most one term.
Receptive field. With and , the recursion and unrolls to
The th layer adds steps of the previous layer, each worth input pixels. With stride 1 everywhere the product is 1 and . Positions. With no padding, the neuron at index of layer reads the cells , , of layer , and applying this rule down the stack gives the exact set of input pixels it sees, which is what the widget draws.
Parameters of the VGG argument ( channels in and out, biases ignored): of three layers is , one layer is , and .
Code
PyTorch checks of this lesson, run locally with PyTorch 2.9.1. Shapes are .
import torch
import torch.nn as nn
import torch.nn.functional as F
x = torch.tensor([[1., 3, 2, 1],
[4, 6, 5, 0],
[7, 2, 9, 8],
[3, 1, 4, 6]]).reshape(1, 1, 4, 4)
print(F.max_pool2d(x, 2).flatten().tolist())
print(F.avg_pool2d(x, 2).flatten().tolist())
print("parameters:",
sum(p.numel() for p in nn.MaxPool2d(2).parameters()))
print("default stride:", nn.MaxPool2d(2).stride)
# gradient of max pooling
xm = x.clone().requires_grad_()
g = torch.tensor([[[[0.4, -0.2], [0.8, 0.1]]]])
F.max_pool2d(xm, 2).backward(g)
print(xm.grad[0, 0])
# global average pooling
f = torch.randn(1, 64, 7, 7)
print(F.adaptive_avg_pool2d(f, 1).shape)
print(torch.allclose(F.adaptive_avg_pool2d(f, 1).flatten(),
f.mean((2, 3)).flatten()))
# a strided convolution can imitate average pooling
w = torch.full((1, 1, 2, 2), 0.25)
print(torch.allclose(F.conv2d(x, w, stride=2), F.avg_pool2d(x, 2)))
print(sum(p.numel() for p in nn.Conv2d(64, 64, 2, stride=2).parameters()))
# receptive field with autograd: conv5, avgpool2, conv5, avgpool2
net = nn.Sequential(nn.Conv2d(1, 1, 5, bias=False), nn.AvgPool2d(2),
nn.Conv2d(1, 1, 5, bias=False), nn.AvgPool2d(2))
for conv in (net[0], net[2]):
nn.init.constant_(conv.weight, 1.0)
img = torch.ones(1, 1, 28, 28, requires_grad=True)
y = net(img) # (1, 1, 4, 4)
y[0, 0, 1, 2].backward()
rows, cols = (img.grad[0, 0] != 0).nonzero().T
print(tuple(y.shape[2:]), rows.min().item(), rows.max().item(),
cols.min().item(), cols.max().item())Output:
[6.0, 5.0, 7.0, 9.0]
[3.5, 2.0, 3.25, 6.75]
parameters: 0
default stride: 2
tensor([[ 0.0000, 0.0000, 0.0000, 0.0000],
[ 0.0000, 0.4000, -0.2000, 0.0000],
[ 0.8000, 0.0000, 0.1000, 0.0000],
[ 0.0000, 0.0000, 0.0000, 0.0000]])
torch.Size([1, 64, 1, 1])
True
True
16448
(4, 4) 4 19 8 23The last line says the neuron at row 1, column 2 of the output has a non-zero gradient on input rows 4 to 19 and columns 8 to 23, which is and matches the recursion. The start and with . (A max pooling layer would send its gradient to one cell per window, so for a stack that contains max pooling the pixels with a non-zero gradient for one input are fewer than the receptive field, and the field is the union over all inputs. For a check of the recursion, a linear stack like this one is cleanest.) The recursion was also compared with autograd on 100 random three-layer stacks of convolutions, max pools and average pools with window 1 to 5, stride 1 to 3 and dilation 1 to 4 (the set of pixels with a non-zero gradient, collected over many random inputs when there was a max pool, matched in every case).
Try it in Python
The first cell writes pooling from scratch, with the gradient. The second finds the receptive field of one neuron by brute force, by adding 1 to each input pixel in turn and seeing whether the output moves, and compares it with the recursion.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Running the cell gives the matrices of this lesson.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Running the cell gives an output of , 256 pixels that matter (rows 4 to 19, columns 8 to 23, a block) and the recursion’s last pair . Change layers to try other stacks; a stack with a stride-2 convolution, such as (3, 2, 1), gives the numbers of the widget.
Common mistakes
Quiz
Check your understanding
A window holds the values , , and . What do max pooling and average pooling output for it?
The largest value is 8 and the mean is . The option with and adds the four values and forgets to divide by 4. The option with and takes the second-largest value instead of the maximum. The option with and swaps the two kinds of pooling.
A map goes through max pooling with a window, stride 2 and no padding. What is the output size?
The formula gives . The size forgets the for the first window. The size would need a window of 2 and a stride of 2 on an 8-wide map. The option with would keep the size, but pooling with a stride above 1 shrinks the map.
Three layers without padding: a convolution with stride 1, a convolution with stride 2, and a convolution with stride 1. How wide is the receptive field of a neuron in the last layer?
The recursion gives with , then with , then . The value is what three layers with stride 1 give, and ignores the stride. The value is the field after the second layer only. The value does not come from any correct step of the recursion.
One convolution (stride 1, channels in and out) is replaced by two stacked convolutions. Which statement is correct?
Two layers see pixels across, like one layer, and have weights against , which is 28% fewer (biases aside). The option with a larger field is wrong because the stack ends at 5, not at 7. The option with the same number of weights ignores that . The option with a smaller field is wrong because the two fields are equal.
The last feature map of a network has shape . What does global average pooling output?
Global average pooling averages each channel over its whole map, so 64 channels give 64 numbers. The option that keeps describes a local smoothing with stride 1, not a global average. The option with would average over the channels, which is a different operation. A single number would also average over channels and discard which feature was present.
Exercises
- Pool with a window and stride 2, with max and with average. With an upstream gradient of 1 on every output, which input cells receive gradient from max pooling, and what do they get?
Show answer
Max pooling gives and average pooling gives . The maxima are at row 2, column 1 (the 5), row 1, column 4 (the 3), row 4, column 2 (the 3) and row 4, column 4 (the 7), counted from 1. Each receives 1 and the other 12 cells receive 0. With average pooling every cell receives . - A network has convolution , convolution , max pooling with stride 2, convolution , convolution , all other strides 1, no padding. What is the receptive field of a neuron after the last layer? What would it be without the pooling layer?
Show answer
: 3, 5, then the pool gives with , then , then . So . Without the pooling layer four layers give , so the pool adds 5 pixels of field and does it with no weights. - Three convolutions with stride 1 use dilations , and . What is the receptive field? Does it have holes?
Show answer
The effective sizes are 3, 5 and 7, so . The offsets are sums of one value from each of , and , and every integer from to appears, so there are no holes in this stack.
Next: P5.7 puts convolutions, pooling and a classifier into one CNN and trains it on images, where the shapes and receptive fields of this lesson and P5.4 are what you check first.