Pooling: values, boundaries and backward routes
池化
Compute max and mean pooling with explicit padding divisors, overlapping gradients and a declared tie policy.
poolingSummarize a neighborhood, lose some detail
A maximum says whether a large activation is present in a window. An average describes its overall level. Neither retains the entire pattern: (1,3) and (3,1) have the same maximum and average. Pooling trades spatial detail for a local summary, and a stride greater than one can also reduce the number of output positions.
Deep Learning, Section 9.3 describes local pooling and its motivation. The fixed PyTorch 2.8 AvgPool 2d and MaxPool 2d documents specify choices that affect actual values: padding, stride, rounding and the average divisor. We use a complete one-dimensional example so every forward value and backward contribution can be inspected.
A window and a reduction are separate choices
Let Wₜ be the observed input indices in window t. For average pooling, let dₜ be either the full padded window width or the number of observed entries, according to policy. Zero padding contributes zero to the numerator. Then:
Max pooling treats missing padded positions as negative infinity in the cited API, so they cannot beat a finite observed value. Padding with zero instead would produce a different maximum when all observed values are negative. Our implementation simply omits padded candidates, which is equivalent for finite inputs and nonempty observed windows.
For input length N, kernel width k, stride s, symmetric padding p and floor rounding, the output count is:
This formula has no dilation and assumes a positive output count. A stride of one need not downsample. The fixed APIs also offer ceiling behavior; we do not implement it. Changing rounding can create additional boundary windows and requires the documented rule about windows that start in right padding.
Backward values accumulate where windows overlap
Let uₜ be the derivative arriving from output t. Define aₜᵢ as 1/dₜ for an observed average-pooling entry, or one at the selected maximum and zero elsewhere for max pooling. Then:
At a unique maximum, the max derivative routes to that input. At a tie, max is not differentiable; a rule choosing one maximizing coordinate is a valid local subgradient of the max operation. Our program deterministically chooses the first valid maximum. This declares our tie policy, not a promise that every framework/device uses the same policy.
With input (1,3,3,0), k=2 and stride 1, max outputs are (3,3,3). The first-max rule routes the derivative of their sum to (0,2,1,0). Average outputs are (2,3,3/2), and their summed derivative is (1/2,1,1,1/2). The interior inputs belong to two windows; assigning rather than adding their contributions would be wrong.
Boundary averages depend on the divisor
For input (2,4), k=3, stride 1 and padding 1, both windows contain the two observed values plus one padded zero. Including padding gives outputs (2,2); excluding it gives (3,3). With upstream ones, gradients are (2/3,2/3) and (1,1), respectively. A divisor policy therefore changes both the forward result and training signal.
Keep the routes used by the forward pass
The complete Python 3.12 program uses exact fractions. It computes each reduction, saves the route to its contributing inputs, and accumulates supplied upstream derivatives. If none are supplied, it computes the derivative of the sum of outputs. Inputs and geometry are bounded; padding is limited to half the kernel width, and empty output windows are rejected.
from fractions import Fraction as F
def scalar(x):
if type(x) not in (int,F) or abs(x)>32:raise ValueError('bounded rational required')
return F(x)
def pool(values,kernel,stride,pad=0,mode='max',include_pad=True,upstream=None):
x=[scalar(v) for v in values];n=len(x)
if not 1<=n<=32 or any(type(v) is not int for v in (kernel,stride,pad)):raise ValueError('bounded input and integer geometry required')
if not 1<=kernel<=8 or not 1<=stride<=8 or not 0<=pad<=kernel//2:raise ValueError('invalid bounded geometry')
if mode not in ('max','mean') or type(include_pad) is not bool:raise ValueError('invalid mode or padding policy')
count=1+(n+2*pad-kernel)//stride
if count<1:raise ValueError('no output windows')
seeds=[F(1)]*count if upstream is None else [scalar(v) for v in upstream]
if len(seeds)!=count:raise ValueError('upstream length mismatch')
output=[];gradient=[F(0)]*n;routes=[]
for t in range(count):
valid=[i for i in range(t*stride-pad,t*stride-pad+kernel) if 0<=i<n]
if not valid:raise ValueError('window has no observed values')
if mode=='max':
winner=max(valid,key=lambda i:x[i]) # First valid maximum wins ties.
output.append(x[winner]);route=[(winner,F(1))]
else:
divisor=kernel if include_pad else len(valid)
output.append(sum((x[i] for i in valid),F(0))/divisor)
route=[(i,F(1,divisor)) for i in valid]
for i,weight in route:gradient[i]+=seeds[t]*weight
routes.append(route)
return dict(output=output,gradient=gradient,routes=routes)
if __name__=='__main__':
for mode in ('max','mean'):
r=pool([1,3,3,0],2,1,mode=mode)
print(mode,'output:',[str(v) for v in r['output']],'gradient of sum:',[str(v) for v in r['gradient']])
for include in (True,False):
r=pool([2,4],3,1,1,'mean',include)
print('include padding:',include,'output:',[str(v) for v in r['output']],'gradient:',[str(v) for v in r['gradient']])
print('negative max boundary:',pool([-4,-2],3,1,1)['output'])
print('one-pixel shift:',pool([0,1,0,0],2,2)['output'],pool([0,0,1,0],2,2)['output'])
Actual output:
max output: ['3', '3', '3'] gradient of sum: ['0', '2', '1', '0']
mean output: ['2', '3', '3/2'] gradient of sum: ['1/2', '1', '1', '1/2']
include padding: True output: ['2', '2'] gradient: ['2/3', '2/3']
include padding: False output: ['3', '3'] gradient: ['1', '1']
negative max boundary: [Fraction(-2, 1), Fraction(-2, 1)]
one-pixel shift: [Fraction(1, 1), Fraction(0, 1)] [Fraction(0, 1), Fraction(1, 1)]
Tests check the literal overlap and boundary results. They compare both mean and unique-maximum derivatives against finite differences with nonuniform upstream values; the separate tie test checks the declared deterministic policy instead of applying a differentiability test at a kink. Negative maxima, invalid geometry and mismatched upstream shapes are covered.
For m windows of width k, this transparent implementation uses O(mk) work and route storage plus O(N) input-gradient storage. Max pooling can instead save one winner per window; average pooling can recompute its simple routes from geometry. Neither operation requires trainable weights in this example.
Local stability is not universal translation invariance
With k=2 and stride 2, input (0,1,0,0) yields max outputs (1,0). Shifting the spike one position right gives input (0,0,1,0) and outputs (0,1). A one-pixel translation crossed a window boundary. Pooling may suppress some within-window movement, but it does not guarantee that every small input translation leaves its output unchanged.
Pooling is usually many-to-one. Keeping maximum indices can help place retained values back into a larger grid, but cannot reconstruct all discarded values. Replacing pooling with a strided convolution changes the operation and adds learned parameters; it is an alternative to evaluate, not an exact inverse or universal improvement.
The max route depends on the current input. Mean routes are fixed for a fixed geometry and divisor. NaNs, infinities, dilation, adaptive output sizes and framework-specific ceiling rules require separate contracts; this finite one-dimensional program does not implement them. Nor does a correct small pooling operation establish model-level accuracy or robustness.
Where does each gradient go?
- With first-maximum ties, what is the summed max-pooling input gradient for (1,3,3,0)?
Answer 1: (0,2,1,0) for width 2, stride 1.
- What does the same overlap pattern give under mean pooling?
Answer 2: (1/2,1,1,1/2).
- Why does padded input (2,4) yield either two or three as its boundary average?
Answer 3: Its numerator is six; the divisor is three when padding counts and two when it does not.
- Why is zero padding unsuitable as a max candidate for the negative-input example?
Answer 4: Zero would defeat the observed negative values, whereas negative-infinity padding should never win.
A pooling result needs its boundary policy
The textbook supplies the local-summary motivation. The fixed APIs supply the padding/divisor distinction and rounding options. Our windows, exact reverse routes, tie convention and translation counterexample are original. No library code, source figure or image-recognition experiment was reproduced.
Continue with receptive fields for how local windows change support, and convolution for a learned local operator. Record window size, stride, padding, rounding, divisor and tie policy when a precise reproduction needs them.
Make a prediction, then check
For input(2,4), width3 and padding1, what average results when padded zero counts?
Learning objectives
- Compute boundary-sensitive pooling values and overlapping gradients.
- Distinguish local summaries from guaranteed translation invariance.
Prerequisites & connections
Explore related knowledge →References
- Deep Learning — Chapter 9: Convolutional Networks
Ian Goodfellow; Yoshua Bengio; Aaron Courville · 2016 - AvgPool2d — PyTorch 2.8
PyTorch contributors - MaxPool2d — PyTorch 2.8
PyTorch contributors
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-06 · Codex single-agent authored technical review: cited primary-source scope, explicit assumptions, original calculations and counterexamples, runnable tests and bilingual review; not independent human or second-agent review.
- Single-agent authored technical review: bounded primary-source locations, assumptions, original derivations, exact/literal references and matching bilingual equations/examples/exercises. Not independent human or second-agent review.
- Four focused CPython3.12.4 tests passed per chapter. Shared gradients, embedding scatter-add, receptive-field geometry and pooling routes are checked against literal references, analytic identities and finite differences. All four examples use exact fractions from the standard library.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
Source locations checked:
- Deep Learning — Chapter 9: Convolutional Networks · Chapter9 Section9.3 printed335–337: pooling as a local summary and translation motivation; original boundary-shift counterexample qualifies invariance.
- AvgPool2d — PyTorch 2.8 · Fixed2.8 AvgPool2d signature/body: zero padding, count_include_pad, divisor_override, floor/ceil output and right-padding start rule; 1D floor-only original implementation.
- MaxPool2d — PyTorch 2.8 · Fixed2.8 MaxPool2d body: negative-infinity padding, stride/dilation/return_indices and ceil behavior; tie choice is our explicit policy, not an API guarantee.
Related topics