6.5  Pooling

Convolutional layers answer local questions (whether an edge sits at pixel \((i, j)\)), whereas a classifier must answer a global question about the whole image. Bridging from local feature maps to a global prediction requires both wide spatial reach (Section 6.3.2.2) and robustness to tiny spatial shifts so a one-pixel camera jitter does not alter the prediction.

A pooling layer serves both goals without adding learnable parameters: it slides a window across each channel independently and summarizes every patch by its maximum or average. Because the maximum over a small block stays unchanged as long as the peak response remains inside that block, local pooling provides tolerance to small shifts, while global pooling across the entire feature map collapses spatial coordinates into a single channel-wise vector.

from functools import partial
from functools import partial

6.5.1 Maximum Pooling and Average Pooling

Like a convolutional layer, a pooling operator slides a fixed-shape window (the pooling window) across its input and computes a single scalar output at each position. Unlike a convolution, however, a pooling layer has no learnable kernel weights: it applies a fixed deterministic reduction to the elements inside the window. Maximum pooling (max-pooling for short) returns the largest entry in the window, whereas average pooling returns their arithmetic mean.

Figure 6.5.1: Max-pooling with a pooling window shape of \(2\times 2\). The shaded portions are the first output element as well as the input tensor elements used for the output computation: \(\max(0, 1, 3, 4)=4\).

In Figure 6.5.1, a \(2\times2\) window slides across a \(3\times3\) input with stride 1, moving from left to right and top to bottom. Because the window fits in two positions along each axis, the output has shape \(2\times2\), with entries given by the maximum of each window:

\[ \begin{aligned} \max(0, 1, 3, 4) &= 4,\\ \max(1, 2, 4, 5) &= 5,\\ \max(3, 4, 6, 7) &= 7,\\ \max(4, 5, 7, 8) &= 8. \end{aligned} \]

Notice that five of the nine input entries (0, 1, 2, 3, and 6) are never the maximum of any window. Perturbing them slightly leaves the output completely unchanged, because max-pooling depends only on the winning element in each window. The same sliding-window construction generalizes immediately to any \(k_\textrm{h} \times k_\textrm{w}\) pooling window.

Below we implement forward propagation for two-dimensional pooling in pool2d. Its nested loop mirrors corr2d from Section 6.2, replacing the weighted inner product with either max or mean. We also include a stride argument so we can examine downsampling next.

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
def pool2d(X, pool_size, mode='max', stride=1):
    k_h, k_w = pool_size
    reduce = tf.reduce_max if mode == 'max' else tf.reduce_mean
    # Build Y from its entries, so that gradients flow through it
    return tf.stack([
        tf.stack([reduce(X[i: i + k_h, j: j + k_w])
                  for j in range(0, X.shape[1] - k_w + 1, stride)])
        for i in range(0, X.shape[0] - k_h + 1, stride)])
def pool2d(X, pool_size, mode='max', stride=1):
    k_h, k_w = pool_size
    Y = jnp.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 = Y.at[i, j].set(window.max() if mode == 'max'
                               else window.mean())
    return Y
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

Testing pool2d on the \(3\times3\) tensor from Figure 6.5.1 confirms that max-pooling yields 4, 5, 7, and 8.

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.]])
<tf.Tensor: shape=(2, 2), dtype=float32, numpy=
array([[4., 5.],
       [7., 8.]], dtype=float32)>
Array([[4., 5.],
       [7., 8.]], dtype=float32)
array([[4., 5.],
       [7., 8.]])

Switching to average pooling on the same input returns the four window means: 2, 3, 5, and 6.

pool2d(X, (2, 2), 'avg')
tensor([[2., 3.],
        [5., 6.]])
<tf.Tensor: shape=(2, 2), dtype=float32, numpy=
array([[2., 3.],
       [5., 6.]], dtype=float32)>
Array([[2., 3.],
       [5., 6.]], dtype=float32)
array([[2., 3.],
       [5., 6.]])

6.5.2 Tolerance to Small Shifts

Just how much spatial shift can pooling absorb? Let us test the simplest possible setting. A \(2\times2\) pooling layer with stride 2 partitions its input into non-overlapping \(2\times2\) blocks and summarizes each block by a single value. Imagine a \(4\times4\) feature map containing a single nonzero response of 1 (like an edge detector firing at an isolated edge), and slide that response one pixel at a time across row 1. Below we compare the max-pooled and average-pooled outputs across three consecutive column positions.

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]]

Shifting the response from column 0 to column 1 leaves both pooled outputs completely unchanged because both locations fall inside the same \(2\times2\) block. Shifting it one pixel further to column 2 crosses a block boundary, causing the pooled response to jump to the adjacent output cell. Thus, a one-pixel horizontal shift is absorbed whenever the response remains within its block (half of all starting columns) and shifts the output by one position otherwise. Local pooling therefore makes a representation tolerant to certain small shifts, not strictly invariant to them. Figure 6.5.2 illustrates the max-pooled outputs across all four column positions.

Figure 6.5.2: A single response moved through the four columns of a \(4\times4\) feature map (top), its \(2\times2\) max-pooled map with stride 2 (middle), and its global maximum (bottom). Heavy lines mark the pooling blocks. The pooled response stays put while the response stays inside its block and jumps when it crosses into the next one; the global maximum never moves.

Notice also how max-pooling and average pooling summarize the block differently. Max-pooling preserves the full strength of the activation (1) anywhere inside the block, effectively asking whether the feature appears somewhere in that neighborhood. Average pooling outputs 0.25 because the feature occupies only one of the four cells, measuring the feature’s spatial coverage and diluting a strong isolated response with its zero neighbors.

Subsampling with stride 2 also introduces a subtle signal-processing hazard whenever a feature crosses a sampling boundary. In the extreme case, taking every second sample of a high-frequency alternating signal \(1, 0, 1, 0, \ldots\) produces either all ones or all zeros depending on a single-pixel shift. This distortion, occurring whenever a signal varies faster than the sampling rate can resolve, is called aliasing, and it affects every stride-2 downsampler, whether pooled or convolutional. Applying a small smoothing filter before subsampling mitigates aliasing (Zhang 2019), a technique explored in the exercises below.

Historically, shift tolerance was the primary motivation behind pooling. Fukushima’s Neocognitron (Fukushima 1980) paired each layer of feature-detecting cells with pooling-like cells that fired whenever a feature appeared anywhere in a local neighborhood. An early version of max-pooling appeared in speech recognition (Yamaguchi et al. 1990), and max-pooling was subsequently proposed in computational neuroscience as a model of hierarchical evidence aggregation in the visual cortex (Riesenhuber and Poggio 1999).

6.5.3 Global Pooling

What about the full translation invariance we desired in Section 6.1 when asking whether Waldo appears anywhere in an image? As we just saw, a small fixed window cannot guarantee it. Expanding the pooling window to cover the entire spatial extent of each feature map can: the maximum or mean over all spatial positions yields the exact same scalar regardless of where the response sits (bottom row of Figure 6.5.2). This operation is called global pooling, and it collapses each channel to a single number.

Inside a full CNN, however, global pooling sits atop zero-padded convolutional layers, which are strictly shift-equivariant only away from the image borders (Section 6.1). As we saw in Section 6.3.1.3, an interior pixel participates in all nine windows of a \(3 \times 3\) kernel whereas a border pixel participates in only six (and a corner pixel in four), so while a global maximum over an isolated response stays constant across columns, a global average drops when a feature moves onto the padded border. Stride-1 convolutional stacks ending in global pooling are therefore strictly invariant to shifts that keep salient content away from the boundaries, and approximately invariant otherwise. Strided layers weaken this guarantee: because of the aliasing we met above, the invariance is then exact only for shifts by a multiple of the product of the strides.

In the modern architectures of Chapter 7, the two roles of pooling are frequently separated. Intermediate spatial downsampling is often handled by stride-2 convolutions, which learn how to weight each window rather than committing to a fixed maximum or average, while the network terminates in global average pooling (Lin et al. 2013) before the final linear classifier. LeNet, the classic architecture we build in the next section, predates both conventions.

6.5.4 Padding and Stride

Because pooling slides a window over spatial grids in exactly the same way as convolution, deep learning frameworks parameterize pooling layers with the same window shape, padding, and stride arguments, and the output shape obeys the identical formula from Section 6.3: padding \(p\) pixels on each side of an axis of length \(n\) with window size \(k\) and stride \(s\) yields \(\lfloor(n+2p-k)/s\rfloor+1\) outputs along that axis. The one subtle difference is what value fills the padded border. To demonstrate these behaviors with built-in pooling layers, we first construct a four-dimensional tensor holding a single \(4\times4\) feature map with entries 0 through 15.

# (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.]]]])
# (example, height, width, channel), as in the previous sections
X = d2l.reshape(d2l.arange(16, dtype=d2l.float32), (1, 4, 4, 1))
X
<tf.Tensor: shape=(1, 4, 4, 1), dtype=float32, numpy=
array([[[[ 0.],
         [ 1.],
         [ 2.],
         [ 3.]],

        [[ 4.],
         [ 5.],
         [ 6.],
         [ 7.]],

        [[ 8.],
         [ 9.],
         [10.],
         [11.]],

        [[12.],
         [13.],
         [14.],
         [15.]]]], dtype=float32)>
# (example, height, width, channel), as in the previous sections
X = d2l.reshape(d2l.arange(16, dtype=d2l.float32), (1, 4, 4, 1))
X
Array([[[[ 0.],
         [ 1.],
         [ 2.],
         [ 3.]],

        [[ 4.],
         [ 5.],
         [ 6.],
         [ 7.]],

        [[ 8.],
         [ 9.],
         [10.],
         [11.]],

        [[12.],
         [13.],
         [14.],
         [15.]]]], dtype=float32)
# (example, channel, height, width)
X = d2l.reshape(d2l.arange(16, dtype=d2l.float32), (1, 1, 4, 4))
X
array([[[[ 0.,  1.,  2.,  3.],
         [ 4.,  5.,  6.,  7.],
         [ 8.,  9., 10., 11.],
         [12., 13., 14., 15.]]]])

Because pooling is usually used to summarize non-overlapping regions, most frameworks default to setting the stride equal to the pooling window size so the windows tile the input without overlap. On our \(4\times4\) input, a \(3\times3\) window with stride 3 fits only once, returning the maximum of the upper-left \(3\times3\) block (10). Since pooling has no learnable weights, the layer requires no parameter initialization.

The function nnx.max_pool, however, defaults to stride 1, so we pass strides explicitly.

pool = nn.MaxPool2d(3)  # The stride defaults to the window shape
pool(X)
tensor([[[[10.]]]])
pool = tf.keras.layers.MaxPool2D(3)  # The stride defaults to the window
pool(X)
<tf.Tensor: shape=(1, 1, 1, 1), dtype=float32, numpy=array([[[[10.]]]], dtype=float32)>
# The stride of nnx.max_pool defaults to 1, so we set it to the window shape
nnx.max_pool(X, window_shape=(3, 3), strides=(3, 3))
Array([[[[10.]]]], dtype=float32)
pool = nn.MaxPool2D(3)  # The stride defaults to the window shape
pool(X)
array([[[[10.]]]])

We can override these defaults whenever we want overlapping windows or explicit padding. Setting padding to 1 and stride to 2 produces an output of size \(\lfloor(4+2-3)/2\rfloor+1 = 2\) along both height and width.

pool = nn.MaxPool2d(3, padding=1, stride=2)
pool(X)
tensor([[[[ 5.,  7.],
          [13., 15.]]]])
# Keras pooling layers pad only 'valid' or 'same'; tf.nn.max_pool2d takes
# the padding of each axis explicitly
pool = partial(tf.nn.max_pool2d, ksize=3, strides=2,
               padding=[[0, 0], [1, 1], [1, 1], [0, 0]])
pool(X)
<tf.Tensor: shape=(1, 2, 2, 1), dtype=float32, numpy=
array([[[[ 5.],
         [ 7.]],

        [[13.],
         [15.]]]], dtype=float32)>
# One (before, after) pair of padding for each spatial axis
pool = partial(nnx.max_pool, window_shape=(3, 3), strides=(2, 2),
               padding=((1, 1), (1, 1)))
pool(X)
Array([[[[ 5.],
         [ 7.]],

        [[13.],
         [15.]]]], dtype=float32)
pool = nn.MaxPool2D(3, padding=1, strides=2)
pool(X)
array([[[[ 5.,  7.],
         [13., 15.]]]])

What value should fill the padded border of a pooling layer? In a convolution, zero is the natural neutral element because multiplying by zero contributes nothing to a weighted sum. For max-pooling, however, the neutral element is \(-\infty\): padded cells can never beat a real activation, ensuring every output equals the maximum over the genuine input entries inside its window. In our example above, the windows cover real rows and columns \(\{0, 1\}\) and \(\{1, 2, 3\}\), yielding 5, 7, 13, and 15. Padding with \(-\infty\) also preserves shift equivariance in value: adding a constant to every input entry shifts every pooled output by the exact same constant. We can verify this on X - 16, whose entries are all strictly negative.

pool(X - 16)
tensor([[[[-11.,  -9.],
          [ -3.,  -1.]]]])
<tf.Tensor: shape=(1, 2, 2, 1), dtype=float32, numpy=
array([[[[-11.],
         [ -9.]],

        [[ -3.],
         [ -1.]]]], dtype=float32)>
Array([[[[-11.],
         [ -9.]],

        [[ -3.],
         [ -1.]]]], dtype=float32)
array([[[[-11.,  -9.],
         [ -3.,  -1.]]]])

Every output decreases by exactly 16, as expected. Had the layer padded with zeros instead, the three windows touching the border would have returned 0, corrupting the result simply because 0 happens to be larger than all negative inputs.

Average pooling has no analogous neutral constant. Including padded zeros in the denominator biases border averages toward 0; the cleaner alternative is to divide only by the count of real input entries falling inside each window.

Average pooling here counts the padded zeros by default (count_include_pad=True); count_include_pad=False averages only the real entries.

tf.keras.layers.AvgPool2D with padding='same' averages only the real entries under each window.

Average pooling here counts the padded zeros by default (count_include_pad=True); count_include_pad=False averages only the real entries.

Average pooling here counts the padded zeros by default (count_include_pad=True); count_include_pad=False averages only the real entries.

6.5.5 Multiple Channels

Whereas a convolutional layer mixes information across all input channels by summing over them (Section 6.4), a pooling layer operates independently on each channel. Consequently, the output always has the exact same number of channels as the input. To verify this behavior, we concatenate X and X + 1 along the channel axis to create a two-channel tensor.

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.]]]])
X = d2l.concat([X, X + 1], 3)  # the channel axis is last
X
<tf.Tensor: shape=(1, 4, 4, 2), dtype=float32, numpy=
array([[[[ 0.,  1.],
         [ 1.,  2.],
         [ 2.,  3.],
         [ 3.,  4.]],

        [[ 4.,  5.],
         [ 5.,  6.],
         [ 6.,  7.],
         [ 7.,  8.]],

        [[ 8.,  9.],
         [ 9., 10.],
         [10., 11.],
         [11., 12.]],

        [[12., 13.],
         [13., 14.],
         [14., 15.],
         [15., 16.]]]], dtype=float32)>
X = d2l.concat([X, X + 1], 3)  # the channel axis is last
X
Array([[[[ 0.,  1.],
         [ 1.,  2.],
         [ 2.,  3.],
         [ 3.,  4.]],

        [[ 4.,  5.],
         [ 5.,  6.],
         [ 6.,  7.],
         [ 7.,  8.]],

        [[ 8.,  9.],
         [ 9., 10.],
         [10., 11.],
         [11., 12.]],

        [[12., 13.],
         [13., 14.],
         [14., 15.],
         [15., 16.]]]], dtype=float32)
X = d2l.concat((X, X + 1), 1)
X
array([[[[ 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.]]]])

Applying our earlier pooling operation (padding 1, stride 2) yields two output channels: the first reproduces 5, 7, 13, and 15, while the second returns the same values incremented by 1.

pool(X)
tensor([[[[ 5.,  7.],
          [13., 15.]],

         [[ 6.,  8.],
          [14., 16.]]]])
<tf.Tensor: shape=(1, 2, 2, 2), dtype=float32, numpy=
array([[[[ 5.,  6.],
         [ 7.,  8.]],

        [[13., 14.],
         [15., 16.]]]], dtype=float32)>
Array([[[[ 5.,  6.],
         [ 7.,  8.]],

        [[13., 14.],
         [15., 16.]]]], dtype=float32)
array([[[[ 5.,  7.],
         [13., 15.]],

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

The result is in the channels-last layout, so the two channels appear side by side in the last axis.

The result is in the channels-last layout, so the two channels appear side by side in the last axis.

Because pooling has no learnable weights, it discovers no patterns on its own; it can only summarize the features detected by preceding convolutional layers. With convolutions, padding, stride, dilation, multi-channel feature maps, and pooling all in hand, we now have every building block needed to assemble and train a complete convolutional neural network and compare it directly against our earlier MLPs.

6.5.6 Summary

Pooling layers summarize each spatial window of an input feature map by its maximum or average. They introduce zero learnable parameters, process each channel independently, and follow the exact same padding and stride output-shape rules as convolutions; max-pooling pads borders with \(-\infty\) so that padded positions never affect the maximum. A \(2\times2\) pooling layer with stride 2 halves spatial resolution along each axis and absorbs small shifts that stay within a block, while still jumping when a response crosses a block boundary. Max-pooling preserves the peak activation in a neighborhood, whereas average pooling dilutes isolated peaks across the window. Finally, global pooling collapses each entire feature map to a single scalar. On top of stride-1 layers this yields full translation invariance for interior patterns (and approximate invariance near padded borders); with strided layers the invariance is exact only for shifts by a multiple of the product of the strides.

6.5.7 Exercises

  1. Pooling alternatives.

    1. Do we need a separate minimum-pooling layer, or can it be expressed through an operation already in this section?
    2. Softmax pooling with temperature \(\tau > 0\) replaces the window entries \(x_1, \ldots, x_m\) by their softmax-weighted average \[\sum_{i=1}^m x_i \frac{\exp(x_i / \tau)}{\sum_{j=1}^m \exp(x_j / \tau)}. \tag{6.5.1}\] Find its limits as \(\tau \to 0\) and as \(\tau \to \infty\). Give one cost that softmax pooling adds relative to max-pooling.
  2. Aliasing and blur-pool. Naive stride-2 downsampling keeps every second entry of its input. Measure frequency in cycles per input sample, so that the one-dimensional signals \((1, 0, 1, 0, 1, 0)\) and \((0, 1, 0, 1, 0, 1)\) both have frequency \(\tfrac{1}{2}\).

    1. Apply naive stride-2 downsampling to both signals, which differ by a shift of one position, and compare the two outputs. Why is this behavior called aliasing?
    2. Which input frequencies can a stride-2 subsampler represent faithfully?
    3. Blur-pool (Zhang 2019) counteracts aliasing by applying a small averaging filter before subsampling. Work out what blur-pool with a two-tap box filter \((\tfrac{1}{2}, \tfrac{1}{2})\) computes on the two signals above. Which pooling operation from this section does it coincide with?
  3. [code] Backward pass of max-pooling. Derive the gradient of two-dimensional max-pooling with respect to its input, for a \(k_\textrm{h} \times k_\textrm{w}\) window and stride equal to the window size, and implement it without automatic differentiation. Verify against the gradient that automatic differentiation computes through the built-in max-pooling operation of this section on a small random tensor, to a relative error below \(10^{-4}\).

    Adapted from Stanford CS231n, Assignment 2, ConvolutionalNetworks, naive max-pooling backward pass.

  4. Max-pooling via ReLU. ● A convolution is linear, so it cannot compute a maximum by itself.

    1. Express \(\max(a, b)\) using only affine operations and \(\textrm{ReLU}(x) = \max(0, x)\).
    2. Use this to implement max-pooling as a stack of convolutions and ReLU layers.
    3. Count the channels per layer and the ReLU layers that your construction uses for a \(2 \times 2\) window and for a \(3 \times 3\) window. How does the number of ReLU layers grow with the number of entries in the window?