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.
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 +1x = 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 * kassert y.shape == (2, 8, side, side)assert count_parameters(layer) == expected_parametersprint(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, 1for k, s, d in [(3, 1, 1), (3, 2, 1), (3, 1, 2)]: receptive_field += (k -1) * d * jump jump *= sprint(f"receptive field={receptive_field}, jump={jump}")assert (receptive_field, jump) == (13, 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.
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?
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.
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.
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.
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.
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.
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.
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\).
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 inenumerate(labels.tolist()):if shifted: center =int(torch.randint(3, 5, (), generator=generator))if index %4<2: center =15- centerelse: center =int(torch.randint(7, 9, (), generator=generator))if label ==0: images[index, 0, center -1:center +1, 4:12] +=1else: images[index, 0, 4:12, center -1:center +1] +=1return 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.longdef 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) inenumerate(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] =1torch.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.
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 inrange(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()assertall(p.grad isnotNoneand 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"])
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"] ==51elseNone 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()
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
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.
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.
Verification: Break the projection shortcut deliberately. Record the failing shape check, then repair it. Retain the gradient and zero-correction checks.
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.
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.
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.