18  Lab 5: CNNs, ResNets, and Augmentation

From local filters to a tested residual classifier

18.1 Lab contract

A flattened image classifier can learn a separate detector for every position. How do shared local filters change this computation, and what do they actually guarantee? Work through the examples below alongside the concepts chapter. The additional material develops the gradient, receptive-field, and computational-cost arguments further.

Run the cells from top to bottom in a fresh kernel. Everything uses small CPU tensors and generated images; no dataset downloads or pretrained weights are needed. Sections 1–8 are component investigations; Section 9 combines the components into a controlled training experiment. Allow about 90–120 minutes, with the extensions as independent practice.

ImportantPredict before executing

For each investigation, write down the expected shape or numerical behavior before running the cell. For the training experiment, record the hypothesis before inspecting accuracy. Assertions check specific mathematical properties; an accuracy difference is an empirical observation.

18.2 1. A convolution is a shared local calculation

PyTorch uses tensors in NCHW order: batch, channels, height, width. Reproduce the chapter’s numerical example with explicit patch multiplication, then compare it with conv2d. The kernel is applied directly, without flipping it: this is cross-correlation.

import copy

import matplotlib.pyplot as plt
import torch
from torch import nn
from torch.nn import functional as F

def count_parameters(model):
    return sum(parameter.numel() for parameter in model.parameters())


torch.manual_seed(51)

image = torch.tensor([[1., 1., 0.], [1., 0., 0.], [1., 1., 1.]])
kernel = torch.tensor([[1., -1.], [1., -1.]])
manual = torch.empty(2, 2)
for row in range(2):
    for col in range(2):
        patch = image[row:row + 2, col:col + 2]
        manual[row, col] = (patch * kernel).sum()

library = F.conv2d(image[None, None], kernel[None, None])
torch.testing.assert_close(manual, torch.tensor([[1., 1.], [1., 0.]]))
torch.testing.assert_close(library[0, 0], manual)
print("Feature map:\n", manual)
Feature map:
 tensor([[1., 1.],
        [1., 0.]])

Try it. Add a bias of 2, then use kernel.flip((0, 1)). Predict which outputs change. Explain why sharing the same kernel across all patches differs from assigning each patch independent weights.

18.3 2. Shapes, parameters, computation, and receptive fields

The output-size formula applies independently to each spatial dimension. Here we use square inputs and symmetric settings to keep the code short. Count a multiply followed by accumulation as one MAC; omit bias additions from that count.

def output_size(size, kernel_size, stride=1, padding=0, dilation=1):
    return (size + 2 * padding - dilation * (kernel_size - 1) - 1) // stride + 1

x = torch.randn(2, 3, 32, 32)
for k, s, p, d in [(3, 1, 1, 1), (3, 2, 1, 1), (3, 1, 2, 2)]:
    layer = nn.Conv2d(3, 8, k, stride=s, padding=p, dilation=d)
    y = layer(x)
    side = output_size(32, k, s, p, d)
    expected_parameters = 8 * 3 * k * k + 8
    macs_per_image = side * side * 8 * 3 * k * k
    assert y.shape == (2, 8, side, side)
    assert count_parameters(layer) == expected_parameters
    print(f"k={k}, s={s}, p={p}, d={d}: {tuple(y.shape)}, "
          f"parameters={expected_parameters}, MACs/image={macs_per_image:,}")

# Track the theoretical receptive-field bounding box and output spacing.
receptive_field, jump = 1, 1
for k, s, d in [(3, 1, 1), (3, 2, 1), (3, 1, 2)]:
    receptive_field += (k - 1) * d * jump
    jump *= s
    print(f"receptive field={receptive_field}, jump={jump}")
assert (receptive_field, jump) == (13, 2)
k=3, s=1, p=1, d=1: (2, 8, 32, 32), parameters=224, MACs/image=221,184
k=3, s=2, p=1, d=1: (2, 8, 16, 16), parameters=224, MACs/image=55,296
k=3, s=1, p=2, d=2: (2, 8, 32, 32), parameters=224, MACs/image=221,184
receptive field=3, jump=1
receptive field=5, jump=2
receptive field=13, jump=2

Explain. The first and third convolutions have equal parameter counts. Why can their receptive fields differ? Why does halving output height and width reduce this layer’s MAC count by roughly four? A receptive-field bounding box does not imply every enclosed pixel is sampled, particularly with dilation.

18.4 3. Translation equivariance has conditions

Use circular padding and a circular shift to remove boundary mismatch. A stride-1 convolution commutes with this shift. A stride-2 convolution only aligns with input shifts that are multiples of its stride.

spatial = torch.randn(1, 1, 12, 12)
weights = torch.randn(2, 1, 3, 3)

def circular_conv(values, stride=1):
    padded = F.pad(values, (1, 1, 1, 1), mode="circular")
    return F.conv2d(padded, weights, stride=stride)

shifted = spatial.roll(1, dims=-1)
features = circular_conv(spatial)
torch.testing.assert_close(circular_conv(shifted), features.roll(1, dims=-1))
# Global averaging removes this circular spatial permutation.
torch.testing.assert_close(
    circular_conv(shifted).mean((-2, -1)), features.mean((-2, -1))
)
downsampled = circular_conv(spatial, stride=2)
torch.testing.assert_close(
    circular_conv(spatial.roll(2, dims=-1), stride=2),
    downsampled.roll(1, dims=-1),
)
print("One-pixel input shift with stride 2, maximum change:",
      (circular_conv(shifted, stride=2) - downsampled).abs().max().item())

# Circular input shifts and zero padding have incompatible boundary rules.
zero_original = F.conv2d(spatial, weights, padding=1)
zero_shifted = F.conv2d(shifted, weights, padding=1)
print("Zero-padding boundary mismatch:",
      (zero_shifted - zero_original.roll(1, dims=-1)).abs().max().item())
One-pixel input shift with stride 2, maximum change: 10.370285987854004
Zero-padding boundary mismatch: 2.849355697631836

Explain. Which equality expresses equivariance? Which expresses invariance? Why do these checks establish neither exact translation invariance nor robustness for a complete classifier with ordinary padding and downsampling?

18.5 4. Backpropagation accumulates shared-weight contributions

Every location using a shared weight contributes to its gradient. The upstream gradient need not be 1: it is determined by the later computation. Check both the weight and input gradients using a nonuniform upstream tensor.

values = torch.tensor([[[1., 2., 3., 4.]]], requires_grad=True)
shared_weights = torch.tensor([[[2., -1.]]], requires_grad=True)
responses = F.conv1d(values, shared_weights)
upstream = torch.tensor([[[1., -2., 3.]]])
(responses * upstream).sum().backward()

patches = values.detach().unfold(-1, 2, 1)
manual_dw = (patches * upstream.unsqueeze(-1)).sum((0, 1, 2))
manual_dx = torch.zeros_like(values)
for position in range(3):
    manual_dx[..., position:position + 2] += (
        upstream[..., position:position + 1] * shared_weights.detach()
    )
torch.testing.assert_close(shared_weights.grad[0, 0], manual_dw)
torch.testing.assert_close(values.grad, manual_dx)
print("Weight gradient:", shared_weights.grad.flatten().tolist())
print("Input gradient:", values.grad.flatten().tolist())
Weight gradient: [6.0, 8.0]
Input gradient: [2.0, -5.0, 8.0, -3.0]

Checkpoint. Calculate the two weight derivatives on paper. Then replace += with = in the input-gradient loop. Explain why overlapping windows make assignment incorrect. The additional material extends this calculation to two dimensions.

18.6 5. Pooling, channel mixing, and normalization

18.6.1 Pooling routes gradients differently

There are no ties in this example. Max pooling routes the upstream gradient to the selected maximum; average pooling divides it equally among the four inputs.

patch = torch.tensor([[[[1., 4.], [2., 3.]]]], requires_grad=True)
max_gradient, = torch.autograd.grad(F.max_pool2d(patch, 2).sum(), patch)
avg_gradient, = torch.autograd.grad(F.avg_pool2d(patch, 2).sum(), patch)
torch.testing.assert_close(max_gradient, torch.tensor([[[[0., 1.], [0., 0.]]]]))
torch.testing.assert_close(avg_gradient, torch.full_like(patch, 0.25))
print("Max-pooling gradient:\n", max_gradient)
print("Average-pooling gradient:\n", avg_gradient)
Max-pooling gradient:
 tensor([[[[0., 1.],
          [0., 0.]]]])
Average-pooling gradient:
 tensor([[[[0.2500, 0.2500],
          [0.2500, 0.2500]]]])

18.6.2 A 1 × 1 convolution mixes channels at each location

Compare the layer with an explicit channelwise linear map. Global average pooling then produces one scalar per channel, regardless of the spatial input size.

channel_map = nn.Conv2d(3, 5, kernel_size=1)
channel_input = torch.randn(2, 3, 7, 9)
channel_output = channel_map(channel_input)
explicit = torch.einsum("oc,nchw->nohw", channel_map.weight[:, :, 0, 0], channel_input)
explicit = explicit + channel_map.bias[None, :, None, None]
torch.testing.assert_close(channel_output, explicit)
pooled = F.adaptive_avg_pool2d(channel_output, 1).flatten(1)
assert pooled.shape == (2, 5)
torch.testing.assert_close(pooled, channel_output.mean((-2, -1)))
print("Flattened head weights:", 5 * 7 * 9 * 2)
print("Global-average head weights:", 5 * 2)
Flattened head weights: 630
Global-average head weights: 10

Explain. Why can this 1 × 1 convolution neither compare neighboring pixels nor enlarge the spatial receptive field? What spatial information does averaging discard?

18.6.3 Batch normalization changes between training and evaluation

Training uses current batch statistics; evaluation uses stored running estimates. We set momentum to 1 here only to make the update visible after one batch. The variance stored for evaluation uses an unbiased estimate, whereas the training normalization uses the biased batch variance, so identical inputs need not yield identical outputs between modes.

bn = nn.BatchNorm2d(3, momentum=1.0)
batch = 3 + 2 * torch.randn(4, 3, 6, 6)
bn.train()
train_output = bn(batch)
torch.testing.assert_close(train_output.mean((0, 2, 3)), torch.zeros(3), atol=1e-6, rtol=0)
running_mean = bn.running_mean.clone()
bn.eval()
with torch.no_grad():
    eval_output = bn(batch)
    changed_batch = bn(batch + 5)
torch.testing.assert_close(bn.running_mean, running_mean)
assert not torch.allclose(changed_batch.mean((0, 2, 3)), torch.zeros(3))
print("Train/eval difference on the same batch:",
      (train_output - eval_output).abs().max().item())
print("Stored mean:", running_mean.tolist())
Train/eval difference on the same batch: 0.010152816772460938
Stored mean: [3.349945068359375, 2.868626117706299, 3.0441787242889404]

Try it. Replace BatchNorm2d(3) with GroupNorm(1, 3). Does changing the other examples in a batch alter the normalized output of the first example? Keep learned parameters fixed while comparing.

18.7 6. Grouped, dilated, and transposed convolution

Depthwise convolution gives each input channel its own spatial filter. A following 1 × 1 convolution mixes their outputs. This changes the parameterization; it is not generally equivalent to an arbitrary dense convolution.

dense = nn.Conv2d(8, 16, 3, padding=1, bias=False)
depthwise = nn.Conv2d(8, 8, 3, padding=1, groups=8, bias=False)
pointwise = nn.Conv2d(8, 16, 1, bias=False)
variant_input = torch.randn(2, 8, 12, 12)
assert dense(variant_input).shape == pointwise(depthwise(variant_input)).shape
print("Dense weights:", count_parameters(dense))
print("Depthwise + pointwise weights:",
      count_parameters(depthwise) + count_parameters(pointwise))
assert count_parameters(dense) == 1152
assert count_parameters(depthwise) + count_parameters(pointwise) == 200

# An impulse reveals dilation's sparse sampling pattern.
impulse = torch.zeros(1, 1, 9, 9)
impulse[0, 0, 4, 4] = 1
for dilation in (1, 2):
    response = F.conv2d(impulse, torch.ones(1, 1, 3, 3),
                        padding=dilation, dilation=dilation)
    locations = response[0, 0].nonzero()
    print(f"Dilation {dilation}: nonzero coordinates {locations.tolist()}")

# Upsampling restores a shape, not information discarded by downsampling.
select = torch.ones(1, 1, 1, 1)
original = torch.arange(16.).reshape(1, 1, 4, 4)
small = F.conv2d(original, select, stride=2)
expanded = F.conv_transpose2d(small, select, stride=2, output_padding=1)
assert expanded.shape == original.shape
assert not torch.equal(expanded, original)
print("After downsampling and transposed convolution:\n", expanded[0, 0])
Dense weights: 1152
Depthwise + pointwise weights: 200
Dilation 1: nonzero coordinates [[3, 3], [3, 4], [3, 5], [4, 3], [4, 4], [4, 5], [5, 3], [5, 4], [5, 5]]
Dilation 2: nonzero coordinates [[2, 2], [2, 4], [2, 6], [4, 2], [4, 4], [4, 6], [6, 2], [6, 4], [6, 6]]
After downsampling and transposed convolution:
 tensor([[ 0.,  0.,  2.,  0.],
        [ 0.,  0.,  0.,  0.],
        [ 8.,  0., 10.,  0.],
        [ 0.,  0.,  0.,  0.]])

Try it. Perturb only channel 0 of variant_input. Verify that only channel 0 changes immediately after the depthwise layer. Can more channels change after the pointwise layer?

18.8 7. Build residual blocks that handle stage transitions

This is a post-activation basic block: convolution–normalization–ReLU–convolution–normalization, followed by shortcut addition and ReLU. A projection shortcut aligns both channels and spatial resolution when entering a new stage. Addition requires identical branch shapes; concatenation would increase the channel count instead.

class ResidualBlock(nn.Module):
    def __init__(self, in_channels, out_channels, stride=1):
        super().__init__()
        self.branch = nn.Sequential(
            nn.Conv2d(in_channels, out_channels, 3, stride=stride, padding=1, bias=False),
            nn.BatchNorm2d(out_channels),
            nn.ReLU(),
            nn.Conv2d(out_channels, out_channels, 3, padding=1, bias=False),
            nn.BatchNorm2d(out_channels),
        )
        self.shortcut = (
            nn.Identity() if stride == 1 and in_channels == out_channels else
            nn.Sequential(
                nn.Conv2d(in_channels, out_channels, 1, stride=stride, bias=False),
                nn.BatchNorm2d(out_channels),
            )
        )

    def forward(self, inputs):
        correction = self.branch(inputs)
        shortcut = self.shortcut(inputs)
        assert correction.shape == shortcut.shape
        return F.relu(shortcut + correction)

for in_c, out_c, stride, side in [(8, 8, 1, 16), (8, 16, 2, 8)]:
    block = ResidualBlock(in_c, out_c, stride)
    block_input = torch.randn(2, in_c, 16, 16, requires_grad=True)
    block_output = block(block_input)
    assert block_output.shape == (2, out_c, side, side)
    block_output.square().mean().backward()
    assert block_input.grad is not None and torch.isfinite(block_input.grad).all()
    assert all(p.grad is not None and torch.isfinite(p.grad).all() for p in block.parameters())
    print(f"{in_c} -> {out_c}, stride {stride}: {count_parameters(block):,} parameters")

# With a zero correction, this post-activation block gives ReLU(x).
zero_block = ResidualBlock(8, 8).eval()
with torch.no_grad():
    zero_block.branch[-1].weight.zero_()
    zero_block.branch[-1].bias.zero_()
    signed_input = torch.randn(2, 8, 4, 4)
    torch.testing.assert_close(zero_block(signed_input), signed_input.relu())
8 -> 8, stride 1: 1,184 parameters
8 -> 16, stride 2: 3,680 parameters

Checkpoint. Why is the final check ReLU(x) rather than x? Write down which activation derivatives can still suppress gradients despite the shortcut.

18.9 8. Isolate the direct gradient path

Use scalar linear branches to isolate a mathematical mechanism. These are deliberately simpler than the nonlinear blocks above. With a branch derivative of 0.1, the plain chain multiplies by \(0.1^L\); the residual chain multiplies by \(1.1^L\).

for depth in (1, 5, 20):
    plain_input = torch.tensor(1., dtype=torch.float64, requires_grad=True)
    residual_input = torch.tensor(1., dtype=torch.float64, requires_grad=True)
    plain, residual = plain_input, residual_input
    for _ in range(depth):
        plain = 0.1 * plain
        residual = residual + 0.1 * residual
    plain.backward()
    residual.backward()
    torch.testing.assert_close(plain_input.grad, plain_input.new_tensor(0.1**depth))
    torch.testing.assert_close(residual_input.grad, residual_input.new_tensor(1.1**depth))
    print(f"depth={depth}: plain gradient={plain_input.grad.item():.3e}, "
          f"residual gradient={residual_input.grad.item():.3e}")
depth=1: plain gradient=1.000e-01, residual gradient=1.100e+00
depth=5: plain gradient=1.000e-05, residual gradient=1.611e+00
depth=20: plain gradient=1.000e-20, residual gradient=6.727e+00

This calculation explains a direct path; it does not prove that arbitrary ResNets avoid vanishing or exploding gradients. Here even the residual chain grows with depth. Try branch derivatives of -1 and 1 to expose cancellation and growth.

18.10 9. Controlled experiment: does translation augmentation help?

18.10.1 Data pipeline and hypothesis

Classify horizontal versus vertical bars. Training images place the bar near the center; shifted evaluation images place it nearer an edge. Small translations preserve this task’s labels, whereas a 90-degree rotation would exchange them. This generated task is a diagnostic, not a substitute for a natural-image benchmark.

Field Configuration
Hypothesis Training translations improve shifted-set accuracy; a CNN may already generalize well without them.
Independent variable Random integer translation during training, on/off
Fixed controls Initial weights within each seed, data, batches, optimizer, updates, architecture
Primary metric Accuracy on a held-out shifted set
Secondary diagnostics Centered accuracy, shifted cross-entropy, loss curve, confusion matrix
Repetitions Seeds 51, 52, 53; report each pair and the mean
Stopping rule Exactly 40 full-batch updates; no evaluation-based model selection

Keep evaluation sets fixed and unaugmented. If you tune settings after inspecting these sets, treat them as validation sets and generate a new final test set.

def make_bars(n, *, shifted, seed):
    generator = torch.Generator().manual_seed(seed)
    labels = torch.arange(n) % 2
    images = 0.08 * torch.randn(n, 1, 16, 16, generator=generator)
    for index, label in enumerate(labels.tolist()):
        if shifted:
            center = int(torch.randint(3, 5, (), generator=generator))
            if index % 4 < 2:
                center = 15 - center
        else:
            center = int(torch.randint(7, 9, (), generator=generator))
        if label == 0:
            images[index, 0, center - 1:center + 1, 4:12] += 1
        else:
            images[index, 0, 4:12, center - 1:center + 1] += 1
    return images, labels.long()

train_x, train_y = make_bars(96, shifted=False, seed=501)
center_x, center_y = make_bars(96, shifted=False, seed=502)
shift_x, shift_y = make_bars(96, shifted=True, seed=503)
assert train_x.shape == (96, 1, 16, 16)
assert train_y.dtype == torch.long

def translate_batch(images, generator, max_shift=4):
    # Zero-filled translations; never wrap pixels across opposite borders.
    result = torch.zeros_like(images)
    height, width = images.shape[-2:]
    offsets = torch.randint(-max_shift, max_shift + 1, (len(images), 2), generator=generator)
    for i, (dy, dx) in enumerate(offsets.tolist()):
        y0, y1 = max(0, dy), min(height, height + dy)
        x0, x1 = max(0, dx), min(width, width + dx)
        result[i, :, y0:y1, x0:x1] = images[i, :, y0-dy:y1-dy, x0-dx:x1-dx]
    return result

# These bars stay inside the frame under shifts up to four pixels.
clean_bars = torch.zeros_like(train_x)
clean_bars[train_x > 0.5] = 1
torch.testing.assert_close(
    translate_batch(clean_bars, torch.Generator().manual_seed(1)).sum((1, 2, 3)),
    clean_bars.sum((1, 2, 3)),
)

18.10.2 Architecture and objective

Build a small residual classifier with two stages, global average pooling, and two output logits. CrossEntropyLoss combines log-softmax with negative log-likelihood; do not put a softmax layer before it.

class TinyResNet(nn.Module):
    def __init__(self):
        super().__init__()
        self.stem = nn.Sequential(
            nn.Conv2d(1, 8, 3, padding=1, bias=False),
            nn.BatchNorm2d(8),
            nn.ReLU(),
        )
        self.stage1 = ResidualBlock(8, 8)
        self.stage2 = ResidualBlock(8, 16, stride=2)
        self.pool = nn.AdaptiveAvgPool2d(1)
        self.head = nn.Linear(16, 2)

    def forward(self, inputs):
        features = self.stage2(self.stage1(self.stem(inputs)))
        return self.head(self.pool(features).flatten(1))

shape_model = TinyResNet().eval()
with torch.no_grad():
    trace = train_x[:2]
    for name in ("stem", "stage1", "stage2", "pool"):
        trace = getattr(shape_model, name)(trace)
        print(name, tuple(trace.shape))
    assert shape_model(train_x[:2]).shape == (2, 2)
print("Classifier parameters:", count_parameters(shape_model))
stem (2, 8, 16, 16)
stage1 (2, 8, 16, 16)
stage2 (2, 16, 8, 8)
pool (2, 16, 1, 1)
Classifier parameters: 4986

18.10.3 Optimizer and evaluation

Each paired run starts with exactly the same state, including normalization buffers. The augmentation uses its own random generator. Evaluation switches off training behavior and records metrics without gradients.

def evaluate(model, images, labels):
    model.eval()
    with torch.no_grad():
        logits = model(images)
        predictions = logits.argmax(1)
        confusion = torch.bincount(2 * labels + predictions, minlength=4).reshape(2, 2)
        return {
            "accuracy": (predictions == labels).float().mean().item(),
            "loss": F.cross_entropy(logits, labels).item(),
            "confusion": confusion,
        }

results = []
# Small CPU convolutions can be slower with large thread pools.
previous_threads = torch.get_num_threads()
torch.set_num_threads(1)
try:
    for seed in (51, 52, 53):
        torch.manual_seed(seed)
        initial = TinyResNet()
        for augment in (False, True):
            model = copy.deepcopy(initial)
            optimizer = torch.optim.Adam(model.parameters(), lr=0.01, weight_decay=1e-4)
            generator = torch.Generator().manual_seed(seed + 1000)
            losses = []
            for step in range(40):
                model.train()
                batch = translate_batch(train_x, generator) if augment else train_x
                optimizer.zero_grad(set_to_none=True)
                logits = model(batch)
                loss = F.cross_entropy(logits, train_y)
                assert torch.isfinite(loss)
                loss.backward()
                assert all(p.grad is not None and torch.isfinite(p.grad).all()
                           for p in model.parameters())
                optimizer.step()
                losses.append(loss.item())
            centered = evaluate(model, center_x, center_y)
            shifted = evaluate(model, shift_x, shift_y)
            results.append(dict(seed=seed, augment=augment, losses=losses,
                                centered=centered, shifted=shifted))
finally:
    torch.set_num_threads(previous_threads)

print("seed | augmented | centered accuracy | shifted accuracy | shifted CE")
for run in results:
    print(f"{run['seed']} | {str(run['augment']):9} | "
          f"{run['centered']['accuracy']:.3f} | {run['shifted']['accuracy']:.3f} | "
          f"{run['shifted']['loss']:.3f}")
for augment in (False, True):
    accuracies = torch.tensor([r["shifted"]["accuracy"] for r in results if r["augment"] == augment])
    print(f"Augmented={augment}: mean shifted accuracy={accuracies.mean():.3f}, "
          f"sample SD={accuracies.std():.3f}")
print("Shifted confusion matrix for the final run (rows=true, columns=predicted):")
print(results[-1]["shifted"]["confusion"])
seed | augmented | centered accuracy | shifted accuracy | shifted CE
51 | False     | 1.000 | 1.000 | 0.006
51 | True      | 1.000 | 1.000 | 0.004
52 | False     | 1.000 | 1.000 | 0.006
52 | True      | 1.000 | 1.000 | 0.003
53 | False     | 1.000 | 1.000 | 0.011
53 | True      | 1.000 | 1.000 | 0.005
Augmented=False: mean shifted accuracy=1.000, sample SD=0.000
Augmented=True: mean shifted accuracy=1.000, sample SD=0.000
Shifted confusion matrix for the final run (rows=true, columns=predicted):
tensor([[48,  0],
        [ 0, 48]])
fig, axes = plt.subplots(1, 2, figsize=(10, 3.5))
for run in results:
    color = "C1" if run["augment"] else "C0"
    label = ("translations" if run["augment"] else "no augmentation") if run["seed"] == 51 else None
    axes[0].plot(range(1, 41), run["losses"], color=color, alpha=0.65, label=label)
for seed in (51, 52, 53):
    pair = [r["shifted"]["accuracy"] for r in results if r["seed"] == seed]
    axes[1].plot([0, 1], pair, "o-", label=f"seed {seed}")
axes[0].set(xlabel="Update", ylabel="Training cross-entropy")
axes[1].set(xticks=[0, 1], xticklabels=["No augmentation", "Translations"],
            ylabel="Shifted-set accuracy", ylim=(-0.02, 1.02))
for ax in axes:
    ax.legend()
fig.tight_layout()
plt.show()
Loss curves for three seeds with and without translation augmentation, beside paired shifted-set accuracies.
Figure 18.1: Training loss and held-out accuracy for paired translation-augmentation runs. Training loss uses different input distributions in the two conditions.

Interpret. Report the paired change for each seed. Does the experiment support the prediction, or does the unaugmented CNN already solve the task? Distinguish sensitivity to initialization from uncertainty due to sampling a new dataset. Use the confusion matrix to check whether errors concentrate in one class. Training loss alone is not comparable evidence of generalization when one condition receives harder augmented inputs.

18.11 Exercises and submission

  1. Mechanics: Extend the manual cross-correlation to two input channels and two output channels, including biases. Check it against F.conv2d and explain which dimensions are summed.
  2. Architecture: Change the stage-transition stride to 1. Predict the activation shapes, parameter count, and computation before execution. Explain why parameter count alone is insufficient to compare cost.
  3. Verification: Break the projection shortcut deliberately. Record the failing shape check, then repair it. Retain the gradient and zero-correction checks.
  4. Controlled comparison: Replace the shortcut addition with a plain branch, keeping branch layers and the update budget fixed. Document the projection and parameter-count differences. Do not change augmentation in the same comparison.
  5. Robustness: Evaluate brightness or noise changes on a newly generated held-out set. Separate this experiment from the translation comparison. Explain why augmentation for one shift may not cover another.
  6. Stretch: Visualize stem feature maps of trained models for each bar orientation, or compute input gradients of a class logit. Describe these as model responses, with no guarantee of causal feature importance.

Submit the executable notebook, component checks, configuration and result table, and a 150–300 word interpretation including one alternative explanation. Include one worked derivation from the additional material. State each student’s individual contribution.