Pooling

Dive into Deep Learning · §6.5

Pooling Layers
max & average pooling · local shift tolerance · aliasing · global pooling · padding with −∞

Why Equivariant Feature Maps Need Spatial Aggregation

Motivation & The Shift-Sensitivity Problem

  • Equivariance is pixel-sensitive: Shifting an input image by 1 pixel shifts every edge activation in every feature map by 1 pixel.
  • Tolerance & downsampling: Classifiers need local shift stability and progressive spatial coarsening.
  • Parameter-free pooling: Summarizes each k \times k patch per channel by its max or mean (0 learnable weights).

Maximum Pooling and Average Pooling

Deterministic Sliding-Window Reductions

A k_\textrm{h} \times k_\textrm{w} pooling window slides across the input grid exactly like corr2d, but applies a fixed reduction (max or mean) instead of a weighted inner product:

\begin{aligned} [\mathbf{Y}^{\textrm{max}}]_{i,j} &= \max_{0 \le a < k_\textrm{h},\, 0 \le b < k_\textrm{w}} [\mathbf{X}]_{i\cdot s + a,\, j\cdot s + b}, \\ [\mathbf{Y}^{\textrm{avg}}]_{i,j} &= \frac{1}{k_\textrm{h} k_\textrm{w}} \sum_{a=0}^{k_\textrm{h}-1} \sum_{b=0}^{k_\textrm{w}-1} [\mathbf{X}]_{i\cdot s + a,\, j\cdot s + b}. \end{aligned}

  • 2 \times 2 max-pooling (s=1) on 3 \times 3 input: \max(0,1,3,4) = 4, \max(1,2,4,5) = 5, \max(3,4,6,7) = 7, \max(4,5,7,8) = 8.
  • Gradient routing in backprop: Max-pooling routes 100% of the upstream gradient to the single winning entry in each window; average pooling splits it equally (1 / (k_\textrm{h} k_\textrm{w})).

Implementing 2D Pooling from Scratch

Replacing the Kernel Inner Product with Max or Mean

The function pool2d mirrors corr2d, stepping the top-left corner by stride and reducing each k_\textrm{h} \times k_\textrm{w} window with .max() or .mean():

def pool2d(X, pool_size, mode='max', stride=1):
    k_h, k_w = pool_size
    Y = d2l.zeros(((X.shape[0] - k_h) // stride + 1,
                   (X.shape[1] - k_w) // stride + 1))
    for i in range(Y.shape[0]):
        for j in range(Y.shape[1]):
            window = X[i * stride: i * stride + k_h,
                       j * stride: j * stride + k_w]
            Y[i, j] = window.max() if mode == 'max' else window.mean()
    return Y

Comparing Max-Pooling vs. Average Pooling Outputs

Peak Activation Preservation vs. Spatial Averaging

X = d2l.tensor([[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]])
pool2d(X, (2, 2))
tensor([[4., 5.],
        [7., 8.]])
pool2d(X, (2, 2), 'avg')
tensor([[2., 3.],
        [5., 6.]])

Testing Shift Tolerance on a Moving Impulse

How a 2×2 Stride-2 Pool Responds to 1-Pixel Shifts

def single_response(i, j, n=4):
    """An n x n feature map that is 1 at (i, j) and 0 elsewhere."""
    return d2l.tensor([[float(r == i and c == j) for c in range(n)]
                       for r in range(n)])

for j in range(3):
    Z = single_response(1, j)
    print(f'response at (1, {j}): max',
          d2l.numpy(pool2d(Z, (2, 2), stride=2)).tolist(),
          'avg', d2l.numpy(pool2d(Z, (2, 2), 'avg', stride=2)).tolist())
response at (1, 0): max [[1.0, 0.0], [0.0, 0.0]] avg [[0.25, 0.0], [0.0, 0.0]]
response at (1, 1): max [[1.0, 0.0], [0.0, 0.0]] avg [[0.25, 0.0], [0.0, 0.0]]
response at (1, 2): max [[0.0, 1.0], [0.0, 0.0]] avg [[0.0, 0.25], [0.0, 0.0]]
  • Within-block absorption (j=0 \to 1): Output is 100\% unchanged.
  • Cross-boundary jump (j=1 \to 2): Peak enters the right 2 \times 2 block.

Local Shift Tolerance vs. Global Invariance

Why Local Pooling Absorbs Half of 1-Pixel Shifts

Tracing the impulse across all four columns of the 4 \times 4 grid contrasts local 2 \times 2 stride-2 pooling (middle) against global pooling over the entire grid (bottom):

  • Local pooling (k \times k, stride k): Absorbs a 1-pixel horizontal shift whenever the peak does not sit in the rightmost column of its block—a fraction (k - 1)/k of starting columns (50\% for k = 2, 67\% for k = 3).
  • Max vs. average signal strength: Max-pooling preserves the full impulse amplitude (1.0) anywhere in the block (“Did the feature occur?”), whereas average pooling dilutes an isolated response by 1/k^2 = 0.25 (“What fraction of the block did it cover?”).

Signal-Processing Pitfall: Subsampling & Aliasing

Why Stride-2 Downsampling Can Flip High-Frequency Signals

  • Nyquist aliasing: On \mathbf{x} = (1,0,1,0,1,0), naive stride-2 subsampling outputs (1,1,1), whereas a 1-pixel shift T_1 \mathbf{x} = (0,1,0,1,0,1) flips the output to (0,0,0).
  • BlurPool fix (Zhang, 2019): Low-pass box filtering [\tfrac{1}{2}, \tfrac{1}{2}] before stride-2 subsampling (i.e., 2 \times 2 AvgPool) maps both to (0.5, 0.5, 0.5).

Global Pooling and Boundary Caveats

Collapsing Each Feature Map to a Single Scalar

  • Global pooling (H \times W \to 1 \times 1): Collapses each channel into a single scalar (c_\textrm{o}-vector), eliminating dense-head spatial weights.
  • Exact interior invariance: Global max is 1 regardless of impulse coordinate.
  • Zero-padded border caveat: Preceding padded convs sample interior pixels in 9 windows vs. 6 at edges (mean 9/16 vs. 6/16).

Built-In Pooling Layers: Default Non-Overlapping Stride

Framework Defaults and 4D Input Tensors

# (example, channel, height, width)
X = d2l.reshape(d2l.arange(16, dtype=d2l.float32), (1, 1, 4, 4))
X
tensor([[[[ 0.,  1.,  2.,  3.],
          [ 4.,  5.,  6.,  7.],
          [ 8.,  9., 10., 11.],
          [12., 13., 14., 15.]]]])
pool = nn.MaxPool2d(3)  # The stride defaults to the window shape
pool(X)
tensor([[[[10.]]]])

Custom Padding and Stride in Pooling Layers

Using the Exact Same Output-Shape Formula as Convolutions

Overriding the defaults with padding=1 and stride=2 on a 3 \times 3 window produces an output of size \lfloor (n + 2p - k)/s \rfloor + 1 = \lfloor (4 + 2 - 3)/2 \rfloor + 1 = 2 \times 2:

pool = nn.MaxPool2d(3, padding=1, stride=2)
pool(X)
tensor([[[[ 5.,  7.],
          [13., 15.]]]])

Systems Pitfall: Why Max-Pooling Pads Borders with −∞

Neutral Elements and Shift Equivariance in Activation Value

pool(X - 16)
tensor([[[[-11.,  -9.],
          [ -3.,  -1.]]]])
  • Neutral element -\infty: Ensures padded border cells never beat negative real activations (\max(\mathbf{X}-16) = \max(\mathbf{X})-16).
  • AvgPool option: Use count_include_pad=False to divide only by real pixel counts.

Channel Independence in Pooling Layers

One Spatial Reduction per Channel, Zero Cross-Channel Mixing

X = d2l.concat((X, X + 1), 1)
X
tensor([[[[ 0.,  1.,  2.,  3.],
          [ 4.,  5.,  6.,  7.],
          [ 8.,  9., 10., 11.],
          [12., 13., 14., 15.]],

         [[ 1.,  2.,  3.,  4.],
          [ 5.,  6.,  7.,  8.],
          [ 9., 10., 11., 12.],
          [13., 14., 15., 16.]]]])
pool(X)
tensor([[[[ 5.,  7.],
          [13., 15.]],

         [[ 6.,  8.],
          [14., 16.]]]])

Modern Evolution: Strided Convs & Global Avg Pool

How Contemporary Architectures Separate Downsampling from Invariance

  • Intermediate downsampling: Modern CNNs (ResNet, ConvNeXt) replace fixed local pooling between stages with stride-2 convolutions that learn downsampling weights.
  • Head aggregation: Global Average Pooling (c \times h \times w \to c) plus a single linear layer replaces multi-layer flattened dense heads, cutting >75\% of parameters.

Concept Check: Pooling Mechanics & Invariance

Concept Check

Test your understanding of pooling shapes, compute cost, and shift tolerance:

  1. LeNet first pooling layer: Takes a feature map of shape 6 \times 28 \times 28 and applies 2 \times 2 pooling with stride 2 and padding 0. What are the output shape, parameter count, and total number of pairwise comparisons (for max-pooling)?
  2. Shift-absorption probability: An isolated peak activation sits at a uniformly random pixel (i, j) in a large feature map and shifts by +1 row and +1 column (diagonally). What fraction of starting positions leave the output of a 3 \times 3, stride-3 max-pooling layer unchanged?
  3. Expressing min-pooling and softmax pooling: How can you compute minimum pooling \min_{x \in W} x using only max-pooling, and what do the temperature limits \tau \to 0^+ and \tau \to \infty of softmax pooling \sum_i x_i e^{x_i/\tau} / \sum_j e^{x_j/\tau} recover?

Answers: (1) Output shape: 6 \times 14 \times 14 (1{,}176 values). Parameters: 0. Comparisons: each 2 \times 2 window of 4 numbers takes 3 comparisons, giving 1{,}176 \times 3 = 3{,}528 comparisons (vs. 117{,}600 MACs in the preceding conv layer). (2) The peak stays inside its 3 \times 3 block iff its row is in \{0, 1\} \pmod 3 and its column is in \{0, 1\} \pmod 3, which occurs for (2/3) \times (2/3) = 4/9 \approx 44.4\% of positions. (3) \min(\mathbf{X}) = -\max(-\mathbf{X}). As \tau \to 0^+, softmax weights concentrate on the largest entry (max-pooling); as \tau \to \infty, all weights approach 1/m (average pooling).

Summary & Key Takeaways

Section Synthesis

Pooling Variant Window Reduction Padding Rule Parameters & Channel Rule Architectural Role
Max-Pooling (k \times k) \max_{(a,b) \in W} X_{i\cdot s+a, j\cdot s+b} Pads with -\infty 0 params; c_\textrm{o} = c_\textrm{i} (per-channel) Preserves peak feature activation; routes gradient to winner
Average Pooling (k \times k) \frac{1}{|W|}\sum_{(a,b) \in W} X_{i\cdot s+a, j\cdot s+b} Divide by real count (count_include_pad=False) 0 params; c_\textrm{o} = c_\textrm{i} (per-channel) Smooths high-frequency aliasing; measures area coverage
Local Stride-k Pool Non-overlapping k \times k tiles Output size \lfloor (n+2p-k)/k \rfloor + 1 Cuts spatial positions by k^2 Absorbs (k-1)/k of 1-pixel shifts per axis (local tolerance)
Global Pooling (H \times W) \max or \textrm{mean} over all (i,j) No padding needed Output shape (c_\textrm{i}, 1, 1) \to \mathbb{R}^{c_\textrm{i}} Replaces dense flatten head; invariant to interior shifts

Next (§6.6): We assemble convolutions, padding, multi-channel feature maps, and pooling into a complete end-to-end CNN—LeNet—and pit it against our MLP on ordered and pixel-shuffled Fashion-MNIST images.