Convolutions for Images

Dive into Deep Learning · §6.2

Convolutions for Images
2D cross-correlation · edge detection · learned kernels · im2col · receptive fields

Detecting Local Edges Across an Image

Motivation & Core Mental Model

  • Synthetic 6 \times 8 test image: White outer columns (1) surrounding a 4-column black vertical band (0).
  • Horizontal finite difference: Sweeping \mathbf{K} = [1, -1] computes [\mathbf{X}]_{i,j} - [\mathbf{X}]_{i,j+1}, firing +1 at white-to-black and -1 at black-to-white edges.
  • Learning vs. hand-crafting: Deep CNNs discover thousands of such kernels automatically via gradient descent.

The 2D Cross-Correlation Operation

Sliding-Window Inner Products

Given an n_\textrm{h} \times n_\textrm{w} input matrix \mathbf{X} and a k_\textrm{h} \times k_\textrm{w} kernel \mathbf{K}, the 2D cross-correlation \mathbf{Y} = \mathbf{X} \star \mathbf{K} places the window’s top-left corner at (i, j) and sums elementwise products:

[\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}

  • Top-left anchor: Zero-based indices a, b \ge 0 match array indexing in code and handle even-sized kernels (like 2 \times 2 or 1 \times 2) cleanly.
  • Shaded top-left output (0,0): 0\cdot 0 + 1\cdot 1 + 3\cdot 2 + 4\cdot 3 = 19.

Valid Window Positions and Output Spatial Shape

Why Unpadded Convolutions Shrink the Grid

\textrm{Output shape} = (n_\textrm{h} - k_\textrm{h} + 1) \times (n_\textrm{w} - k_\textrm{w} + 1)

  • Valid window placements: A k_\textrm{h} \times k_\textrm{w} window fits inside an n_\textrm{h} \times n_\textrm{w} grid at n - k + 1 positions per axis.
  • Shape examples: 3 \times 3 \star 2 \times 2 \to 2 \times 2 (19, 25, 37, 43); 28 \times 28 \star 5 \times 5 \to 24 \times 24.

Implementing 2D Cross-Correlation in Code

Direct Nested-Loop Implementation

The function corr2d allocates the (n_\textrm{h} - k_\textrm{h} + 1) \times (n_\textrm{w} - k_\textrm{w} + 1) output tensor and computes each entry as the sum of X[i:i+h, j:j+w] * K:

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

Each iteration slices a k_\textrm{h} \times k_\textrm{w} sub-window of X, multiplies elementwise with K, and reduces via sum.

Verifying corr2d and the Flipped-Kernel Equivalence

Cross-Correlation vs. Mathematical Convolution

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.]])
  • 180° flipped kernel \mathbf{K}': Cross-correlating with \mathbf{K} equals convolving with [\mathbf{K}']_{a,b} = [\mathbf{K}]_{-a,-b}.
  • Identical learned class: Frameworks compute cross-correlation and call it convolution.

Building a 2D Convolutional Layer Module

Learnable Kernel Weights Plus Scalar Bias

A convolutional layer wraps corr2d with a learnable k_\textrm{h} \times k_\textrm{w} weight parameter (initialized from \mathcal{N}(0, 0.01^2)) and a scalar bias (initialized to 0):

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

Resolution Independence of Convolutional Layers

Fixed Parameters Across Arbitrary Input Sizes

layer = Conv2D((2, 2))
layer(X).shape, layer(d2l.ones((6, 8))).shape
(torch.Size([2, 2]), torch.Size([5, 7]))
  • Decoupled from H \times W: The exact same 5 parameters (2 \times 2 kernel + 1 bias) process 3 \times 3, 6 \times 8, or megapixel inputs without reshaping weights.

Constructing a Synthetic Vertical-Edge Image

A 6×8 Binary Test Pattern

We construct the 6 \times 8 test image X with ones on the left and right borders and zeros across the middle four columns (X[:, 2:6] = 0):

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.]])
  • Piecewise-constant columns: Intensity is constant (1 or 0) within columns 0\text{--}1, 2\text{--}5, and 6\text{--}7, jumping only between columns 1 \to 2 and 5 \to 6.

Applying the Horizontal Finite-Difference Kernel

Detecting Vertical Edges with K = [1, -1]

Cross-correlating X with the 1 \times 2 kernel \mathbf{K} = \begin{bmatrix} 1 & -1 \end{bmatrix} computes [\mathbf{Y}]_{i,j} = [\mathbf{X}]_{i,j} - [\mathbf{X}]_{i,j+1} at every horizontal pair:

K = d2l.tensor([[1.0, -1.0]])
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.]])
  • Signed edge map: Column 1 fires +1 (white-to-black transition), column 5 fires -1 (black-to-white transition), and all constant interior columns evaluate to 0.

Orientation Selectivity of Edge Kernels

Why One Kernel Cannot Detect All Orientations

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.]])
  • Blind to horizontal edges: Transposing X (X.T) makes horizontal neighbors identical, so [1, -1] outputs all zeros.
  • Filter banks (§6.4): Vision layers learn parallel channels for horizontal, vertical, and diagonal orientations.

Learning an Edge Detector via Gradient Descent

Supervising a Built-In Convolutional Layer on (X, Y)

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
  • 4D framework tensors: Reshape X and Y to 4D tensors (one example, one channel) and minimize \mathcal{L} = \|\hat{\mathbf{Y}} - \mathbf{Y}\|_2^2 at \eta = 0.03.

Inspecting the Learned Kernel Weights

Why Initial Loss Is 12 and Converges to [1, -1]

d2l.reshape(conv2d.weight.data, (1, 2))
tensor([[ 0.9891, -0.9876]])
  • Why loss starts at 12.0: Near-zero weights predict \hat{Y} \approx 0, missing the twelve \pm 1 edge pixels in Y (12 \times 1^2 = 12).
  • Convergence in 9 steps: SGD recovers [0.99, -0.99] automatically from data.

Fast Execution: Convolution via Matrix Multiplication

The im2col (Image-to-Columns) Transformation

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.))
  • Single dense GEMM: Flatten each k_\textrm{h} \times k_\textrm{w} window into a row of patches \in \mathbb{R}^{(h_\textrm{o} w_\textrm{o}) \times (k_\textrm{h} k_\textrm{w})} and multiply by \textrm{vec}(\mathbf{K}).
  • Trade-off: Peak GPU Tensor Core speed at the cost of k_\textrm{h} k_\textrm{w}\times patch workspace duplication.

Dual View: Unrolling the Kernel into a Banded Matrix

Toeplitz Weight Matrix Multiplication

Instead of unfolding the input image into duplicated patches, we can unroll the kernel into a sparse banded matrix \mathbf{W} that multiplies the flattened input vector \textrm{vec}(\mathbf{X}):

  • Matrix–vector form: \textrm{vec}(\mathbf{Y}) = \mathbf{W}\,\textrm{vec}(\mathbf{X}), where \mathbf{W} has (n_\textrm{h}-k_\textrm{h}+1)(n_\textrm{w}-k_\textrm{w}+1) rows and n_\textrm{h} n_\textrm{w} columns.
  • Connection to §6.1 and backprop: Every row of \mathbf{W} holds the same k_\textrm{h} k_\textrm{w} kernel entries shifted across columns (panel c), making the backward pass with respect to \mathbf{X} simply multiplication by \mathbf{W}^\top (a transposed convolution).

Feature Maps and Receptive Fields Across Depth

Linear Receptive-Field Growth in Stacked Layers

A unit’s receptive field is the region of the original input image whose pixels can influence that unit’s activation during forward propagation:

  • Single layer (L=1): A k_1 \times k_1 kernel sees a k_1 \times k_1 input patch.
  • Stacking L stride-1 layers: Layer i with kernel size k_i reaches k_i - 1 pixels farther along each axis than a single element of layer i-1: r = 1 + \sum_{i=1}^{L} (k_i - 1)
  • L stacked 3 \times 3 layers: Each layer adds 3 - 1 = 2 pixels, giving side length r = 2L + 1 (3 \to 5 \to 7).

Why Deep Stacks of 3×3 Kernels Beat One Large Kernel

Parameter Efficiency & Nonlinear Expressivity

  • Matched 7 \times 7 receptive field: Three stacked 3 \times 3 layers (r = 1 + 2 + 2 + 2 = 7) see the exact same 7 \times 7 patch as one 7 \times 7 layer.
  • 45% fewer parameters: 3 \times 9 c^2 = 27 c^2 weights instead of 49 c^2 across c channels.
  • Richer expressivity: Compounds 3 nonlinear activations instead of 1 (the core VGG design rule in §7.2).

Theoretical vs. Effective Receptive Fields

Gaussian Decay of Sensitivity Away from the Center

  • Theoretical RF (r = 2L+1): Bounding box of all pixels with at least one path to the output unit.
  • Central Limit Theorem: Center pixels connect via exponentially many paths, whereas corner pixels connect via only 1 path.
  • Effective RF (Luo et al., 2016): Input gradient magnitude \partial y / \partial \mathbf{X} decays in a Gaussian bell curve with std \sigma \propto \sqrt{L}.

Concept Check: Cross-Correlation & Receptive Fields

Concept Check

Test your understanding of output shapes, im2col, and receptive-field arithmetic:

  1. im2col matrix dimensions: You apply an unpadded 3 \times 3 single-channel kernel to a 10 \times 10 image via im2col. What is the output spatial shape, and what are the exact dimensions of the patches matrix and flattened kernel vector?
  2. Depth to span Fashion-MNIST: At stride 1, how many stacked 3 \times 3 layers are required so a single unit’s theoretical receptive field spans an entire 28 \times 28 image? How many with 5 \times 5 layers?
  3. Edge-loss boundary shift: In our 6 \times 8 vertical-edge learning experiment, why did the loss start at \approx 12, and what would the initial loss be if the black band extended all the way to the right edge (X[:, 2:8] = 0)?

Answers: (1) Output shape is (10-3+1) \times (10-3+1) = 8 \times 8 (64 outputs). The patches matrix has shape (64, 9) and multiplies the (9, 1) kernel vector. (2) For 3 \times 3: 2L + 1 \ge 28 \implies L = 14 layers. For 5 \times 5: 4L + 1 \ge 28 \implies L = 7 layers. (3) Each of the 6 rows had two \pm 1 edges (6 \times 2 \times 1^2 = 12). Extending the black band to the right border eliminates the right-hand black-to-white edge, leaving one edge per row and halving the initial loss to \approx 6.

Summary & Key Takeaways

Section Synthesis

  • 2D Cross-Correlation & Edge Learning: Slides \mathbf{K} across valid windows ((n_\textrm{h}-k_\textrm{h}+1)\times(n_\textrm{w}-k_\textrm{w}+1)); SGD learns [1, -1] in 9 steps.
  • im2col Matrix Multiply: Trades k_\textrm{h} k_\textrm{w}\times patch duplication for peak GPU GEMM throughput.
  • Stacked Receptive Fields: r = 1 + \sum (k_i - 1) = 2L+1 for 3 \times 3 stacks, with Gaussian center sensitivity.