19  Additional Material: Convolution, Receptive Fields, and Augmentation

Derivations and numerical checks behind the CNN lab

The concepts chapter builds CNNs from shared local filters. The lab tests their behavior in code. This optional sheet asks why those computations work. Work through the exercises before opening the solutions. The code runs independently of the lab, from top to bottom, using only small CPU tensors.

19.1 Shared weights make gradients add up

For one example, consider valid, stride-1 cross-correlation with multiple channels:

\[ Z_{o,i,j}=b_o+\sum_c\sum_u\sum_v W_{o,c,u,v}X_{c,i+u,j+v}. \]

Let \(G_{o,i,j}=\partial L/\partial Z_{o,i,j}\) be the upstream gradient, after differentiating through any subsequent activation. The chain rule gives

\[ \frac{\partial L}{\partial W_{o,c,u,v}} =\sum_{i,j}G_{o,i,j}X_{c,i+u,j+v}, \qquad \frac{\partial L}{\partial b_o}=\sum_{i,j}G_{o,i,j}. \]

A batch adds a sum over examples as well. If the loss is a mean, its normalization is already included in \(G\); do not divide by the batch size a second time.

An input pixel participates in several output windows, so its gradient also accumulates:

\[ \frac{\partial L}{\partial X_{c,p,q}} =\sum_o\sum_{i,j}\sum_{u,v} G_{o,i,j}W_{o,c,u,v}\, \mathbf{1}\{p=i+u,\ q=j+v\}. \]

This form emphasizes the indexing: a contribution exists only when a window actually uses that input pixel. Padding, dilation, and stride change the index conditions, not the chain rule.

import torch
from torch.nn import functional as F

torch.manual_seed(551)
x = torch.randn(1, 2, 4, 4, dtype=torch.float64, requires_grad=True)
w = torch.randn(3, 2, 2, 2, dtype=torch.float64, requires_grad=True)
b = torch.randn(3, dtype=torch.float64, requires_grad=True)
z = F.conv2d(x, w, b)
g = torch.randn_like(z)
dx, dw, db = torch.autograd.grad((z * g).sum(), (x, w, b))

manual_dw = torch.zeros_like(w)
manual_dx = torch.zeros_like(x)
for i in range(z.shape[-2]):
    for j in range(z.shape[-1]):
        patch = x.detach()[0, :, i:i+2, j:j+2]
        for o in range(3):
            manual_dw[o] += g[0, o, i, j] * patch
            manual_dx[0, :, i:i+2, j:j+2] += g[0, o, i, j] * w.detach()[o]
torch.testing.assert_close(dw, manual_dw)
torch.testing.assert_close(dx, manual_dx)
torch.testing.assert_close(db, g.sum((0, 2, 3)))
print("Weight, input, and bias gradient checks passed.")
Weight, input, and bias gradient checks passed.

Exercise 1. For \(x=(1,2,3,4)\), \(w=(2,-1)\), valid 1D cross-correlation, and \(L=y_0-2y_1+3y_2\), calculate \(y\), \(\nabla_w L\), and \(\nabla_x L\).

The output is \((0,1,2)\), so \(L=4\). The upstream gradient is \((1,-2,3)\). Therefore

\[ \nabla_w L=(1-4+9,\;2-6+12)=(6,8). \]

Accumulating overlapping contributions gives

\[ \nabla_x L=(2,\;-1-4,\;2+6,\;-3)=(2,-5,8,-3). \]

The middle entries receive contributions from two windows. The forward outputs are not the upstream gradients: the loss determines those gradients.

19.2 Transposed convolution is an adjoint, not an inverse

With fixed weights and no bias, convolution is linear in its input. After flattening tensors, write it as \(y=Ax\). The input gradient is \(A^\top g\). A transposed convolution implements this adjoint operation with compatible shape settings:

\[ \langle Ax,g\rangle=\langle x,A^\top g\rangle. \]

An inverse would instead require \(A^{-1}Ax=x\). Downsampling can discard information, so the adjoint identity does not imply reconstruction.

# Even-sized input, stride 2: output_padding=1 selects the original input shape.
source = torch.randn(1, 2, 6, 6, dtype=torch.float64)
fixed_kernel = torch.randn(3, 2, 3, 3, dtype=torch.float64)
encoded = F.conv2d(source, fixed_kernel, stride=2, padding=1)
probe = torch.randn_like(encoded)
adjoint_probe = F.conv_transpose2d(
    probe, fixed_kernel, stride=2, padding=1, output_padding=1
)
assert adjoint_probe.shape == source.shape
torch.testing.assert_close((encoded * probe).sum(), (source * adjoint_probe).sum())
print("Adjoint inner-product identity verified.")
Adjoint inner-product identity verified.

Exercise 2. Let \(A=\begin{pmatrix}1&0&0&0\\0&0&1&0\end{pmatrix}\). Compute \(A^\top Ax\) for \(x=(1,2,3,4)^\top\). What does this say about a stride-2, size-1 convolution?

\(Ax=(1,3)^\top\) and \(A^\top Ax=(1,0,3,0)^\top\). The values at the unselected positions have disappeared. Many distinct inputs give the same output, so no decoder can uniquely recover those positions from \(Ax\) alone. Output padding resolves a shape choice; it does not restore discarded values.

19.3 Receptive fields: coverage and spacing

Let \(r_l\) denote the side length of the theoretical receptive-field bounding box at layer \(l\), and \(j_l\) the input-space distance between neighboring output centers. Starting with \(r_0=j_0=1\),

\[ r_l=r_{l-1}+(k_l-1)d_lj_{l-1}, \qquad j_l=s_lj_{l-1}. \]

A dilated kernel’s first and last samples are \((k_l-1)d_l\) positions apart on its input feature map. Multiplying by the previous spacing converts that distance into original-input coordinates. Padding affects alignment and border coverage; it does not change this bounding-box recurrence.

The theoretical receptive field is a set of possible dependencies. Learned weights, activation gates, and the input determine their actual influence. Near boundaries, some dependencies are on padding rather than image pixels. Dilation can leave unsampled holes within the bounding box.

Exercise 3. For three layers with \((k,s,d)=(3,1,1),(3,2,1),(3,1,2)\), calculate \((r,j)\) after each layer. Compare with replacing the second layer’s stride by 1.

The original sequence gives \((3,1)\), \((5,2)\), then \((13,2)\). With stride 1 throughout, it gives \((3,1)\), \((5,1)\), then \((9,1)\). Striding increases the spacing used by later kernels, which makes their receptive fields grow faster in input coordinates. It also discards intermediate spatial samples.

Verify a simpler bounding box using input gradients. Positive weights and a linear stack avoid ReLU gates or cancellation hiding dependencies.

field_input = torch.zeros(1, 1, 15, 15, requires_grad=True)
ones = torch.ones(1, 1, 3, 3)
field_output = F.conv2d(F.conv2d(field_input, ones), ones)
field_gradient, = torch.autograd.grad(field_output[0, 0, 5, 5], field_input)
support = field_gradient[0, 0].nonzero()
extent = support.max(0).values - support.min(0).values + 1
assert extent.tolist() == [5, 5]
assert len(support) == 25
print("Two size-3, stride-1 layers cover:", extent.tolist())
Two size-3, stride-1 layers cover: [5, 5]

19.4 Parameter efficiency and computational cost

Ignoring biases, a dense \(k\times k\) convolution requires \(k^2 C_{\mathrm{in}}C_{\mathrm{out}}\) weights. A depthwise convolution followed by a pointwise convolution requires

\[ k^2 C_{\mathrm{in}}+C_{\mathrm{in}}C_{\mathrm{out}}. \]

Their ratio is

\[ \frac{1}{C_{\mathrm{out}}}+\frac{1}{k^2}. \]

For equal output spatial sizes, this is also the ratio of their MAC counts under the same counting convention. It need not predict wall-clock speed: intermediate activations, memory traffic, and implementation overhead also matter.

The saving restricts the function class. With one depthwise filter per input channel and no intervening nonlinearity, the equivalent dense kernel factors as

\[ W_{o,c,u,v}=P_{o,c}D_{c,u,v}. \]

For a fixed input channel \(c\), every output channel uses a scaled version of the same spatial pattern \(D_c\). A general dense kernel does not have to satisfy this constraint.

Exercise 4. Compare weight counts for an \(8\to16\), \(3\times3\) dense convolution and its depthwise-plus-pointwise alternative. Calculate MACs if each produces \(12\times12\) output maps.

Dense: \(9\cdot8\cdot16=1152\) weights and \(144\cdot1152=165{,}888\) MACs. Separable: \(9\cdot8+8\cdot16=200\) weights and \(144\cdot200=28{,}800\) MACs. The ratio is \(200/1152\approx0.174\). These counts omit biases and normalization and assume the depthwise map also has spatial size \(12\times12\).

19.5 Augmentation encodes a task assumption

For an input-label pair \((x,y)\), augmentation samples a transformation \(T\) and trains on \((Tx,y)\). This is justified when \(T\) preserves the target meaning over the relevant input distribution. Its training objective is

\[ \mathbb E_{(x,y)}\mathbb E_T\big[\ell(f_\theta(Tx),y)\big]. \]

The expectation encourages performance across sampled transformations; it does not impose exact architectural invariance or establish performance under all distribution shifts. Cropping may remove the object, flipping may reverse text, and rotation may change an orientation label. The lab’s translations keep the complete bar inside the frame, so its label-preservation assumption is explicit.

Exercise 5. Why is a random 90-degree rotation invalid as a label-preserving augmentation for the horizontal-versus-vertical task? How could you still use it during training?

A 90-degree rotation swaps the two classes. Retaining the original label supplies incorrect supervision. Transform the label along with the image: swap horizontal and vertical for odd multiples of 90 degrees, and keep the label for multiples of 180 degrees. This uses known task structure rather than assuming every geometric transformation preserves the class.

For further reading and architecture references, return to the chapter’s selected resources. For experimental evidence, run the paired comparisons in the lab and distinguish exact mathematical checks from results on a small generated dataset.