Implement the backward pass of a strided multi-channel conv2d
Why it matters Custom conv layers and conv kernels in research code need a correct backward, and interviewers ask for it.
Writing conv backward by hand shows that it is just the forward pass's patches, used in reverse.
Write conv2d_backward(x, w, dy, stride=1). The forward pass (no padding, no dilation) was out[o, i, j] = b[o] + sum over c, u, v of x[c, i * stride + u, j * stride + v] * w[o, c, u, v], with x (C_in, H, W) and w (C_out, C_in, k, k). Given dy of shape (C_out, Ho, Wo), return a dict with "dx" (same shape as x), "dw" (same shape as w) and "db" (C_out,).
def conv2d_backward(x, w, dy, stride=1)Example
x = [[[1, 2], [3, 4]]], w = [[[[1, 0], [0, 1]]]], dy = [[[1]]] gives dx [[[1, 0], [0, 1]]], dw [[[[1, 2], [3, 4]]]], db [1].
Understand the idea
In the forward pass each output value is a dot product between the kernel and one patch of the input. So in the backward pass each output's gradient flows to exactly two places: to the kernel, weighted by that patch, and to that patch, weighted by the kernel. Where patches overlap, the input gradients add up, like overlapping paint strokes.
Tiny example: input [[1, 2], [3, 4]], kernel [[1, 0], [0, 1]], one output, dy = 1. dw = dy * patch = [[1, 2], [3, 4]]. dx = dy * kernel = [[1, 0], [0, 1]]. db = 1.
Rules: db[o] = sum dy[o]; dw[o] += dy[o, i, j] * x_patch(i, j); dx_patch(i, j) += sum_o dy[o, i, j] * w[o].
Every CNN framework computes exactly these three gradients, usually rewritten as matrix multiplies through im2col.
Shapes and data flow
x (C_in,H,W); w (C_out,C_in,k,k); dy (C_out,Ho,Wo) -> dx, dw, db