6.2 Convolutions for Images

In Section 6.1, we derived the convolutional layer on paper from two geometric principles: translation equivariance and locality. Now we see what that formula actually computes on an image, and whether gradient descent can discover useful kernels automatically from data.

Consider locating vertical edges where a bright region meets a dark one. Subtracting each pixel's right-hand neighbor ([X]i,j−[X]i,j+1[\mathbf{X}]_{i,j} - [\mathbf{X}]_{i,j+1}) yields zero inside uniform regions, +1+1 where white transitions to black, and −1-1 where black returns to white. Sweeping the two-weight detector (1,−1)(1, -1) across every valid image location produces an edge map. In this section, we implement two-dimensional cross-correlation, test our hand-crafted edge detector, let gradient descent learn (1,−1)(1, -1) directly from data, show how a convolution becomes a single matrix multiplication (im2col), and derive how stacking layers widens a unit's receptive field.

6.2.1 Cross-Correlation#

6.2.1.1 The Operation#

Leaving channels aside for the moment, let the input X\mathbf{X} be an nh×nwn_\textrm{h} \times n_\textrm{w} matrix and the kernel K\mathbf{K} be a kh×kwk_\textrm{h} \times k_\textrm{w} matrix. The kernel defines a sliding window of shape kh×kwk_\textrm{h} \times k_\textrm{w}. Placing the window's upper-left corner at (i,j)(i, j), we multiply the covered input patch elementwise with K\mathbf{K} and sum the products to produce the output entry at (i,j)(i, j):

[Y]i,j=∑a=0kh−1∑b=0kw−1[K]a,b [X]i+a,j+b.(6.2.1)[\mathbf{Y}]_{i, j} = \sum_{a=0}^{k_\textrm{h}-1} \sum_{b=0}^{k_\textrm{w}-1} [\mathbf{K}]_{a, b}\, [\mathbf{X}]_{i+a, j+b}. \tag{6.2.1}

This is the two-dimensional cross-correlation of X\mathbf{X} with K\mathbf{K}, written Y=X⋆K\mathbf{Y} = \mathbf{X} \star \mathbf{K} with zero-based indices matching code. Whereas Section 6.1 centered offsets symmetrically from −Δ-\Delta to Δ\Delta, anchoring at the upper-left corner differs only by a fixed shift of Δ\Delta while naturally handling even-sized kernels (such as a 2×22 \times 2 kernel or our 1×21 \times 2 edge detector) that have no center pixel.

Figure 6.2.1:

Two-dimensional cross-correlation. The shaded portions are the first output element and the input and kernel elements used to compute it: 0×0+1×1+3×2+4×3=190\times0+1\times1+3\times2+4\times3=19.

In Figure 6.2.1, we slide a 2×22 \times 2 kernel across a 3×33 \times 3 input one pixel at a time, left to right and top to bottom. The window fits cleanly at four positions, yielding the 2×22 \times 2 output:

0×0+1×1+3×2+4×3=19,1×0+2×1+4×2+5×3=25,3×0+4×1+6×2+7×3=37,4×0+5×1+7×2+8×3=43.\begin{aligned} 0\times0+1\times1+3\times2+4\times3 &= 19,\\ 1\times0+2\times1+4\times2+5\times3 &= 25,\\ 3\times0+4\times1+6\times2+7\times3 &= 37,\\ 4\times0+5\times1+7\times2+8\times3 &= 43. \end{aligned}

Notice that the output shrinks slightly along each axis because the kernel must stay wholly inside the input. Fitting a width-kk window into length nn leaves n−k+1n - k + 1 valid positions, so the output shape is

(nh−kh+1)×(nw−kw+1).(6.2.2)(n_\textrm{h}-k_\textrm{h}+1) \times (n_\textrm{w}-k_\textrm{w}+1). \tag{6.2.2}

Thus a 3×33 \times 3 input with a 2×22 \times 2 kernel yields 2×22 \times 2, a 6×86 \times 8 image with a 1×21 \times 2 kernel yields 6×76 \times 7, and a 28×2828 \times 28 Fashion-MNIST image with a 5×55 \times 5 kernel yields 24×2424 \times 24. Whenever we want to preserve spatial dimensions, we surround the input with a border of zeros (padding), which we examine alongside strides and dilation in Section 6.3.

6.2.1.2 Implementation#

We implement (6.2.1) directly in corr2d using a pair of loops over every output coordinate.

def corr2d(X, K):
    """Compute 2D cross-correlation."""
    h, w = K.shape
    Y = d2l.zeros((X.shape[0] - h + 1, X.shape[1] - w + 1))
    for i in range(Y.shape[0]):
        for j in range(Y.shape[1]):
            Y[i, j] = d2l.reduce_sum((X[i: i + h, j: j + w] * K))
    return Y

To verify corr2d against our hand calculation in Figure 6.2.1, we construct the 3×33 \times 3 input tensor X and 2×22 \times 2 kernel K and evaluate corr2d(X, K).

X = d2l.tensor([[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]])
K = d2l.tensor([[0.0, 1.0], [2.0, 3.0]])
corr2d(X, K)
tensor([[19., 25.],
        [37., 43.]])

The output reproduces Figure 6.2.1 entry for entry (and as shown in Section 6.1, strict mathematical convolution with a flipped kernel K′\mathbf{K}' learns the exact same family of layers, so we follow standard deep learning terminology and call cross-correlation "convolution").

6.2.2 Convolutional Layers#

6.2.2.1 The Layer#

A two-dimensional convolutional layer cross-correlates its input with a learned kernel and adds a scalar bias. Just like our MLP weights in Chapter 4, we initialize the kernel from N(0,0.012)\mathcal{N}(0, 0.01^2) and the bias to zero. Below, Conv2D registers both parameters and invokes corr2d in its forward pass; a layer with a kernel of height hh and width ww is called an h×wh \times w convolutional layer.

class Conv2D(nn.Module):
    def __init__(self, kernel_size):
        super().__init__()
        self.weight = nn.Parameter(0.01 * torch.randn(kernel_size))
        self.bias = nn.Parameter(torch.zeros(1))

    def forward(self, x):
        return corr2d(x, self.weight) + self.bias

Unlike a dense layer, a convolutional layer is not locked to a fixed input resolution because its parameters depend only on the kernel size. The exact same 2×22 \times 2 layer (5 parameters total) processes both our 3×33 \times 3 tensor X and a 6×86 \times 8 image, returning outputs of shapes 2×22 \times 2 and 5×75 \times 7:

layer = Conv2D((2, 2))
layer(X).shape, layer(d2l.ones((6, 8))).shape
(torch.Size([2, 2]), torch.Size([5, 7]))

6.2.2.2 Edge Detection#

We now test the vertical edge detector from the introduction on a 6×86 \times 8 synthetic image whose middle four columns are black (0) and outer columns are white (1).

X = d2l.ones((6, 8))
X[:, 2:6] = 0
X
tensor([[1., 1., 0., 0., 0., 0., 1., 1.],
        [1., 1., 0., 0., 0., 0., 1., 1.],
        [1., 1., 0., 0., 0., 0., 1., 1.],
        [1., 1., 0., 0., 0., 0., 1., 1.],
        [1., 1., 0., 0., 0., 0., 1., 1.],
        [1., 1., 0., 0., 0., 0., 1., 1.]])

We define the 1×21 \times 2 kernel

K=[1−1].(6.2.3)\mathbf{K} = \begin{bmatrix} 1 & -1 \end{bmatrix}. \tag{6.2.3}

At every position (i,j)(i, j), this computes the horizontal finite difference [X]i,j−[X]i,j+1[\mathbf{X}]_{i,j} - [\mathbf{X}]_{i,j+1}, a discrete approximation (up to sign) of the horizontal derivative of brightness, which vanishes across flat regions and spikes wherever intensity jumps.

K = d2l.tensor([[1.0, -1.0]])

Cross-correlating the 6×86 \times 8 stripe image X with the 1×21 \times 2 horizontal-difference kernel K via corr2d(X, K) produces the 6×76 \times 7 edge map Y:

Y = corr2d(X, K)
Y
tensor([[ 0.,  1.,  0.,  0.,  0., -1.,  0.],
        [ 0.,  1.,  0.,  0.,  0., -1.,  0.],
        [ 0.,  1.,  0.,  0.,  0., -1.,  0.],
        [ 0.,  1.,  0.,  0.,  0., -1.,  0.],
        [ 0.,  1.,  0.,  0.,  0., -1.,  0.],
        [ 0.,  1.,  0.,  0.,  0., -1.,  0.]])

Sure enough, Y fires +1 along the white-to-black boundary, -1 along the black-to-white boundary, and 0 everywhere else. Applying the exact same kernel to the transposed image (turning the vertical stripe into a horizontal one) yields all zeros:

corr2d(d2l.transpose(X), K)
tensor([[0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0.]])

Clearly [1, -1] responds strictly to vertical edges. Detecting horizontal edges, diagonals, corners, or textures requires different kernels altogether.

6.2.2.3 Learning a Kernel#

Hand-crafting [1, -1] is easy when we know the exact feature we want, yet no engineer can specify thousands of intermediate filters across a deep network by hand. Can gradient descent recover the kernel [1, -1] from the input–output pair (X, Y) alone? We test this using each framework's built-in 2D convolutional layer (with bias omitted and weights initialized from N(0,0.012)\mathcal{N}(0, 0.01^2)), minimizing squared error summed across all 42 output entries over 10 gradient steps at learning rate 0.030.03. Because built-in layers expect 4D tensors including batch and channel axes (Section 6.4), we reshape X and Y accordingly.

conv2d = nn.Conv2d(1, 1, kernel_size=(1, 2), bias=False)
nn.init.normal_(conv2d.weight, std=0.01)
# Layers take (example, channel, height, width): one example, one channel
X = X.reshape((1, 1, 6, 8))
Y = Y.reshape((1, 1, 6, 7))
lr = 3e-2  # Learning rate

for i in range(10):
    l = ((conv2d(X) - Y) ** 2).sum()
    conv2d.zero_grad()
    l.backward()
    with torch.no_grad():
        conv2d.weight -= lr * conv2d.weight.grad
    if i % 3 == 0:
        print(f'step {i}, loss {l:.3f}')
step 0, loss 12.216
step 3, loss 0.840
step 6, loss 0.058
step 9, loss 0.004

Initially the loss sits near 12 (the near-zero random kernel misses all 12 ±1\pm 1 edge pixels by roughly 1), and within just nine steps it drops below 0.01. Inspecting the learned kernel confirms what it found:

d2l.reshape(conv2d.weight.data, (1, 2))
tensor([[ 0.9891, -0.9876]])

Both entries land within roughly 0.02 of [1, -1]. Nothing in this loop knew anything about edges: given a loss signal, gradient descent discovered the filter on its own. Here we supervised the single layer directly with Y; in a deep CNN, backpropagation learns every layer's kernels end to end from the final task loss alone.

6.2.3 Convolution as Matrix Multiplication#

While the nested loops in corr2d make the math transparent, visiting one output pixel at a time in Python is far too slow for real workloads. A classic remedy, and still one of the algorithms that libraries choose from, is to recast cross-correlation as a single large matrix multiplication, the exact operation GPUs execute at peak speed. Notice that every output entry in Figure 6.2.1 is simply the dot product of the flattened khkwk_\textrm{h} k_\textrm{w}-element kernel with the corresponding flattened input window. Extracting all (nh−kh+1)(nw−kw+1)(n_\textrm{h}-k_\textrm{h}+1)(n_\textrm{w}-k_\textrm{w}+1) windows and stacking them as rows yields a patch matrix; multiplying it by the flattened kernel computes the entire cross-correlation in one shot. This standard layout transformation is called im2col ("image to columns", or rows here). Figure 6.2.2 carries it out on the example of Figure 6.2.1.

Figure 6.2.2:

The cross-correlation of Figure 6.2.1 as one matrix product. Each of the four 2×22 \times 2 windows of the input becomes a row of the patch matrix, and multiplying by the flattened kernel gives the flattened output. The shaded cells follow the first window to its row and to the output 19. The center pixel 4 lies in all four windows, so it appears in every row.

The trade-off is extra workspace memory, since each interior pixel is duplicated into up to khkwk_\textrm{h} k_\textrm{w} patches. Below we verify on Figure 6.2.1 that this single matrix multiply matches corr2d exactly:

X = d2l.tensor([[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]])
K = d2l.tensor([[0.0, 1.0], [2.0, 3.0]])
h, w = K.shape
h_o, w_o = X.shape[0] - h + 1, X.shape[1] - w + 1
patches = d2l.stack([d2l.reshape(X[i:i + h, j:j + w], (-1,))
                     for i in range(h_o) for j in range(w_o)])
Y_mat = d2l.reshape(d2l.matmul(patches, d2l.reshape(K, (-1, 1))), (h_o, w_o))
Y_mat, d2l.reduce_sum(d2l.abs(Y_mat - corr2d(X, K)))
(tensor([[19., 25.],
         [37., 43.]]),
 tensor(0.))

The discrepancy is identically zero: one matrix product reproduces corr2d perfectly.

Equivalently, we can unroll the kernel instead of the input into a sparse banded matrix W\mathbf{W} multiplying the flattened image—the exact 2D analog of panel (c) in Figure 6.1.3, where every row repeats the same handful of kernel weights. Seeing a convolution as a structured dense layer brings us full circle to the derivation of Section 6.1 (and the exercises build W\mathbf{W} explicitly).

6.2.4 Feature Maps and Receptive Fields#

A single convolutional layer sees only a patch the size of its kernel, whereas recognizing whole objects demands integrating context across much wider areas. Recall from Section 6.1.4 that a convolutional layer's output is called a feature map (like our vertical edge map Y). For any element xx in a feature map, its receptive field is the region of the input image (or of an earlier layer) whose values can influence xx during forward propagation—borrowing the neurophysiology term from Figure 6.1.

6.2.4.1 Stacked Layers#

In Figure 6.2.1, the shaded output 19 has a 2×22 \times 2 receptive field covering the top-left four pixels of X\mathbf{X}. Now stack a second 2×22 \times 2 convolutional layer on top of the 2×22 \times 2 output Y\mathbf{Y} to produce a single scalar zz: zz depends on all four elements of Y\mathbf{Y}, which together depend on all nine elements of X\mathbf{X}. Stacking layers expands the receptive field smoothly with depth.

How quickly does it grow? Each k×kk \times k convolutional layer reaches k−1k - 1 pixels farther than a single element of its input, so stacking LL layers with kernel sizes k1,…,kLk_1, \ldots, k_L yields a receptive field of side length

r=1+∑i=1L(ki−1).(6.2.4)r = 1 + \sum_{i=1}^{L} (k_i - 1). \tag{6.2.4}

For a stack of LL consecutive 3×33 \times 3 layers, each layer adds 2 pixels, covering (2L+1)×(2L+1)(2L + 1) \times (2L + 1) inputs: 5×55 \times 5 after two layers and 7×77 \times 7 after three (Figure 6.2.3). This linear growth is actually a blessing rather than a reason to reach for huge kernels: three stacked 3×33 \times 3 layers achieve the same 7×77 \times 7 receptive field as a single 7×77 \times 7 layer using far fewer parameters (3×9=273 \times 9 = 27 weights vs. 49 per channel pair) while interleaving three nonlinearities instead of one.

Figure 6.2.3:

Receptive field of one unit after three one-dimensional layers with kernel size 3. Shaded cells are the units that the top unit depends on, and the lines connect each of them to its inputs. Each layer widens the receptive field by 2, to 7 inputs.

6.2.4.2 Effective Receptive Fields#

Keep in mind that rr measures the theoretical receptive field (every input pixel with any path to an output unit) without saying how strongly each pixel actually contributes. Measuring input gradients directly, Luo et al. (2016) showed that the effective receptive field decays sharply away from the center in a roughly Gaussian bell curve, in both untrained and trained networks. Deep units can theoretically see far across the image, but their sensitivity concentrates heavily near the center.

Counting paths explains the bell shape. An input at the edge of the receptive field reaches the output unit along a single chain of connections, whereas the center input can take many routes through the layers in between. Figure 6.2.4 counts them for the tower of Figure 6.2.3: the center input has seven paths to the top unit and each edge input has one. If all weights have a similar magnitude, the influence of an input grows with its number of paths.

Figure 6.2.4:

Number of paths from each unit to the top unit of Figure 6.2.3 (three one-dimensional layers with kernel size 3). Each count is the sum of the counts of the units that the cell feeds. Darker cells have more paths than the other cells of their layer, and the bars repeat the counts of the input row: 1, 3, 6, 7, 6, 3, 1.

Two practical gaps remain in our basic layer: every unpadded convolution shrinks spatial dimensions while under-sampling border pixels, and a single kernel detects only one pattern. We address spatial sizing and borders next in Section 6.3, and multi-channel feature maps in Section 6.4.

6.2.5 Summary#

A convolutional layer applies two-dimensional cross-correlation with a learned kernel plus a scalar bias, sliding the kernel across every valid window of the input. A simple 1×21 \times 2 finite-difference kernel [1, -1] detects vertical edges anywhere in an image, and gradient descent recovers those exact weights from input–output data alone, just as deep CNNs learn entire hierarchies of filters end to end. Mathematical convolution flips the kernel, making no difference once kernels are learned. A convolution can be evaluated as a single matrix multiplication (im2col), and stacking LL convolutional layers widens each unit's receptive field linearly by ki−1k_i - 1 per layer.

6.2.6 Exercises#

  1. [code] Hand-designed kernels. Design some kernels manually.

    1. Given a directional vector v=(v1,v2)\mathbf{v} = (v_1, v_2), derive an edge-detection kernel that detects edges orthogonal to v\mathbf{v}, i.e., edges in the direction (v2,−v1)(v_2, -v_1).
    2. Derive a finite difference operator for the second derivative. Which structures in images respond most strongly to it?
    3. What is the minimum size of a kernel to obtain a derivative of order dd?
    4. How would you design a blur kernel? Why might you want to use such a kernel?
    5. Load a photograph, convert it to one channel, and downsample it to about 100×100100 \times 100 pixels (corr2d loops in Python). Apply the edge detector, the blur kernel, and the sharpening kernel "twice the identity minus the blur", and display each result next to the original. What does the edge map of a photograph show that the edge map of the black band could not?

    Adapted from Stanford CS231n, Assignment 2, ConvolutionalNetworks notebook.

  2. [code] Convolution as a banded matrix. The patch matrix of Section 6.2.3 unfolds the input. The opposite construction unrolls the kernel. Let X\mathbf{X} be a 4×44 \times 4 input, K\mathbf{K} a 3×33 \times 3 kernel, and vec(⋅)\textrm{vec}(\cdot) the row-by-row flattening.

    1. Construct the 4×164 \times 16 matrix W\mathbf{W} with W vec(X)=vec(Y)\mathbf{W}\,\textrm{vec}(\mathbf{X}) = \textrm{vec}(\mathbf{Y}), where Y\mathbf{Y} is the cross-correlation of X\mathbf{X} with K\mathbf{K}. How many nonzero entries does each row have, and how many distinct values appear in W\mathbf{W}?
    2. Build W\mathbf{W} in code from K and confirm that the product reproduces corr2d(X, K).
    3. For an n×nn \times n input and a k×kk \times k kernel, count the entries of W\mathbf{W} stored as a dense array, the nonzero entries of W\mathbf{W}, and the entries of the patch matrix. How does each count grow with nn?
    4. Keep the sparsity pattern of W\mathbf{W} but give every row its own k2k^2 values. The result is a locally connected layer: the fourth-order tensor V\mathsf{V} of Section 6.1 in [H]i,j=[U]i,j+∑a,b[V]i,j,a,b[X]i+a,j+b[\mathbf{H}]_{i,j} = [\mathbf{U}]_{i,j} + \sum_{a,b} [\mathsf{V}]_{i,j,a,b}[\mathbf{X}]_{i+a,j+b}, restricted to a k×kk \times k window of offsets (a,b)(a, b) before translation equivariance ties the weights. For an n×nn \times n input, count the parameters of this layer, of a fully connected layer with the same input and output shapes, and of the convolution.

    Adapted from CMU 11-785, Homework 2 Part 1.

  3. [code] Effective receptive field. ● The theoretical receptive field rr of this section bounds which inputs can influence an output; the effective receptive field measures how much they actually do (Luo et al., 2016). Build a stack of LL single-channel 3×33 \times 3 convolutional layers with no padding, no bias, and no nonlinearity on a 32×3232 \times 32 input, using the built-in layer of Section 6.2.2.3. Draw every kernel entry independently from a standard normal distribution.

    1. For L=3L = 3 and a single draw of the kernels, backpropagate a unit gradient from an output unit near the center of the last layer to the input and plot the magnitude of the input gradient. Compare its support with the 7×77 \times 7 theoretical receptive field, and say where the magnitude is largest.
    2. Average the squared input gradient over 500 draws of the kernels, for L=3L = 3 and for L=10L = 10. Sum each averaged map over its rows and normalize the resulting column profile to sum to one. How does the ratio of the profile's standard deviation to the theoretical side length 2L+12L + 1 change with depth?
    3. Figure 6.2.4 counts the paths for L=3L = 3 in one dimension. Show that for general LL the expected squared input gradient, summed over rows, is proportional to the convolution of LL copies of the vector (1,1,1)(1, 1, 1). Derive how the standard deviation of the normalized profile grows with LL.
  4. [code] Backward pass of a convolution. ● Let Y\mathbf{Y} be the single-channel cross-correlation of an input X\mathbf{X} with a kernel K\mathbf{K}, as computed by corr2d, and let ℓ\ell be a scalar loss that depends on X\mathbf{X} and K\mathbf{K} only through Y\mathbf{Y}.

    1. Derive ∂ℓ/∂K\partial \ell/\partial \mathbf{K} and ∂ℓ/∂X\partial \ell/\partial \mathbf{X} in terms of ∂ℓ/∂Y\partial \ell/\partial \mathbf{Y}, in the style of the backpropagation equations of Section 4.3.
    2. Implement your expression for ∂ℓ/∂K\partial \ell/\partial \mathbf{K} without automatic differentiation for the loss ℓ=∑i,jGijYij\ell = \sum_{i,j} G_{ij} Y_{ij}, where G\mathbf{G} is a fixed random matrix of the shape of Y\mathbf{Y}. Compare it with a centered finite-difference gradient with step size 10−210^{-2} on a small random X and K, and report the largest relative error.
    3. Check your expression for ∂ℓ/∂K\partial \ell/\partial \mathbf{K} against the kernel gradient that automatic differentiation computes in the experiment of Section 6.2.2.3.

    Adapted from Michael Nielsen, Neural Networks and Deep Learning, Chapter 6, and Stanford CS231n, Assignment 2, ConvolutionalNetworks notebook.

Discussions