Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 5: Computer Vision and CNNs

Pooling and receptive fields

P5.640 min●●○ IntermediateReviewed Dec 3, 2026

Why this matters for machine learning

A convolution looks at a few pixels at a time, yet a network must judge a whole picture. Pooling shrinks the maps, and the receptive field tells how much of the picture one neuron can see, which together decide what a CNN can recognise and what it costs.

  • A CNN is a stack of convolutions with pooling or strides between them, and the receptive field is how you check that the last layer sees enough of the image. (P5.7: Build a CNN)
  • Deeper neurons can respond to larger patterns because their receptive field is larger, which is what feature visualisation shows. (P5.8: What do CNNs learn?)

Before this: The convolution operation, Padding, stride and dilation, Backpropagation: step by step with numbers

After this lesson you can

  • Compute max pooling and average pooling by hand, give the output size for a window and stride, and say why pooling has no parameters
  • Say what max pooling does and does not do for a shifted input, and where the gradient of max pooling and of average pooling goes
  • Compute the receptive field of a neuron in a stack of convolution and pooling layers with the recursion rℓ=rℓ−1+(kℓ−1) jℓ−1r_\ell=r_{\ell-1}+(k_\ell-1)\,j_{\ell-1} and the jump jℓ=jℓ−1sℓj_\ell=j_{\ell-1}s_\ell
  • Explain why a stack of small kernels, strides, pooling or dilation grows the receptive field, and compare the cost with one large kernel

A neuron in the first layer of a CNN looks at 9 pixels, a 3×33\times3 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 3×33\times3 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 4×44\times4 map and a 2×22\times2 window that moves 2 pixels at a time (stride 2), so the windows do not overlap:

X=(1321465072983146)\mathbf{X}=\begin{pmatrix}1&3&2&1\\4&6&5&0\\7&2&9&8\\3&1&4&6\end{pmatrix}

The top-left window holds 1,3,4,61,3,4,6. Its maximum is 6 and its mean is 14/4=3.514/4=3.5. The top-right window holds 2,1,5,02,1,5,0: maximum 5, mean 2. The two windows at the bottom give 7 and 3.25 (left), 9 and 6.75 (right). So

max pool(X)=(6579),avg pool(X)=(3.523.256.75).\begin{aligned} \text{max pool}(\mathbf{X})&=\begin{pmatrix}6&5\\7&9\end{pmatrix},\\[4pt] \text{avg pool}(\mathbf{X})&=\begin{pmatrix}3.5&2\\3.25&6.75\end{pmatrix}. \end{aligned}

A 4×44\times4 map has become 2×22\times2: 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 2×22\times2 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, Hout=⌊(H−k)/s⌋+1H_{\text{out}}=\lfloor(H-k)/s\rfloor+1. A 28×2828\times28 map with k=2k=2, s=2s=2 gives 14×1414\times14. When the numerator is not a multiple of the stride, the floor drops the last rows and columns, as in P5.4: a 5×55\times5 map with k=2k=2, s=2s=2 gives 2×22\times2 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 8×88\times8 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).

Window k Stride s
Shift 0 px

Output size: ⌊(8 − 2) / 2⌋ + 1 = 4×4. The image is not shifted.

Input (values 0–9)
0000000000699600000049400004940000049400004940000049400000000000
Output (4×4). Pick a cell, or use the arrow keys.
0990049409900940
  • window of the selected output
  • ◇ its maximum (the cell that gets the gradient)
  • ✕ never read

Selected output: 9, the maximum of its window, at row 1, column 3. Nothing is learned here: pooling has no weights.

Pooling widget on an 8×8 image: choose the image, max or average pooling, window, stride and a shift of up to 2 pixels. The left grid is the input with the window of the selected output, the right grid is the output, and a second view shows the gradient of the sum of the outputs in orange. Nothing animates, so Lite Mode shows the same.

Things to try:

  1. Choose A stroke, Max pooling, 2×22\times2, stride 2. The output is 4×44\times4. 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.
  2. Switch to Average pooling and shift by 1: 11 of 16 outputs change (it does change the outputs by smaller amounts).
  3. Press Gradient of the sum of the outputs with max pooling, 2×22\times2, 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 2×22\times2 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 −∞-\infty, so a padded cell never wins. For average pooling the padded zeros count by default (count_include_pad=True). On the map (−3−1−2−4)\begin{pmatrix}-3&-1\\-2&-4\end{pmatrix} with k=3k=3, s=2s=2, p=1p=1, max pooling gives −1-1, average pooling gives −10/9≈−1.11-10/9\approx-1.11 (the zeros count in the divisor 9), and with count_include_pad=False it gives −2.5-2.5. 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 5×55\times5 map with k=2k=2, s=2s=2 gives 3×33\times3 instead of 2×22\times2.

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 X\mathbf{X} above and upstream gradients 0.40.4, −0.2-0.2 (top row) and 0.80.8, 0.10.1 (bottom row), one for each window, the input gradient has four non-zero entries:

(000000.4−0.200.800.100000)\begin{pmatrix}0&0&0&0\\0&0.4&-0.2&0\\0.8&0&0.1&0\\0&0&0&0\end{pmatrix}

The 0.4 sits at the cell that held the 6, the −0.2-0.2 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 X\mathbf{X} with k=3k=3, s=1s=1 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 k2k^2 cells, so each cell moves it by 1/k21/k^2 of its own change. The upstream gradient is shared equally: each cell of a 2×22\times2 window gets a quarter. With the same upstream gradients the input gradient is

(0.10.1−0.05−0.050.10.1−0.05−0.050.20.20.0250.0250.20.20.0250.025)\begin{pmatrix}0.1&0.1&-0.05&-0.05\\0.1&0.1&-0.05&-0.05\\0.2&0.2&0.025&0.025\\0.2&0.2&0.025&0.025\end{pmatrix}

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 CC channels of size H×WH\times W, for instance 6464 channels of 7×77\times7. To classify, a layer must turn it into a vector. One way is to flatten it into 64⋅49=313664\cdot49=3136 numbers and use a dense layer (P4.5) to 10 classes, which has 3136⋅10+10=31,3703136\cdot10+10=31{,}370 parameters.

Global average pooling takes the average of each whole channel. It is average pooling with a window as large as the map, so (C,H,W)=(64,7,7)(C,H,W)=(64,7,7) becomes a vector of length 64: one number per channel. The dense layer to 10 classes then has 64⋅10+10=65064\cdot10+10=650 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 2×22\times2 kernel whose four weights are all 1/41/4 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 2×22\times2 convolution with stride 2 from 64 to 64 channels has 4⋅64⋅64+64=16,4484\cdot64\cdot64+64=16{,}448 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 3×33\times3 convolution has a receptive field of 3×33\times3: it reads 9 pixels.

Take a second 3×33\times3 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 5×55\times5. A third 3×33\times3 layer gives 7×77\times7. With stride 1, each layer adds k−1k-1:

r=1+∑ℓ(kℓ−1).r=1+\sum_{\ell}(k_\ell-1).

So rr grows by 2 per 3×33\times3 layer. To see 100100 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 jℓj_\ell as the number of input pixels between two neighbouring cells of layer ℓ\ell. The input has j0=1j_0=1. If layer ℓ\ell has stride sℓs_\ell, moving one cell in layer ℓ\ell moves sℓs_\ell cells in layer ℓ−1\ell-1, which is sℓ jℓ−1s_\ell\,j_{\ell-1} input pixels:

jℓ=jℓ−1 sℓ.j_\ell=j_{\ell-1}\,s_\ell .

Now the field. Layer ℓ\ell has window size kℓk_\ell (from now on, a dilated kernel uses its effective size keff=d(k−1)+1k_{\text{eff}}=d(k-1)+1 of P5.4 in place of kℓk_\ell). A neuron reads kℓk_\ell cells of layer ℓ−1\ell-1, spaced jℓ−1j_{\ell-1} input pixels apart. Each of those cells already has a field of rℓ−1r_{\ell-1} pixels. The first and the last of the kℓk_\ell cells are (kℓ−1) jℓ−1(k_\ell-1)\,j_{\ell-1} pixels apart, so the union of their fields is rℓ−1r_{\ell-1} plus that distance:

rℓ=rℓ−1+(kℓ−1) jℓ−1,r0=1,j0=1.\begin{aligned} r_\ell&=r_{\ell-1}+(k_\ell-1)\,j_{\ell-1},\\ r_0&=1,\quad j_0=1 . \end{aligned}

A worked stack, a 28×2828\times28 image through convolution 5×55\times5, pooling 2×22\times2 (stride 2), convolution 5×55\times5, pooling 2×22\times2. The sizes follow P5.4: 28→24→12→8→428\to24\to12\to8\to4. The recursion gives

  • layer 1, conv 5×55\times5: r1=1+4⋅1=5r_1=1+4\cdot1=5, j1=1j_1=1
  • layer 2, pool 2×22\times2, stride 2: r2=5+1⋅1=6r_2=5+1\cdot1=6, j2=2j_2=2
  • layer 3, conv 5×55\times5: r3=6+4⋅2=14r_3=6+4\cdot2=14, j3=2j_3=2
  • layer 4, pool 2×22\times2, stride 2: r4=14+1⋅2=16r_4=14+1\cdot2=16, j4=4j_4=4

A neuron of the last 4×44\times4 map sees 16×1616\times16 pixels of the 28×2828\times28 image. The second convolution is also 5×55\times5, 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 (15×1515\times15) and three layers as grids. Each layer is a convolution, a max pooling or an average pooling, with its window kk, stride ss and (for a convolution) dilation dd. 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.

Layer 1
size k 3
stride s 1
dilation d 1
Layer 2
size k 2
stride s 2
dilation d 1
Layer 3
size k 3
stride s 1
dilation d 1

Neuron row 1, column 1 of layer 3 sees 8×8 of the 15×15 input, 64 of 225 pixels.

rℓ = rℓ−1 + (keff − 1) · jℓ−1, and jℓ = jℓ−1 · sℓ; keff = d(k − 1) + 1
Input: r₀ = 1, j₀ = 1
Layer 1 (conv 3×3, stride 1): r₁ = 1 + (3 − 1)·1 = 3, j₁ = 1·1 = 1
Layer 2 (max pool 2×2, stride 2): r₂ = 3 + (2 − 1)·1 = 4, j₂ = 1·2 = 2
Layer 3 (conv 3×3, stride 1): r₃ = 4 + (3 − 1)·2 = 8, j₃ = 2·1 = 2
Input, 15×15. Sees 8×8 (jump 1)
Layer 1: conv 3×3, stride 1 → 13×13. Sees 6×6 (jump 1)
Layer 2: max pool 2×2, stride 2 → 6×6. Sees 3×3 (jump 2)
Layer 3: conv 3×3, stride 1 → 4×4
  • selected neuron
  • • in its receptive field
  • dashed frame: the 8×8 extent

Click a cell of layer 1, 2 or 3, tap a grid and use the arrow keys, or use the buttons and sliders. Convolutions and pooling layers give the same field: only the window size, the stride and the dilation count. Padding is 0 here; with padding, a border neuron has the same field size, clipped at the edge of the image.

Receptive-field widget: three layers on a 15 by 15 input, each a convolution, a max pooling or an average pooling with window k, stride s and (convolutions only) dilation d, and no padding. Select a neuron by clicking a cell, with the arrow keys or with the sliders, and every earlier grid highlights its receptive field while the recursion is shown with your numbers. Nothing is animated, so Lite Mode shows the same.

Things to try:

  1. Start with Conv, pool, conv. The neuron of layer 3 sees 8×88\times8 of the input: r=3, 4, 8r=3,\ 4,\ 8 and the jump doubles at the pool. Select a neuron in layer 2: it sees 4×44\times4.
  2. Press Stride 2 each time: the maps are 7×77\times7, 3×33\times3 and 1×11\times1, and the single neuron of layer 3 sees all 15×1515\times15 pixels. The jump is 2,4,82,4,8, so r=3,7,15r=3,7,15.
  3. Press Pool first: a pool at layer 1 sees 2×22\times2, but later 3×33\times3 layers add 4 per layer, and layer 3 reaches 10×1010\times10, bigger than three 3×33\times3 layers can reach.
  4. 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 3×33\times3 window on a 2×22\times2 map).

Why small kernels in a stack

Two stacked 3×33\times3 convolutions see 5×55\times5, the same as one 5×55\times5 convolution. Three see 7×77\times7, like one 7×77\times7. Which is cheaper? Take CC channels in and out. A 5×55\times5 layer has 25C225C^2 weights and two 3×33\times3 layers have 2⋅9C2=18C22\cdot9C^2=18C^2, which is 28% fewer. A 7×77\times7 layer has 49C249C^2 and three 3×33\times3 layers have 27C227C^2, about 45% fewer. With C=64C=64, counting biases, three 3×33\times3 layers have 110,784 parameters and one 7×77\times7 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 7×77\times7 case. The two are not the same function: with one channel and no non-linearity, two 3×33\times3 layers have 18 free numbers and cannot produce every 5×55\times5 kernel, which has 25.

Growing the field fast

Three ways, and they combine:

  • More layers. Each 3×33\times3 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 3×33\times3 layers with stride 1 see 9×99\times9, and with stride 2 in all four they see 31×3131\times31. The cost is resolution: the position of a feature is known less precisely.
  • Dilation (P5.4). The same weights cover a larger window. Three 3×33\times3 layers with d=1,2,4d=1,2,4 see 15×1515\times15, and in general d=1,2,4,…,2m−1d=1,2,4,\dots,2^{m-1} gives 2m+1−12^{m+1}-1 after mm layers, with no loss of resolution and (for this choice) no holes: the offsets cover every integer from −7-7 to 77.
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 3×33\times3 layers whose weights are all 1/91/9, with no non-linearity. The theoretical field is 21×2121\times21. Along one row the gradient is the 3-tap average [1/3,1/3,1/3][1/3,1/3,1/3] convolved with itself ten times: it peaks at 0.1520.152 in the middle and falls to 3−10≈1.7⋅10−53^{-10}\approx1.7\cdot10^{-5} at the outermost pixel. In two dimensions the central 11×1111\times11 pixels, about 27% of the 441, hold 94% of the gradient, and the central 5×55\times5 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 −1-1, 0 or +1+1, with standard deviation 10⋅2/3≈2.6\sqrt{10\cdot2/3}\approx2.6 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 kk and stride ss,

yijmax⁡=max⁡0≤a,b<k xis+a,  js+b,yijavg=1k2∑a,b=0k−1xis+a,  js+b,\begin{aligned} y^{\max}_{ij}&=\max_{0\le a,b<k}\ x_{is+a,\;js+b},\\ y^{\text{avg}}_{ij}&=\frac1{k^2}\sum_{a,b=0}^{k-1}x_{is+a,\;js+b}, \end{aligned}

with ⌊(H−k)/s⌋+1\lfloor(H-k)/s\rfloor+1 outputs per axis. Gradients. Let gij=∂L/∂yijg_{ij}=\partial L/\partial y_{ij} be the upstream gradient, let a(i,j)a(i,j) be the position of the maximum of window (i,j)(i,j), and write S(u,v)\mathcal{S}(u,v) for the set of windows that contain the pixel (u,v)(u,v). Then the first line is for max pooling and the second for average pooling:

∂L∂xuv=∑(i,j): a(i,j)=(u,v)gij,∂L∂xuv=∑(i,j)∈S(u,v)gijk2.\begin{aligned} \frac{\partial L}{\partial x_{uv}}&=\sum_{(i,j):\,a(i,j)=(u,v)}g_{ij},\\ \frac{\partial L}{\partial x_{uv}}&=\sum_{(i,j)\in\mathcal{S}(u,v)}\frac{g_{ij}}{k^2}. \end{aligned}

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 j0=1j_0=1 and r0=1r_0=1, the recursion jℓ=jℓ−1sℓj_\ell=j_{\ell-1}s_\ell and rℓ=rℓ−1+(keff,ℓ−1) jℓ−1r_\ell=r_{\ell-1}+(k_{\text{eff},\ell}-1)\,j_{\ell-1} unrolls to

jℓ=∏i≤ℓsi,rm=1+∑ℓ=1m(keff,ℓ−1)∏i<ℓsi.\begin{aligned} j_\ell&=\prod_{i\le\ell}s_i,\\ r_m&=1+\sum_{\ell=1}^{m}(k_{\text{eff},\ell}-1)\prod_{i<\ell}s_i . \end{aligned}

The ℓ\ellth layer adds (keff,ℓ−1)(k_{\text{eff},\ell}-1) steps of the previous layer, each worth ∏i<ℓsi\prod_{i<\ell}s_i input pixels. With stride 1 everywhere the product is 1 and rm=1+∑(keff,ℓ−1)r_m=1+\sum(k_{\text{eff},\ell}-1). Positions. With no padding, the neuron at index tt of layer ℓ\ell reads the cells tsℓ+q dℓts_\ell+q\,d_\ell, q=0,…,kℓ−1q=0,\dots,k_\ell-1, of layer ℓ−1\ell-1, 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 (CC channels in and out, biases ignored): ∑\sum of three 3×33\times3 layers is 3⋅9C2=27C23\cdot9C^2=27C^2, one 7×77\times7 layer is 49C249C^2, and 27/49≈0.5527/49\approx0.55.

Code

PyTorch checks of this lesson, run locally with PyTorch 2.9.1. Shapes are (N,C,H,W)(N,C,H,W).

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 23

The last line says the neuron at row 1, column 2 of the 4×44\times4 output has a non-zero gradient on input rows 4 to 19 and columns 8 to 23, which is 16×1616\times16 and matches the recursion. The start 4=1⋅j44=1\cdot j_4 and 8=2⋅j48=2\cdot j_4 with j4=4j_4=4. (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.

Pooling and its gradient

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.

The receptive field by brute force, and by the recursion

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Running the cell gives an output of 4×44\times4, 256 pixels that matter (rows 4 to 19, columns 8 to 23, a 16×1616\times16 block) and the recursion’s last pair (16,4)(16,4). 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

  1. A 2×22\times2 window holds the values 22, 66, 44 and 88. What do max pooling and average pooling output for it?

  2. A 7×77\times7 map goes through max pooling with a 3×33\times3 window, stride 2 and no padding. What is the output size?

  3. Three layers without padding: a 3×33\times3 convolution with stride 1, a 3×33\times3 convolution with stride 2, and a 3×33\times3 convolution with stride 1. How wide is the receptive field of a neuron in the last layer?

  4. One 5×55\times5 convolution (stride 1, CC channels in and out) is replaced by two stacked 3×33\times3 convolutions. Which statement is correct?

  5. The last feature map of a network has shape (C,H,W)=(64,7,7)(C,H,W)=(64,7,7). What does global average pooling output?

Exercises

  1. Pool (2013540211620327)\begin{pmatrix}2&0&1&3\\5&4&0&2\\1&1&6&2\\0&3&2&7\end{pmatrix} with a 2×22\times2 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 answerMax pooling gives (5337)\begin{pmatrix}5&3\\3&7\end{pmatrix} and average pooling gives (2.751.51.254.25)\begin{pmatrix}2.75&1.5\\1.25&4.25\end{pmatrix}. 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 1/41/4.
  2. A network has convolution 3×33\times3, convolution 3×33\times3, max pooling 2×22\times2 with stride 2, convolution 3×33\times3, convolution 3×33\times3, 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 answerrr: 3, 5, then the pool gives 5+1⋅1=65+1\cdot1=6 with j=2j=2, then 6+2⋅2=106+2\cdot2=10, then 10+2⋅2=1410+2\cdot2=14. So 14×1414\times14. Without the pooling layer four 3×33\times3 layers give 1+4⋅2=91+4\cdot2=9, so the pool adds 5 pixels of field and does it with no weights.
  3. Three 3×33\times3 convolutions with stride 1 use dilations 11, 22 and 33. What is the receptive field? Does it have holes?
    Show answerThe effective sizes are 3, 5 and 7, so r=1+2+4+6=13r=1+2+4+6=13. The offsets are sums of one value from each of {−1,0,1}\{-1,0,1\}, {−2,0,2}\{-2,0,2\} and {−3,0,3}\{-3,0,3\}, and every integer from −6-6 to 66 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.

Key takeaways

  • Pooling replaces each window of a feature map by one number, the maximum or the average. The window size kk and stride ss (usually 2×22\times2 and 2) give the output size ⌊(H−k)/s⌋+1\lfloor(H-k)/s\rfloor+1 of P5.4 without padding. A pooling layer has no parameters, and acts on each channel on its own.
  • Max pooling gives a small tolerance to shifts: a pixel that moves inside its window leaves the output unchanged, while a pixel that crosses a window border changes it. Shifting by the stride moves the output by one cell.
  • In the backward pass max pooling sends the whole upstream gradient to the cell that held the maximum and 0 to the others. Average pooling sends 1/k21/k^2 of it to every cell of the window. Global average pooling averages each channel over the whole map, giving one number per channel.
  • A strided convolution can replace pooling. With all weights equal to 1/41/4 a 2×22\times2 convolution with stride 2 is average pooling, and with learned weights it learns its own downsampling at the price of parameters.
  • The receptive field of a neuron is the part of the input that can change it. Through a stack it grows by (kℓ−1) jℓ−1(k_\ell-1)\,j_{\ell-1} at layer ℓ\ell, where the jump jℓ=jℓ−1sℓj_\ell=j_{\ell-1}s_\ell is the number of input pixels between two neighbours of layer ℓ\ell. Strides and pooling raise the jump, so the field grows faster. Two 3×33\times3 layers see 5×55\times5 with fewer weights than one 5×55\times5 layer. The effective receptive field is smaller than the theoretical one.
Found a mistake? Tell us