Implement average pooling forward and backward with overlapping windows

Why it matters Average pooling and its gradient appear in classic CNNs and in global pooling heads.

Average pooling spreads its gradient evenly over each window. When windows overlap, those shares add up.

Write avgpool2d(x, k, s, dy). x is (H, W), the window is k x k and the stride is s (no padding). Output size Ho = (H - k) // s + 1, the same for Wo. Return (y, dx): y[i, j] is the mean of x[i*s : i*s + k, j*s : j*s + k], and dx (same shape as x) is the gradient given upstream dy of shape (Ho, Wo).

Signaturedef avgpool2d(x, k, s, dy)

Example

x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]], k = 2, s = 1, dy = ones((2, 2)) gives y [[3, 4], [6, 7]] and dx [[0.25, 0.5, 0.25], [0.5, 1, 0.5], [0.25, 0.5, 0.25]].

Understand the idea

Average pooling summarises each window by its mean. Every input in the window had an equal vote, so in the backward pass each one gets an equal share of the blame. If a pixel belongs to several windows, it collects a share from each, like a person in two committees getting feedback from both.

Tiny example: 3 x 3 input, 2 x 2 windows, stride 1, dy = 1 everywhere. Each window passes 1/4 to its four cells. The centre is in all four windows: 4 * 0.25 = 1. Corners are in one window: 0.25. Edges are in two: 0.5.

Rules: y[i, j] = mean(window(i, j)); dx[window(i, j)] += dy[i, j] / k^2.

Average and global average pooling are used in ResNet heads and in many lightweight CNNs.

Shapes and data flow

x (H,W) -> y (Ho,Wo); dy (Ho,Wo) -> dx (H,W)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: exampleavgpool2d([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]], 2, 1, np.ones((2, 2)))
  • Sample 2: non-overlapavgpool2d(np.arange(16, dtype=float).reshape(4, 4), 2, 2, [[1.0, 2.0], [3.0, 4.0]])