Convolution, pooling and optimizers in NumPy
The backward passes of convolution and max pooling, sensible weight initialisation, and SGD with momentum and Adam.
- Derive the backward pass of a convolution as another convolution
- Route max-pooling gradients to the winning positions
- Choose Xavier or He initialisation, and explain what momentum and Adam add
Lesson 3 used nn.Conv2d. 02_CNN writes it out. The forward pass is a cross-correlation: slide each kernel over the zero-padded input and take the sum of the element-wise products, plus a bias.
output_tensor[n, f, i, j] = np.sum(
input_tensor[n, :, i*sy : i*sy + kh, j*sx : j*sx + kw] * self.weights[f]
) + self.bias[f]
The backward pass is a convolution too
Each input pixel contributes to every output it was under, weighted by the kernel entry it met. Summing those contributions is a convolution (kernel flipped) of the upsampled error with the weights, and the weight gradient is a correlation of the padded input with the error:
return_tensor[batch, ch] += convolve2d(self.up_error_T[batch, kernel], self.weights[kernel, ch], 'same')
self.gradient_weights[kernel, c] += correlate2d(self.de_padded[batch, c], self.up_error_T[batch, kernel], 'valid')
Strides are handled by scattering the error into a zero tensor of input size first (up_error_T), so one code path serves every stride.
A numerical gradient check of this layer is reassuring for odd kernels — 3×3 with stride 1 and stride 2 both agree to about \(10^{-8}\) — and finds a bug for even ones. With a 4×4 kernel the weight gradient is still right, but the gradient passed back to the input is off by up to 7.2. For even sizes, “same” padding cannot be symmetric: the forward pass puts the extra row and column on one side, while convolve2d(..., 'same') centres the kernel the other way. Rolling the returned gradient by one pixel up and one pixel left makes it match the numerical one to \(10^{-8}\) everywhere away from the border, so the input gradient is simply shifted by one pixel diagonally. Odd kernels — almost all of practice — are unaffected.
Max pooling
Pooling has no weights; its backward pass is pure bookkeeping. The forward pass records where each maximum was (x_s, y_s), and the backward pass returns each gradient to that position only:
return_tensor[a, b, i*sy + self.x_s[a, b, i, j], j*sx + self.y_s[a, b, i, j]] += error_tensor[a, b, i, j]
The += matters: with overlapping windows one input can be the maximum of two windows and must collect both gradients.
Initialisation
Initializers.py provides the two standard choices. Xavier draws weights with variance \(2 / (n_{\text{in}} + n_{\text{out}})\), keeping activations the same size through tanh or sigmoid layers. He uses \(2 / n_{\text{in}}\): ReLU zeros half its inputs, so the weights must be \(\sqrt{2}\) larger to compensate. The default UniformRandom — all weights in \([0, 1)\), all positive — is what lesson 10’s network started with; it works for tiny models and stalls deep ones.
Momentum and Adam
Plain SGD steps by \(-\eta\, g\). Momentum keeps a running velocity, \(v \leftarrow \mu v + \eta g\), so steps grow along directions where the gradient keeps its sign and cancel where it oscillates. Adam keeps running averages of \(g\) and \(g^2\), corrects their start-up bias by dividing by \(1 - \beta^k\), and steps by \(\eta\, \hat{v} / (\sqrt{\hat{r}} + \varepsilon)\) — every parameter gets its own effective step size. The repository’s Adam is exactly this, with \(\beta_1\) and \(\beta_2\) named mu and rho.
Because both optimizers keep state, weights and bias need separate optimizer objects; this version of FullyConnected makes them with copy.deepcopy, and sums the bias gradient over the batch — the two fixes the previous lesson called for.
Try it yourself. Reproduce the gradient check: build Conv((1, 1), (2, 4, 4), 3), compare backward’s output with central differences, and confirm the mismatch. Then change the forward padding so that the extra row and column sit on the side convolve2d expects, and make the check pass for both 3×3 and 4×4.