TExcelTAD
Home › Fourier Analysis & Signals › Convolution in CNNs

Convolution in CNNs

Convolutional neural networks are built from the same convolutions as this course, with three twists: the kernels are learned, they are tiny, and deep-learning libraries actually compute cross-correlation. This lesson connects the signal-processing view (LTI filters, frequency responses, the convolution theorem) to CNN layers. The full deep-learning treatment, including backpropagation through convolutions, is in Math for Deep Learning: Convolution.

Cross-correlation, not convolution

A CNN layer computes y[n]=∑kw[k] x[n+k]y[n] = \sum_k w[k]\, x[n + k]: the kernel slides without being flipped. That is cross-correlation, or convolution with the reversed kernel. Since ww is learned, the network simply learns the flipped version; nothing changes in practice, but it matters when you compare with np.convolve.

python · try it yourself
import numpy as np

x = np.array([0, 1, 2, 3, 4, 3, 2, 1, 0], dtype=float)
w = np.array([1.0, 0.0, -1.0])                      # a learned "edge" kernel

conv = np.convolve(x, w, mode="valid")              # flips w
corr = np.correlate(x, w, mode="valid")             # what a CNN layer computes
manual = np.array([np.dot(w, x[i:i + 3]) for i in range(len(x) - 2)])
print("np.convolve :", conv.tolist())
print("np.correlate:", corr.tolist())
print("CNN-style   :", manual.tolist(), " equals correlate:", np.allclose(manual, corr))
np.convolve : [2.0, 2.0, 2.0, 0.0, -2.0, -2.0, -2.0]
np.correlate: [-2.0, -2.0, -2.0, 0.0, 2.0, 2.0, 2.0]
CNN-style   : [-2.0, -2.0, -2.0, 0.0, 2.0, 2.0, 2.0]  equals correlate: True

A convolution layer is a filter bank

Each output channel of a layer is an LTI filter (per input channel) followed by a sum and a nonlinearity. Its frequency response tells you what it detects. Classic hand-designed kernels show the range:

python · try it yourself
import numpy as np

kernels = {
    "average [1,1,1]/3":      np.array([1, 1, 1]) / 3,
    "difference [1,0,-1]":    np.array([1, 0, -1]),
    "second diff [1,-2,1]":   np.array([1, -2, 1]),
}
w = np.linspace(0, np.pi, 5)
for name, k in kernels.items():
    H = np.abs([np.sum(k * np.exp(-1j * wi * np.arange(len(k)))) for wi in w])
    print(f"{name:22s} gain at omega = 0, pi/4, pi/2, 3pi/4, pi: {np.round(H, 3).tolist()}")
average [1,1,1]/3      gain at omega = 0, pi/4, pi/2, 3pi/4, pi: [1.0, 0.805, 0.333, 0.138, 0.333]
difference [1,0,-1]    gain at omega = 0, pi/4, pi/2, 3pi/4, pi: [0.0, 1.414, 2.0, 1.414, 0.0]
second diff [1,-2,1]   gain at omega = 0, pi/4, pi/2, 3pi/4, pi: [0.0, 0.586, 2.0, 3.414, 4.0]

Averaging is low-pass, the difference is band-pass (zero at DC and at Nyquist), and the second difference is high-pass. Trained first-layer filters of image CNNs typically look like oriented edge and colour-blob detectors, similar to these and to Gabor filters.

Stride is downsampling, and it aliases

A stride-2 convolution keeps every other output: downsampling by 2 without a proper anti-aliasing filter. Small shifts of the input can then change the output a lot, a known weakness of CNNs. "Blur pooling" (low-pass before striding) restores much of the shift stability:

python · try it yourself
import numpy as np

n = np.arange(64)
x = np.cos(2 * np.pi * 0.4 * n)                       # a fine pattern near the Nyquist frequency
plain = x[::2]                                        # stride 2, no filter
blur = np.convolve(x, np.array([1, 2, 1]) / 4, mode="same")[::2]
plain_shift = np.roll(x, 1)[::2]
blur_shift = np.convolve(np.roll(x, 1), np.array([1, 2, 1]) / 4, mode="same")[::2]
print("energy of output, plain stride:", round(float(np.mean(plain ** 2)), 3), "  after blurring first:", round(float(np.mean(blur ** 2)), 3))
print("change when input shifts by 1 sample: plain", round(float(np.mean((plain - plain_shift) ** 2)), 3),
      " blurred", round(float(np.mean((blur - blur_shift) ** 2)), 3))
energy of output, plain stride: 0.503   after blurring first: 0.007
change when input shifts by 1 sample: plain 1.75  blurred 0.016

The fine pattern (frequency 0.4 cycles per sample, above the new Nyquist limit 0.25) aliases into the plain strided output; the [1,2,1]/4[1, 2, 1]/4 blur removes most of it first, and the output barely reacts to the shift.

FFT convolution for large kernels

For the usual 3×33 \times 3 kernels, direct convolution (or the Winograd algorithm) is fastest. For large kernels, global filters or long 1-D sequences, layers use the convolution theorem: FNet and "global filter networks" replace attention by FFTs, and long-sequence models such as Hyena compute convolutions with very long kernels via the FFT in O(Nlog⁡N)O(N\log N).

In software

  • PyTorch nn.Conv1d/2d (cross-correlation; padding, stride, dilation, groups), torch.fft for FFT-based layers. See Padding and Stride.
  • cuDNN chooses between direct, Winograd, and FFT algorithms per layer shape.

Exercises

Exercise 1: Convolution or correlation?

A CNN learned the kernel [1,2,3][1, 2, 3]. Which kernel gives the same output with np.convolve?

Answer

[3,2,1][3, 2, 1].

Solution

Convolution flips the kernel, so to reproduce a correlation with ww you convolve with ww reversed.

Exercise 2: Receptive field

What is the receptive field of two stacked 3×33 \times 3 convolutions (stride 1)?

Answer

5×55 \times 5.

Solution

Convolving two kernels of width 3 gives an effective kernel of width 3+3−1=53 + 3 - 1 = 5, the same widths-add rule as for any convolution.

Exercise 3: A difference kernel's frequency response (code)

Compute the gain of the kernel [1,−1][1, -1] at ω=0,π/2,π\omega = 0, \pi/2, \pi.

Answer

0, about 1.414, 2.

Solution
python · try it yourself
import numpy as np
k = np.array([1, -1])
print([round(float(abs(np.sum(k * np.exp(-1j * w * np.arange(2))))), 3) for w in (0, np.pi / 2, np.pi)])
[0.0, 1.414, 2.0]

∣H∣=2∣sin⁡(ω/2)∣\lvert H \rvert = 2\lvert \sin(\omega/2) \rvert: a high-pass filter.

Test yourself

Deep-learning convolution layers actually compute…

  1. true convolution
  2. cross-correlation (no kernel flip)
  3. an FFT
  4. a matrix inverse

A stride-2 convolution without blurring can…

  1. never alias
  2. alias high-frequency content
  3. double the resolution
  4. remove all edges

For very large kernels or long sequences, convolution is computed fastest via…

  1. nested loops
  2. the FFT and the convolution theorem
  3. sorting
  4. matrix inversion