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).
def 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)