TExcelTAD

Convolution as a Linear Operator

A convolutional layer slides a small filter over its input and computes a weighted sum at every position. Mathematically it is a linear map with two strong constraints: local connectivity and shared weights. Those constraints cut the parameter count by orders of magnitude and make the layer translation-equivariant: shift the input and the output shifts the same way. This lesson treats convolution as the matrix it secretly is. Signal-processing background: Signals and Fourier.

The operation

For a 1-D input x\mathbf{x} and a kernel w\mathbf{w} of length kk, deep learning's "convolution" is actually cross-correlation:

yi=∑j=0k−1wj xi+jy_i = \sum_{j=0}^{k-1} w_j\,x_{i+j}

(Mathematical convolution flips the kernel, ∑jwjxi−j\sum_j w_jx_{i-j}; since the kernel is learned, the flip does not matter.) In 2-D with CinC_{\text{in}} input channels and CoutC_{\text{out}} filters,

Yo,i,j=bo+∑c=1Cin∑u=0k−1∑v=0k−1Wo,c,u,v Xc,i+u,j+vY_{o, i, j} = b_o + \sum_{c=1}^{C_{\text{in}}}\sum_{u=0}^{k-1}\sum_{v=0}^{k-1}W_{o, c, u, v}\,X_{c, i+u, j+v}

The layer has CoutCink2+CoutC_{\text{out}}C_{\text{in}}k^2 + C_{\text{out}} parameters, independent of the image size.

python · try it yourself
import numpy as np

x = np.array([0, 0, 1, 2, 3, 0, 0, 5, 0], dtype=float)
w = np.array([-1.0, 0.0, 1.0])                   # a difference (edge) detector
y = np.array([w @ x[i:i + 3] for i in range(len(x) - 2)])
print("input :", x)
print("output:", y)
print("np.correlate agrees:", np.allclose(y, np.correlate(x, w, mode="valid")))
print("np.convolve flips the kernel:", np.convolve(x, w, mode="valid"))
input : [0. 0. 1. 2. 3. 0. 0. 5. 0.]
output: [ 1.  2.  2. -2. -3.  5.  0.]
np.correlate agrees: True
np.convolve flips the kernel: [-1. -2. -2.  2.  3. -5.  0.]

Convolution is a structured matrix

Stacking the outputs, y=Tx\mathbf{y} = T\mathbf{x} where TT is a Toeplitz matrix: each row is the kernel shifted one step. A dense layer from 9 to 7 units has 63 free weights; this one has 3, repeated. This view also gives the backward pass at once: the gradient with respect to the input is TTgT^T\mathbf{g}, which is a convolution with the flipped kernel (Backpropagation Through Convolutions).

python · try it yourself
import numpy as np

x = np.array([0, 0, 1, 2, 3, 0, 0, 5, 0], dtype=float); w = np.array([-1.0, 0.0, 1.0])
n, k = len(x), len(w)
T = np.zeros((n - k + 1, n))
for i in range(n - k + 1):
    T[i, i:i + k] = w
print(T.astype(int))
print("T @ x:", T @ x)
shift = np.roll(x, 1); shift[0] = 0
print("equivariance: conv(shift(x)) == shift(conv(x)) inside:", np.allclose((T @ shift)[1:], (T @ x)[:-1]))
[[-1  0  1  0  0  0  0  0  0]
 [ 0 -1  0  1  0  0  0  0  0]
 [ 0  0 -1  0  1  0  0  0  0]
 [ 0  0  0 -1  0  1  0  0  0]
 [ 0  0  0  0 -1  0  1  0  0]
 [ 0  0  0  0  0 -1  0  1  0]
 [ 0  0  0  0  0  0 -1  0  1]]
T @ x: [ 1.  2.  2. -2. -3.  5.  0.]
equivariance: conv(shift(x)) == shift(conv(x)) inside: True

Why convolutions suit images

  • Locality: nearby pixels are strongly related; a 3×33 \times 3 filter looks only at a neighborhood.
  • Weight sharing: an edge detector useful at one place is useful everywhere.
  • Equivariance: a shifted object gives a shifted feature map; pooling then adds some invariance (Pooling).

The parameter savings are dramatic: a 3×33 \times 3 convolution from 64 to 64 channels has 36,928 parameters whatever the image size, while a dense layer between two 64×56×5664 \times 56 \times 56 feature maps would have about 4×10104 \times 10^{10}.

The convolution theorem

Convolution in space is multiplication in frequency: w∗x^=w^⋅x^\widehat{w * x} = \hat{w}\cdot\hat{x} (with circular boundaries). FFT-based convolution is faster for large kernels; for the small kernels of CNNs, direct or Winograd algorithms win.

In software

  • nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding) stores weights as (C_out, C_in, k, k).
  • nn.Conv1d is used for audio and, with causal padding, for sequence models; depthwise convolutions (groups=C) mix space only.
  • F.unfold (im2col) turns convolution into one big matrix multiply, which is how many GPU kernels implement it.

Go further: A CNN in NumPy, then in PyTorch trains a gradient-checked convolutional network on digits.

Exercises

Exercise 1: Output by hand

Cross-correlate x=(1,2,3,4)\mathbf{x} = (1, 2, 3, 4) with w=(1,−1)\mathbf{w} = (1, -1).

Answer

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

Solution

1−21 - 2, 2−32 - 3, 3−43 - 4. A constant slope gives a constant response.

Exercise 2: Parameter count

How many parameters does Conv2d(3, 32, kernel_size=5) have?

Answer
Solution

32⋅3⋅5⋅5=240032 \cdot 3 \cdot 5 \cdot 5 = 2400 weights plus 32 biases.

Exercise 3: 2-D convolution (code)

Implement a valid 2-D cross-correlation with loops and apply the vertical-edge kernel (1−1)\begin{pmatrix} 1 & -1 \end{pmatrix} to an image that is 0 on the left half and 1 on the right.

Answer

The response is nonzero only in the column where the edge is.

Solution
python · try it yourself
import numpy as np
def corr2d(X, K):
    h, w = K.shape
    return np.array([[np.sum(X[i:i + h, j:j + w] * K) for j in range(X.shape[1] - w + 1)] for i in range(X.shape[0] - h + 1)])
X = np.zeros((4, 6)); X[:, 3:] = 1
print(corr2d(X, np.array([[1.0, -1.0]])))
[[ 0.  0. -1.  0.  0.]
 [ 0.  0. -1.  0.  0.]
 [ 0.  0. -1.  0.  0.]
 [ 0.  0. -1.  0.  0.]]

Test yourself

What do deep-learning libraries actually compute in a 'convolution' layer?

  1. True convolution with a flipped kernel
  2. Cross-correlation (no flip)
  3. A Fourier transform
  4. A dense matrix product with free weights

Translation equivariance means…

  1. the output is unchanged by shifts
  2. shifting the input shifts the output by the same amount
  3. the layer has no parameters
  4. the image must be square

As a matrix, a 1-D convolution is…

  1. diagonal
  2. a Toeplitz (banded, constant-diagonal) matrix
  3. orthogonal
  4. random