Part 11 / Stage 3
Training well
Goal: Get networks to train, and to generalise: optimizers, learning rates, regularization, early stopping, and how to debug a run. Time: ~3 hours · Needs: Part 10
What you will learn
- Optimizers: SGD, momentum, Adam, AdamW
- The learning rate — the knob that decides everything
- Regularizing networks: weight decay, dropout, augmentation
- Normalization: BatchNorm and LayerNorm
- Early stopping
- Debugging training: overfit one batch first
Topics in this part
Practice
Exercise 1: Optimizer bake-off
Train the digits MLP for 10 epochs with SGD (lr=0.01), SGD+momentum (0.9), and Adam (1e-3) — same seed, same data. Print test accuracy for each.
Show the solution to Exercise 1
# Exercise 1: Optimizer bake-off
import torch
from torch import nn
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
X, y = load_digits(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X / 16.0, y, test_size=0.2, random_state=0, stratify=y)
X_tr, X_te = torch.tensor(X_tr, dtype=torch.float32), torch.tensor(X_te, dtype=torch.float32)
y_tr, y_te = torch.tensor(y_tr), torch.tensor(y_te)
def run(make_opt):
torch.manual_seed(0)
model = nn.Sequential(nn.Linear(64, 64), nn.ReLU(), nn.Linear(64, 10))
opt = make_opt(model.parameters())
loader = torch.utils.data.DataLoader(
torch.utils.data.TensorDataset(X_tr, y_tr), batch_size=64, shuffle=True)
for _ in range(10):
for xb, yb in loader:
opt.zero_grad()
nn.functional.cross_entropy(model(xb), yb).backward()
opt.step()
model.eval()
with torch.no_grad():
return (model(X_te).argmax(1) == y_te).float().mean().item()
print("SGD lr=0.01 :", round(run(lambda p: torch.optim.SGD(p, lr=0.01)), 3))
print("SGD + momentum .9:", round(run(lambda p: torch.optim.SGD(p, lr=0.01, momentum=0.9)), 3))
print("Adam lr=1e-3 :", round(run(lambda p: torch.optim.Adam(p, lr=1e-3)), 3))
Exercise 2: Find the edge
On the lesson's toy problem, bisect between lr=0.9 (converges) and lr=1.5 (diverges): try 1.1, 1.2, 1.3, 1.4 and print the 50-step loss for each. Where is the cliff?
Show the solution to Exercise 2
# Exercise 2: Find the edge
import torch
def train(lr, steps=50):
torch.manual_seed(0)
x = torch.linspace(-1, 1, 100).unsqueeze(1)
y = 4 * x + 1
w = torch.zeros(1, requires_grad=True); b = torch.zeros(1, requires_grad=True)
opt = torch.optim.SGD([w, b], lr=lr)
for _ in range(steps):
opt.zero_grad()
loss = ((w * x + b - y) ** 2).mean()
loss.backward()
opt.step()
return loss.item()
for lr in [0.9, 1.1, 1.2, 1.3, 1.4, 1.5]:
print(f"lr={lr:<4} loss after 50 steps = {train(lr):.4g}")
# The cliff sits where the largest-curvature direction's step exceeds 2/L:
# below it losses shrink every step, above it each step overshoots further.
Exercise 3: Weight decay sweep
Train the 200-sample digits MLP with weight_decay in [0, 1e-4, 1e-2, 1.0] (AdamW). Print train and validation accuracy per setting. Does any value clearly over-regularize here — and if not, what does that tell you?
Show the solution to Exercise 3
# Exercise 3: Weight decay sweep
import torch
from torch import nn
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
X, y = load_digits(return_X_y=True)
X_tr, X_val, y_tr, y_val = train_test_split(X / 16.0, y, train_size=200, random_state=0, stratify=y)
X_tr, X_val = torch.tensor(X_tr, dtype=torch.float32), torch.tensor(X_val, dtype=torch.float32)
y_tr, y_val = torch.tensor(y_tr), torch.tensor(y_val)
for wd in [0.0, 1e-4, 1e-2, 1.0]:
torch.manual_seed(0)
model = nn.Sequential(nn.Linear(64, 256), nn.ReLU(), nn.Linear(256, 10))
opt = torch.optim.AdamW(model.parameters(), lr=1e-2, weight_decay=wd)
for _ in range(200):
model.train(); opt.zero_grad()
nn.functional.cross_entropy(model(X_tr), y_tr).backward()
opt.step()
model.eval()
with torch.no_grad():
tr = (model(X_tr).argmax(1) == y_tr).float().mean().item()
va = (model(X_val).argmax(1) == y_val).float().mean().item()
print(f"weight_decay={wd:<6} train={tr:.3f} val={va:.3f}")
# On this run the sweep barely moves validation (0.928-0.930): this small
# MLP on clean digits isn't overfitting enough for decay to rescue anything.
# The honest takeaway: regularizers only show their worth where overfitting
# actually hurts - measure, don't assume.
Exercise 4: One-batch sanity test
Introduce a deliberate bug — comment out opt.zero_grad() — and run the overfit-one-batch test. Print the loss at steps 1/100/300 with and without the bug. Does the test catch it?
Show the solution to Exercise 4
# Exercise 4: One-batch sanity test
import torch
from torch import nn
from sklearn.datasets import load_digits
X, y = load_digits(return_X_y=True)
xb = torch.tensor(X[:64] / 16.0, dtype=torch.float32)
yb = torch.tensor(y[:64])
def overfit_one_batch(buggy):
torch.manual_seed(0)
model = nn.Sequential(nn.Linear(64, 256), nn.ReLU(), nn.Linear(256, 10))
opt = torch.optim.Adam(model.parameters(), lr=1e-3)
for step in range(1, 301):
if not buggy:
opt.zero_grad() # the line under test
loss = nn.functional.cross_entropy(model(xb), yb)
loss.backward()
opt.step()
if step in (1, 100, 300):
print(f" step {step:3d} loss {loss.item():.4f}")
return loss.item()
print("correct loop:")
ok = overfit_one_batch(buggy=False)
print("missing zero_grad():")
bad = overfit_one_batch(buggy=True)
print(f"caught: {'yes' if bad > ok * 10 else 'inspect curves'} "
f"(final {ok:.4f} vs {bad:.4f})")
Mini-project: Training lab
Run the same digits MLP with four learning rates (1e-4, 1e-3, 1e-2, 1e-1), with and without dropout — eight runs. Print a table: final train loss, validation accuracy. Write one comment per row explaining the curve in the lesson's vocabulary.
A complete version is in solutions/mini_training_lab.py.
Stretch: add a learning-rate schedule (torch.optim.lr_scheduler.StepLR) to the best run and write a one-page guide to reading loss curves.
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
| Tuning five things at once | Can't attribute the change | One knob per run, fixed seed |
| lr chosen once, never revisited | New architecture/data = new lr | Sweep powers of 10 again |
| Early stopping without restoring | You keep the overfitted end state | load_state_dict(best_state) |
| Judging dropout on training accuracy | It lowers training fit by design | Compare validation |
| Skipping the one-batch test | Hours lost to a shape bug | 300 steps, one batch, expect ~0 loss |
Quick recap
- Adam at 1e-3 is the starting point; use AdamW for transformers.
- The learning-rate sweep measured final losses of 5.912, 0.005, 3e-10 and 3e+29 — one knob decided all four fates.
- Regularize with weight decay, dropout (worth +0.007 validation accuracy here) and augmentation.
- Use BatchNorm for vision and LayerNorm for transformers.
- With early stopping, stop late and keep the best epoch (28 vs 23 here).
- Debug in a fixed order: overfit one batch, check the starting loss, read the curves, and change one thing at a time.
Checklist
- I can match each optimizer to its one-line idea.
- I ran the lr sweep and can name both failure signatures.
- I know why dropout shows its worth on validation, not training.
- I implemented early stopping with weight restoration.
- I overfitted one batch on purpose and know what it proves.
Read more: PyTorch quickstart — optimization