Chapter 16 — Assignment Project: Rescuing a Training Run
Overview¶
A colleague’s network does not learn. Their configuration is below: a deep network of sigmoid units with a tiny initialisation, trained with plain SGD at a large rate. Your job is to find out why, fix it one change at a time with evidence for each change, and then make the fixed network generalise from a small, noisy training set. Everything runs on CPU in a few minutes, on scikit-learn’s digits.
| Part | Task | Points |
|---|---|---|
| A | Diagnose the broken run | 15 |
| B | Fix the initialisation and the activations | 20 |
| C | Choose the optimiser and the learning rate | 20 |
| D | Make it generalise | 25 |
| E | Report | 20 |
import copy
import math
import numpy as np
import torch
import torch.nn as nn
import matplotlib.pyplot as plt
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
X, y = load_digits(return_X_y=True)
X_dev, X_test, y_dev, y_test = train_test_split(X / 16, y, test_size=0.25, random_state=0, stratify=y)
X_tr, X_va, y_tr, y_va = train_test_split(X_dev, y_dev, test_size=0.25, random_state=1, stratify=y_dev)
T = lambda a, dt=torch.float32: torch.tensor(a, dtype=dt)
X_tr, X_va, X_test = T(X_tr), T(X_va), T(X_test)
y_tr, y_va, y_test = T(y_tr, torch.long), T(y_va, torch.long), T(y_test, torch.long)
print(f'training {len(y_tr)}, validation {len(y_va)}, test {len(y_test)} (use the test set only in Part D)')
def build(depth=10, width=64, act=nn.Sigmoid, init_std=0.01, bn=False, drop=0.0):
"""The colleague's network builder: depth hidden layers of width units."""
layers, n = [], 64
for _ in range(depth):
lin = nn.Linear(n, width)
if init_std == 'he':
nn.init.kaiming_normal_(lin.weight, nonlinearity='relu')
else:
nn.init.normal_(lin.weight, 0.0, init_std)
nn.init.zeros_(lin.bias)
layers += [lin] + ([nn.BatchNorm1d(width)] if bn else []) + [act()] + ([nn.Dropout(drop)] if drop else [])
n = width
return nn.Sequential(*layers, nn.Linear(n, 10))
def run(net, opt, Xt, yt, epochs=30, batch=64, clip=None, seed=0):
"""Train; return the history of training loss, validation loss and accuracy, and gradient norm per epoch."""
g = torch.Generator().manual_seed(seed); loss_fn = nn.CrossEntropyLoss()
h = {'loss': [], 'val_loss': [], 'val_acc': [], 'gnorm': []}
for ep in range(epochs):
net.train(); norms = []
for idx in torch.randperm(len(Xt), generator=g).split(batch):
opt.zero_grad(); loss = loss_fn(net(Xt[idx]), yt[idx]); loss.backward()
norms.append(float(nn.utils.clip_grad_norm_(net.parameters(), clip or float('inf')))); opt.step()
net.eval()
with torch.no_grad():
h['loss'].append(float(loss_fn(net(Xt), yt))); zv = net(X_va)
h['val_loss'].append(float(loss_fn(zv, y_va))); h['val_acc'].append(float((zv.argmax(1) == y_va).float().mean()))
h['gnorm'].append(float(np.mean(norms)))
return h
torch.manual_seed(0)
broken = build()
h_broken = run(broken, torch.optim.SGD(broken.parameters(), lr=2.0), X_tr, y_tr)
print(f'the colleague\'s run: training loss {h_broken["loss"][0]:.3f} -> {h_broken["loss"][-1]:.3f}, validation accuracy {h_broken["val_acc"][-1]:.3f}')Part A — Diagnose (15 points)¶
Plot the broken run’s training and validation loss. What value does the loss sit at, and what does that value mean?
Compute, at initialisation, the gradient norm of each
nn.Linearlayer’s weights on one batch of 256 training images. Plot it against the layer’s depth on a log scale.In three sentences: what is wrong, and why does a learning rate of 2.0 not rescue it?
# Your code hereYour diagnosis:
Part B — Fix the Initialisation and the Activations (20 points)¶
Change one thing at a time, and for each version report the gradient norms of the first and last layers at initialisation and the validation accuracy after 30 epochs (SGD at 0.03 with momentum 0.9):
sigmoid, Xavier-like initialisation (
init_std = 1 / sqrt(64));ReLU, He initialisation (
act=nn.ReLU, init_std='he');ReLU, He initialisation, with batch normalisation.
Which change mattered most? Justify with the numbers.
# Your code hereYour comparison:
Part C — Optimiser and Learning Rate (20 points)¶
Keep the best network of Part B.
Run a learning-rate range test with SGD and momentum (rates from 10-4 to 10, multiplied after every batch) and choose a rate.
Compare SGD with momentum at your rate, and Adam at 10-3, each with three seeds (the initialisation and the batch order change). Report the mean and the spread of the validation accuracy after 20 epochs.
Is the difference between them larger than the spread between seeds?
# Your code hereYour answer:
Part D — Make It Generalise (25 points)¶
The data you will get in practice are small and noisy. Build a training set of the first 250 training images, and replace 25% of their labels by random ones (seed 7).
With 250 images, ten layers are far too many: use two hidden layers of 256 ReLU units with He initialisation, no batch normalisation (
build(depth=2, width=256, act=nn.ReLU, init_std='he')), and AdamW at 0^{-3}$. Train it for 150 epochs (batches of 32): without regularisation, with dropout 0.5, with weight decay 0.5, and with both. Plot the validation loss of each.Add early stopping (patience 15, restore the best weights) to the best of them.
Evaluate your final model on the test set, once, and give its accuracy.
# Your code hereYour comments:
Part E — Report (20 points)¶
One page for your colleague:
what was wrong with the original run, and the evidence (Part A);
the changes, in order, with the effect of each (Parts B and C);
what you did against overfitting and what each remedy contributed (Part D);
the test accuracy, and a sentence on how much to trust it;
the three checks you would run first on the next network that does not learn.
Grading Rubric¶
| Criterion | Excellent | Adequate | Insufficient |
|---|---|---|---|
| A (15) | loss at ln 10 explained, vanishing gradient shown by layer | one of the two | no evidence |
| B (20) | one change at a time, numbers for each, the main cause identified | changes made together | missing |
| C (20) | range test, three seeds, difference compared to the spread | one seed | rate guessed |
| D (25) | curves, early stopping with restored weights, test used once | no early stopping | test set used for choices |
| E (20) | clear, ordered, evidence for each claim, honest about uncertainty | generic | missing |