Part 10 / Stage 3
PyTorch
Goal: Hand Part 9's mechanics to PyTorch: tensors, autograd, and a correct training loop you will reuse everywhere. Time: ~3 hours · Needs: Part 9
What you will learn
- Tensors: creating, reshaping, dtypes, devices
- Autograd: requires_grad, backward(), gradient accumulation
- Defining models with nn.Module / nn.Sequential
- The training loop: zero_grad, forward, loss, backward, step
- Datasets and DataLoaders
- Evaluation mode: model.eval() and torch.no_grad()
- Saving and loading checkpoints
Topics in this part
Practice
Exercise 1: Accumulation proof
Create w = torch.tensor(1.0, requires_grad=True). Call backward() on 2*w twice without zeroing and print w.grad. Zero it (w.grad = None), backward once more, print again.
Show the solution to Exercise 1
# Exercise 1: Accumulation proof
import torch
w = torch.tensor(1.0, requires_grad=True)
(2 * w).backward()
(2 * w).backward()
print("after two backward():", w.grad.item()) # 4.0 — they accumulated
w.grad = None
(2 * w).backward()
print("after zero + one :", w.grad.item()) # 2.0
Exercise 2: The missing softmax
Train the digits MLP twice for 10 epochs: once correctly (logits into CrossEntropyLoss), once with nn.Softmax(dim=1) appended to the model. Print both test accuracies. Which is worse, and why does the wrong one still "work" a bit?
Show the solution to Exercise 2
# Exercise 2: The missing softmax
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 train(extra_softmax):
torch.manual_seed(0)
layers = [nn.Linear(64, 64), nn.ReLU(), nn.Linear(64, 10)]
if extra_softmax:
layers.append(nn.Softmax(dim=1)) # WRONG: CrossEntropyLoss wants logits
model = nn.Sequential(*layers)
opt = torch.optim.Adam(model.parameters(), lr=1e-3)
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("logits (correct) :", round(train(False), 3))
print("softmax then CE (bug) :", round(train(True), 3))
# The buggy version still learns some — argmax order survives the double
# squashing — but its gradients are much weaker, so it lands lower.
Exercise 3: eval() vs no_grad()
Build a model with nn.Dropout(0.5). Show (a) train-mode forward passes on an all-ones input differ run to run, (b) eval-mode passes are identical and unchanged, and (c) no_grad() alone does NOT stop the dropout.
Show the solution to Exercise 3
# Exercise 3: eval() vs no_grad()
import torch
from torch import nn
torch.manual_seed(0)
drop = nn.Dropout(0.5)
x = torch.ones(8)
drop.train()
print("train pass 1:", drop(x).tolist())
print("train pass 2:", drop(x).tolist()) # different zeros — random each pass
drop.eval()
print("eval pass :", drop(x).tolist()) # all ones — identity
drop.train()
with torch.no_grad(): # no_grad stops RECORDING, not dropout
print("train + no_grad:", drop(x).tolist())
Exercise 4: Checkpoint round trip
Train the digits MLP for 5 epochs, save model and optimizer state_dicts plus the epoch to one file, reload everything into fresh objects, continue to epoch 10, and print the final test accuracy.
Show the solution to Exercise 4
# Exercise 4: Checkpoint round trip
import pathlib
import tempfile
import torch
from torch import nn
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
torch.manual_seed(0)
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)
loader = torch.utils.data.DataLoader(
torch.utils.data.TensorDataset(X_tr, y_tr), batch_size=64, shuffle=True)
def make():
model = nn.Sequential(nn.Linear(64, 64), nn.ReLU(), nn.Linear(64, 10))
return model, torch.optim.Adam(model.parameters(), lr=1e-3)
def run_epochs(model, opt, n):
model.train()
for _ in range(n):
for xb, yb in loader:
opt.zero_grad()
nn.functional.cross_entropy(model(xb), yb).backward()
opt.step()
model, opt = make()
run_epochs(model, opt, 5)
path = pathlib.Path(tempfile.mkdtemp()) / "checkpoint.pt"
torch.save({"epoch": 5, "model": model.state_dict(), "opt": opt.state_dict()}, path)
print("saved at epoch 5")
model2, opt2 = make()
ckpt = torch.load(path, weights_only=True)
model2.load_state_dict(ckpt["model"])
opt2.load_state_dict(ckpt["opt"])
run_epochs(model2, opt2, 5)
model2.eval()
with torch.no_grad():
acc = (model2(X_te).argmax(1) == y_te).float().mean().item()
print(f"resumed {ckpt['epoch']} -> 10 epochs; test accuracy {acc:.3f}")
Mini-project: Digits classifier
A clean train/validate/test split (60/20/20), the five-line loop with per-epoch validation accuracy, and a checkpoint of the best-validation weights used for the one final test score.
A complete version is in solutions/mini_digits_classifier.py.
Stretch: make it a CLI script with arguments for epochs and learning rate, resuming from the checkpoint if present.
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
Forgetting zero_grad() |
Stale gradients accumulate into every step | First line of the loop |
| Softmax before CrossEntropyLoss | Double softmax, weak gradients | Give it raw logits |
| float64 data into float32 layers | dtype error at the first Linear | torch.tensor(..., dtype=torch.float32) |
| Evaluating in train mode | Dropout/BatchNorm corrupt the metric | model.eval() + torch.no_grad() |
torch.load without weights_only |
Unpickling untrusted files can execute code | weights_only=True |
Quick recap
- Tensors are arrays with GPU support and gradients added; float32 is the default.
- Autograd replays the computation backwards; gradients accumulate, which is why every step calls zero_grad.
- Models output logits; CrossEntropyLoss handles the softmax.
- The five-line loop reached 0.950 on digits in 20 epochs.
- eval() changes layer behaviour; no_grad() stops recording — evaluation needs both.
- Save state_dicts; load with weights_only=True.
Checklist
- I can predict
w.gradafter two backward() calls on 2·w. - I wrote the five-line loop from memory.
- I know why there is no softmax in the model.
- I used eval() + no_grad() together and can say what each did.
- I saved a checkpoint and verified identical predictions after reload.
Read more: Autograd mechanics · PyTorch quickstart