TExcelTAD
Home › Math for Deep Learning & LLMs › Backpropagation Through Convolutions

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 kk): yi=∑jwjxi+jy_i = \sum_{j} w_jx_{i+j}. With upstream gradient gi=∂L/∂yig_i = \partial\mathcal{L}/\partial y_i:

∂L∂wj=∑igi xi+j(cross-correlate x with g)\frac{\partial\mathcal{L}}{\partial w_j} = \sum_i g_i\,x_{i+j} \qquad \text{(cross-correlate } \mathbf{x} \text{ with } \mathbf{g}\text{)}
∂L∂xm=∑igi wm−i(full convolution of g with w)\frac{\partial\mathcal{L}}{\partial x_m} = \sum_i g_i\,w_{m-i} \qquad \text{(full convolution of } \mathbf{g} \text{ with } \mathbf{w}\text{)}

The weight gradient sums over every position where wjw_j was used (weight sharing = fan-out). The input gradient is TTgT^T\mathbf{g} for the Toeplitz matrix TT of Convolution as a Linear Operator: zero-pad g\mathbf{g} by k−1k - 1 and cross-correlate with the flipped kernel.

python · try it yourself
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 Yo=∑cWo,c⋆XcY_{o} = \sum_c W_{o,c} \star X_c (with ⋆\star the 2-D cross-correlation), the same pattern holds per channel pair:

∂L∂Wo,c=Xc⋆Go,∂L∂Xc=∑ofull_conv⁡(Go,Wo,c),∂L∂bo=∑i,jGo,i,j\frac{\partial\mathcal{L}}{\partial W_{o,c}} = X_c \star G_o, \qquad \frac{\partial\mathcal{L}}{\partial X_c} = \sum_o \operatorname{full\_conv}(G_o, W_{o,c}), \qquad \frac{\partial\mathcal{L}}{\partial b_o} = \sum_{i,j}G_{o,i,j}

summed over the batch as well. With stride ss, the input gradient is a transposed convolution with stride ss (Padding and Stride); equivalently, insert s−1s - 1 zeros between the entries of GG 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 Y=Wflat XcolsY = W_{\text{flat}}\,X_{\text{cols}}. Then the backward pass is just the dense-layer rule: ∂L/∂Wflat=G XcolsT\partial\mathcal{L}/\partial W_{\text{flat}} = G\,X_{\text{cols}}^T and ∂L/∂Xcols=WflatTG\partial\mathcal{L}/\partial X_{\text{cols}} = W_{\text{flat}}^TG, followed by "col2im", which adds the overlapping patches back into place.

python · try it yourself
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_weight and conv2d_input expose 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 4×44 \times 4 with all upstream gradients equal to 0.50.5, batch size 2. What is the bias gradient?

Answer
Solution

The bias is added to all 2⋅16=322 \cdot 16 = 32 outputs; 32⋅0.5=1632 \cdot 0.5 = 16.

Exercise 2: Weight gradient by hand

x=(1,2,3)\mathbf{x} = (1, 2, 3), kernel length 2, upstream gradient g=(1,−1)\mathbf{g} = (1, -1). Find ∂L/∂w\partial\mathcal{L}/\partial\mathbf{w}.

Answer

(−1,−1)(-1, -1).

Solution

∂L/∂w0=g0x0+g1x1=1−2=−1\partial\mathcal{L}/\partial w_0 = g_0x_0 + g_1x_1 = 1 - 2 = -1; ∂L/∂w1=g0x1+g1x2=2−3=−1\partial\mathcal{L}/\partial w_1 = g_0x_1 + g_1x_2 = 2 - 3 = -1.

Exercise 3: Transpose check (code)

Build the Toeplitz matrix TT for a length-3 kernel on a length-6 input and verify that TTgT^T\mathbf{g} equals np.convolve(g, w, "full").

Answer

They are equal.

Solution
python · try it yourself
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…

  1. the gradient at the first position only
  2. the sum of its contributions at every position it was applied
  3. the average kernel
  4. always zero

The gradient with respect to a convolution's input is computed by…

  1. a full convolution of the upstream gradient with the (flipped) kernel, i.e. the transposed operator
  2. a max pooling
  3. the same forward convolution
  4. a softmax

With im2col, a convolution's backward pass becomes…

  1. impossible
  2. the dense-layer rules plus adding overlapping patches back (col2im)
  3. a Fourier transform
  4. a sort