Pooling, Stride and Receptive Fields
A 3 3 convolution sees nine pixels. A digit is 8 8, a face in a photo may be 200 200, and the classifier at the end of the network has to answer a question about the whole object. Something must make each unit see more of the image as you go deeper, and something must shrink the feature maps so the network stays affordable. Those are the jobs of stride, pooling and dilation; the quantity that measures their effect is the receptive field.
The derivations are in the Mathematics lessons padding and stride and pooling and receptive fields. This lesson turns them into code you can trust: an output-size function checked against a real convolution, pooling layers in NumPy, a receptive-field calculator checked against gradients in PyTorch, and the shapes of a small CNN printed layer by layer.
Output size
For an input of size (per spatial axis), kernel , stride , zero padding on each side and dilation :
This is the formula in the PyTorch documentation of nn.Conv2d and nn.MaxPool2d. Read it from the inside: a dilated kernel covers input pixels (its span), the padded input has , so the kernel fits in shifted positions beyond the first one, and stride keeps every -th of them. The floor means a stride that does not divide evenly silently drops the last rows and columns.
Three settings come up again and again: keeps the size ("same"); halves it (rounding up for odd ); a pool with stride 2 halves it (rounding down).
The function below implements the formula, and a loop-based convolution with stride, padding and dilation produces real outputs to compare with. Dilation reads every -th pixel under a kernel's span, so a 3 3 kernel with covers a 5 5 area with nine weights.
import numpy as np
def out_size(n, k, s=1, p=0, d=1):
return (n + 2 * p - d * (k - 1) - 1) // s + 1
def conv2d(x, w, s=1, p=0, d=1):
"""One channel, general stride s, zero padding p, dilation d (loops, for clarity)."""
x = np.pad(x, p)
k = w.shape[0]
span = d * (k - 1) + 1 # the kernel's footprint on the input
Ho = (x.shape[0] - span) // s + 1
Wo = (x.shape[1] - span) // s + 1
out = np.zeros((Ho, Wo))
for i in range(Ho):
for j in range(Wo):
patch = x[i * s:i * s + span:d, j * s:j * s + span:d] # every d-th pixel
out[i, j] = np.sum(patch * w)
return out
rng = np.random.default_rng(0)
x = rng.normal(size=(9, 9))
print(" k s p d formula actual")
for k, s, p, d in [(3, 1, 0, 1), (3, 1, 1, 1), (3, 2, 1, 1), (5, 2, 2, 1), (3, 1, 2, 2), (4, 3, 0, 1)]:
y = conv2d(x, rng.normal(size=(k, k)), s, p, d)
print(f"{k:2d} {s:2d} {p:2d} {d:2d} {out_size(9, k, s, p, d):5d} {y.shape[0]:5d}") k s p d formula actual
3 1 0 1 7 7
3 1 1 1 9 9
3 2 1 1 5 5
5 2 2 1 5 5
3 1 2 2 9 9
4 3 0 1 2 2
Every row agrees, including the last one where the stride does not fit: a 4-wide kernel with stride 3 on 9 pixels fits at positions 0 and 3, and position 6 would need pixels up to 9 (one past the end), so the output has 2 values and pixel 8 is never used.
Pooling
A pooling layer slides a window like a convolution, but applies a fixed function to it instead of learned weights: the maximum (max pooling) or the mean (average pooling). It acts on each channel separately and has no parameters. Global average pooling (GAP) averages each channel over the whole map, turning into numbers whatever and are.
import numpy as np
def pool2d(x, k=2, s=2, op=np.max):
"""x: (C, H, W). Max or average over each k x k window, stride s, no padding."""
C, H, W = x.shape
Ho, Wo = (H - k) // s + 1, (W - k) // s + 1
out = np.zeros((C, Ho, Wo))
for i in range(Ho):
for j in range(Wo):
out[:, i, j] = op(x[:, i * s:i * s + k, j * s:j * s + k], axis=(1, 2))
return out
x = np.array([[1, 3, 2, 0],
[4, 6, 1, 1],
[0, 2, 9, 5],
[1, 1, 3, 7]], dtype=float)[None] # one channel, 4 x 4
print("max pool 2x2:", pool2d(x).astype(int)[0].tolist())
print("avg pool 2x2:", pool2d(x, op=np.mean)[0].tolist())
print("global average:", float(x.mean(axis=(1, 2))[0]))
# Pooling has no parameters and works per channel; a shift of one pixel may not change it
y = np.zeros((1, 6, 6)); y[0, 2, 2] = 1.0
y_shift = np.zeros((1, 6, 6)); y_shift[0, 2, 3] = 1.0
print("max pool of a dot, then of the dot moved 1 px:",
pool2d(y)[0].astype(int).tolist() == pool2d(y_shift)[0].astype(int).tolist())
# Global average pooling turns any (C, H, W) map into C numbers
for H in (6, 11):
fmap = np.ones((64, H, H))
print(f"GAP of a (64, {H}, {H}) map ->", fmap.mean(axis=(1, 2)).shape)max pool 2x2: [[6, 2], [2, 9]]
avg pool 2x2: [[3.5, 1.0], [1.0, 6.0]]
global average: 2.875
max pool of a dot, then of the dot moved 1 px: True
GAP of a (64, 6, 6) map -> (64,)
GAP of a (64, 11, 11) map -> (64,)
The 4 4 example by hand: the top-left window holds 1, 3, 4, 6, so the max is 6 and the mean 3.5. Max pooling keeps "is the feature present in this region", average pooling "how much of it". Moving a single bright dot by one pixel inside the same window does not change the max-pooled map at all, which is the small amount of translation invariance pooling buys. GAP returns 64 numbers for a 6 6 and for an 11 11 map alike, which is why modern classifiers end with it instead of flattening a map of a fixed size.
Receptive field through a stack
The receptive field of a unit is the size of the input region that can affect it. Track it with the jump , the distance in input pixels between two neighbouring units of the current layer. Starting from , , each layer with kernel , stride and dilation updates
so a 3 3 convolution adds 2 pixels times the current jump. Stride (and pooling) multiply the jump, which makes every later layer grow the field faster. Dilation multiplies the growth of one layer without shrinking the map.
import numpy as np
# (name, kernel, stride, dilation) for a small CNN
layers = [("conv3", 3, 1, 1), ("conv3", 3, 1, 1), ("pool2", 2, 2, 1),
("conv3", 3, 1, 1), ("conv3", 3, 1, 1), ("pool2", 2, 2, 1),
("conv3", 3, 1, 1), ("conv3 d=2", 3, 1, 2)]
r, j = 1, 1 # receptive field and jump (input pixels between neighbouring outputs)
print("layer r jump")
for name, k, s, d in layers:
r = r + d * (k - 1) * j
j = j * s
print(f"{name:10s} {r:3d} {j:5d}")
# Without pooling: 8 stacked 3x3 convs grow r linearly
print("8 x conv3, stride 1:", 1 + 8 * 2)layer r jump
conv3 3 1
conv3 5 1
pool2 6 2
conv3 10 2
conv3 14 2
pool2 16 4
conv3 24 4
conv3 d=2 40 4
8 x conv3, stride 1: 17
Two convolutions see 5 pixels, the first pool doubles the jump, and from then on every 3 3 convolution adds 4 pixels, then 8 after the second pool. The dilated convolution at the end adds pixels in one layer, giving 40. Eight stride-1 convolutions without pooling would reach only 17.
Checking it with gradients
The receptive field has an empirical definition: the input pixels whose gradient with respect to one output unit is not zero. Build the same eight layers in PyTorch (average pooling, so every input in a window gets gradient; with max pooling only the maximum would), set all weights to 1 so nothing cancels, take one unit of the output and call backward(). The recorded run (CPU):
import torch
from torch import nn
torch.manual_seed(0)
def stack(): # the same 8 layers as the NumPy table
return nn.Sequential(
nn.Conv2d(1, 1, 3, padding=1), nn.Conv2d(1, 1, 3, padding=1), nn.AvgPool2d(2),
nn.Conv2d(1, 1, 3, padding=1), nn.Conv2d(1, 1, 3, padding=1), nn.AvgPool2d(2),
nn.Conv2d(1, 1, 3, padding=1), nn.Conv2d(1, 1, 3, padding=2, dilation=2))
def grad_map(net):
x = torch.randn(1, 1, 64, 64, requires_grad=True)
y = net(x) # (1, 1, 16, 16)
y[0, 0, 8, 8].backward() # one output unit near the centre
g = x.grad[0, 0].abs()
rows = torch.nonzero(g.sum(1)).flatten()
cols = torch.nonzero(g.sum(0)).flatten()
return g, rows, cols
# 1) positive weights, average pooling: every input in the receptive field gets a non-zero gradient
net = stack()
with torch.no_grad():
for m in net:
if isinstance(m, nn.Conv2d):
m.weight.fill_(1.0); m.bias.zero_()
g, rows, cols = grad_map(net)
print("output shape:", tuple(net(torch.zeros(1, 1, 64, 64)).shape))
print("empirical receptive field:", len(rows), "x", len(cols),
" rows", rows.min().item(), "to", rows.max().item())
# 2) random weights: the same footprint, but the gradient mass sits near the centre
net = stack()
g, rows, cols = grad_map(net)
c0, c1 = rows.min().item(), rows.max().item() + 1
mid = (c0 + c1) // 2
total = g.sum().item()
inner = g[mid - 7:mid + 7, mid - 7:mid + 7].sum().item()
print("random weights, footprint:", len(rows), "x", len(cols))
print(f"share of |gradient| in the central 14 x 14: {inner / total:.3f}")output shape: (1, 1, 16, 16)
empirical receptive field: 40 x 40 rows 14 to 53
random weights, footprint: 40 x 40
share of |gradient| in the central 14 x 14: 0.315
The non-zero gradient covers exactly 40 40 input pixels, the number the formula gave. With random weights the footprint is still 40 40, but the gradient is far from uniform: the central 14 14 pixels, about 12 % of the area, carry 31.5 % of the total gradient magnitude. This concentration is the effective receptive field: a unit "sees" its whole theoretical field, but the centre matters much more than the edges. When you design a network for objects of a certain size, aim for a theoretical receptive field comfortably larger than the object.
Shapes through a small CNN
The figure shows a typical small classifier for 32 32 RGB images, the kind of model the next lessons train. Shapes are channels height width for one image.
Printing the shape after every layer is the fastest way to find a shape bug, and it shows where the parameters live. Iterating over an nn.Sequential calls each layer in turn (for other models, use forward hooks, see custom layers and hooks).
import torch
from torch import nn
torch.manual_seed(0)
model = nn.Sequential(
nn.Conv2d(3, 16, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2), # 32 -> 32 -> 16
nn.Conv2d(16, 32, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2), # 16 -> 16 -> 8
nn.Conv2d(32, 64, 3, stride=2, padding=1), nn.ReLU(), # 8 -> 4 (strided conv)
nn.AdaptiveAvgPool2d(1), nn.Flatten(), # global average pooling
nn.Linear(64, 10))
x = torch.randn(8, 3, 32, 32) # a batch of 8 RGB images
print(f"{'layer':18s} {'output shape':18s} params")
print(f"{'input':18s} {tuple(x.shape)}")
for layer in model:
x = layer(x)
n = sum(p.numel() for p in layer.parameters())
print(f"{layer.__class__.__name__:18s} {str(tuple(x.shape)):18s} {n}")
print("total parameters:", sum(p.numel() for p in model.parameters()))
# Global average pooling makes the head independent of the input size
print("64 x 64 input ->", tuple(model(torch.randn(2, 3, 64, 64)).shape))
# ceil_mode and odd sizes
print("MaxPool2d(2) on 7 x 7:", tuple(nn.MaxPool2d(2)(torch.zeros(1, 1, 7, 7)).shape),
" ceil_mode=True:", tuple(nn.MaxPool2d(2, ceil_mode=True)(torch.zeros(1, 1, 7, 7)).shape))layer output shape params
input (8, 3, 32, 32)
Conv2d (8, 16, 32, 32) 448
ReLU (8, 16, 32, 32) 0
MaxPool2d (8, 16, 16, 16) 0
Conv2d (8, 32, 16, 16) 4640
ReLU (8, 32, 16, 16) 0
MaxPool2d (8, 32, 8, 8) 0
Conv2d (8, 64, 4, 4) 18496
ReLU (8, 64, 4, 4) 0
AdaptiveAvgPool2d (8, 64, 1, 1) 0
Flatten (8, 64) 0
Linear (8, 10) 650
total parameters: 24234
64 x 64 input -> (2, 10)
MaxPool2d(2) on 7 x 7: (1, 1, 3, 3) ceil_mode=True: (1, 1, 4, 4)
The parameters sit in the convolutions (448, 4640 and 18,496: each is ) and a 650-parameter head, 24,234 in total; ReLU and pooling have none. The stride-2 convolution halves 8 to 4 as the formula says (). Because of the global average pooling the same model accepts a 64 64 image and still returns 10 logits per image. With Flatten straight after the last convolution, the linear layer would need exactly inputs and any other image size would crash. The last line shows the rounding: a 2 2 pool on a 7 7 map gives 3 3 and drops the last row and column, unless ceil_mode=True keeps a partial window (4 4).
Stride-2 convolution or max pooling? Both halve the map. Pooling is free and fixed; a strided convolution learns how to downsample and costs parameters. Most networks since ResNet use strided convolutions inside the body and keep only one pooling step early on, plus GAP at the end (CNN architectures).
Pitfalls
- Odd sizes and the floor. Strides and pools drop pixels when the size is not divisible. In encoder-decoder models (U-Nets) the up-sampled map then is one pixel smaller than the skip connection; keep sizes divisible by or crop explicitly.
padding="same"with stride. PyTorch rejectspadding="same"for strided convolutions; compute the padding yourself ( for odd ).- Flatten before the head fixes the input size. Prefer
nn.AdaptiveAvgPool2d(1)+Flattenif the model may see other resolutions. - Theoretical vs effective receptive field. The formula gives an upper bound on what a unit can see; the gradient concentrates near the centre, so a network whose theoretical field just matches the object often still struggles.
- Max pooling and gradients. Only the maximum of each window receives gradient. Average pooling and strided convolutions spread it.
Practice
- Compute the output size of a 224 224 input after
Conv2d(3, 64, 7, stride=2, padding=3)and thenMaxPool2d(3, stride=2, padding=1)(the ResNet stem). - What is the receptive field after three 3 3 convolutions with stride 1? After the same three convolutions with stride 2 each?
- With dilation and , what padding keeps the size at stride 1?
- Change the
layerslist in the receptive-field example so the network reaches a receptive field of at least 64 without dilation. How many layers did you need?
Answer
- , then : the stem turns 224 into 56.
- Stride 1: . Stride 2: .
- : the span is , so needs (that is why the PyTorch example used
padding=2, dilation=2). - One way: replace the dilated layer by an ordinary
conv3(, jump 4), append a thirdpool2(, jump 8) and twoconv3layers (, then ): 11 layers. Any stack whose sum of reaches 63 works.
Test yourself
What is the output width of nn.Conv2d(1, 1, kernel_size=3, stride=2, padding=1) on a width of 15?
- 7
- 8
- 15
- 6
Why does adding nn.AdaptiveAvgPool2d(1) before the final nn.Linear let a CNN accept images of any size?
- It resizes the input image
- It averages each channel over the whole map, so the head always gets numbers
- It removes the batch axis
- It adds padding until the size is fixed
A network has conv3 (stride 1), max pool 2 (stride 2), conv3 (stride 1). What is the receptive field of one output unit?
- 7
- 8
- 10
- 5
In the gradient experiment with random weights, what did the central 14 14 pixels (about 12 % of the 40 40 field) carry?
- About 12 % of the gradient magnitude
- None of it
- 31.5 % of the gradient magnitude
- All of it