Backpropagation Through Convolutions
A convolution is a linear map with shared weights, so its backward pass follows from two facts already in this course: the gradient with respect to the input is the transposed linear map applied to the upstream gradient, and the gradient of a shared weight is the sum of its gradients at every place it is used. Both turn out to be convolutions themselves.
The 1-D case
Forward (valid cross-correlation, kernel length ): . With upstream gradient :
The weight gradient sums over every position where was used (weight sharing = fan-out). The input gradient is for the Toeplitz matrix of Convolution as a Linear Operator: zero-pad by and cross-correlate with the flipped kernel.
import numpy as np
rng = np.random.default_rng(0)
x = rng.normal(size=8); w = rng.normal(size=3); g = rng.normal(size=6)
conv = lambda x, w: np.correlate(x, w, mode="valid")
L = lambda x, w: conv(x, w) @ g # a loss with upstream gradient g
dw = np.correlate(x, g, mode="valid") # weight gradient
dx = np.convolve(g, w, mode="full") # input gradient (flip + full padding)
num_w = np.array([(L(x, w + e) - L(x, w - e)) / 2e-6 for e in np.eye(3) * 1e-6])
num_x = np.array([(L(x + e, w) - L(x - e, w)) / 2e-6 for e in np.eye(8) * 1e-6])
print("dL/dw matches:", np.allclose(dw, num_w), " dL/dx matches:", np.allclose(dx, num_x))
print("dL/dw =", np.round(dw, 4))dL/dw matches: True dL/dx matches: True
dL/dw = [ 0.237 -1.8245 -2.0211]
Multi-channel 2-D layers
For (with the 2-D cross-correlation), the same pattern holds per channel pair:
summed over the batch as well. With stride , the input gradient is a transposed convolution with stride (Padding and Stride); equivalently, insert zeros between the entries of and proceed as above.
The im2col view
Implementations often unroll every receptive-field patch of the input into a column (im2col), turning the convolution into one matrix product . Then the backward pass is just the dense-layer rule: and , followed by "col2im", which adds the overlapping patches back into place.
import numpy as np
rng = np.random.default_rng(1)
X = rng.normal(size=(5, 5)); K = rng.normal(size=(3, 3)); G = rng.normal(size=(3, 3))
cols = np.stack([X[i:i + 3, j:j + 3].ravel() for i in range(3) for j in range(3)], axis=1) # (9, 9)
Y = (K.ravel() @ cols).reshape(3, 3)
dK = (G.ravel() @ cols.T).reshape(3, 3) # dense-layer rule
dcols = np.outer(K.ravel(), G.ravel()) # (9 patch entries, 9 positions)
dX = np.zeros_like(X)
for p, (i, j) in enumerate([(i, j) for i in range(3) for j in range(3)]):
dX[i:i + 3, j:j + 3] += dcols[:, p].reshape(3, 3) # col2im: overlapping patches add up
L = lambda X, K: np.sum((np.stack([X[i:i + 3, j:j + 3].ravel() for i in range(3) for j in range(3)], 1).T @ K.ravel()).reshape(3, 3) * G)
num = np.zeros_like(X)
for idx in np.ndindex(X.shape):
E = np.zeros_like(X); E[idx] = 1e-6; num[idx] = (L(X + E, K) - L(X - E, K)) / 2e-6
print("dX via col2im matches finite differences:", np.allclose(dX, num))
print("dK equals X correlated with G:", np.allclose(dK, np.array([[np.sum(X[u:u + 3, v:v + 3] * G) for v in range(3)] for u in range(3)])))dX via col2im matches finite differences: True
dK equals X correlated with G: True
Pooling and memory
Max pooling's backward pass routes each gradient to the stored argmax; average pooling spreads it evenly. Convolutional networks store large activation maps for these backward passes, so CNN training memory is dominated by the early, high-resolution layers.
In software
torch.nn.grad.conv2d_weightandconv2d_inputexpose the two backward convolutions directly.- cuDNN picks among direct, im2col (GEMM), FFT and Winograd algorithms for forward and backward separately.
- Gradient checks for conv layers are done on tiny inputs like the ones above.
Exercises
Exercise 1: Bias gradient
A conv layer's output for one channel is with all upstream gradients equal to , batch size 2. What is the bias gradient?
Answer
Solution
The bias is added to all outputs; .
Exercise 2: Weight gradient by hand
, kernel length 2, upstream gradient . Find .
Answer
.
Solution
; .
Exercise 3: Transpose check (code)
Build the Toeplitz matrix for a length-3 kernel on a length-6 input and verify that equals np.convolve(g, w, "full").
Answer
They are equal.
Solution
import numpy as np
w, g = np.array([1.0, 2.0, -1.0]), np.array([0.5, -1.0, 2.0, 1.0])
T = np.zeros((4, 6))
for i in range(4): T[i, i:i + 3] = w
print(np.allclose(T.T @ g, np.convolve(g, w, "full")))True
Test yourself
The gradient of a shared convolution weight is…
- the gradient at the first position only
- the sum of its contributions at every position it was applied
- the average kernel
- always zero
The gradient with respect to a convolution's input is computed by…
- a full convolution of the upstream gradient with the (flipped) kernel, i.e. the transposed operator
- a max pooling
- the same forward convolution
- a softmax
With im2col, a convolution's backward pass becomes…
- impossible
- the dense-layer rules plus adding overlapping patches back (col2im)
- a Fourier transform
- a sort