Autograd, nn.Module and the training loop
Last updated
Every PyTorch training script has the same skeleton: data in a DataLoader, a model that’s an nn.Module, a loss, an optimiser, and a loop of four lines. You built each piece in Stage 6, so this lesson is mostly matching names. By the end you’ll have lesson 6.9’s digits network written the way PyTorch code is really written, and you’ll know what goes wrong when one of the four lines is missing.
By the end of this lesson you can
- Use requires_grad and backward() to get gradients from PyTorch
- Write a model as an nn.Module subclass, with layers in __init__ and the forward pass in forward
- Feed it batches with Dataset and DataLoader, and switch between model.train() and model.eval()
- Write the standard training loop, and say why zero_grad() is in it
requires_grad and backward()
In simplenet every Value and Tensor recorded its graph. PyTorch records only for tensors that ask: make one with requires_grad=True, and every operation on it remembers its inputs, as your _parents did. Here's lesson 6.6's formula once more (scripts run as in lesson 7.1; they're all in the ml-local download there):
"""requires_grad and backward(): lesson 6.6's formula, differentiated by PyTorch.""" import torch a = torch.tensor(2.0, requires_grad=True) # record what's done with a b = torch.tensor(-3.0, requires_grad=True) c = torch.tensor(10.0, requires_grad=True) f = (a * b + c) * a print("f =", f.item(), " made by", type(f.grad_fn).__name__) f.backward() print("df/da =", a.grad.item(), " df/db =", b.grad.item(), " df/dc =", c.grad.item()) f = (a * b + c) * a # a second forward and backward pass... f.backward() print("after a second backward(), df/da =", a.grad.item()) # ...adds to the first
(.venv) $ python autograd.py f = 8.0 made by MulBackward0 df/da = -2.0 df/db = 4.0 df/dc = 2.0 after a second backward(), df/da = -4.0
, 4 and 2: lesson 6.6's answers. grad_fn is PyTorch's _backward: MulBackward0 knows how to pass a gradient back through a multiplication. And the last line is lesson 6.7's wrong way, in PyTorch: a second backward() adds to .grad, so reads . PyTorch accumulates on purpose, as you did, so that a value used twice collects both gradients.
The weights of nn.Linear and every other layer are made with requires_grad=True for you. Your data isn't, and doesn't need to be.
nn.Module: a model as a class
nn.Sequential (lesson 7.1) is fine for a stack of layers. For anything else, write a class:
- Subclass
nn.Module, and callsuper().__init__()first in__init__. - Make the layers in
__init__and keep them as attributes. PyTorch finds every layer kept this way, somodel.parameters()lists all their weights, as yourMLP.parameters()did. - Write the forward pass in
forward. Call the model asmodel(x), notmodel.forward(x):__call__runsforward, as yours did, and some PyTorch features hook into the call.
DigitNet in the script below is lesson 6.9's network, 64 → 32 → 10, and has the same 2,410 parameters.
Dataset and DataLoader
Lesson 6.9 shuffled and sliced batches by hand. PyTorch splits that job in two:
- A Dataset answers two questions: how many examples (
len(ds)), and what's example (ds[i], a pair of input and label).TensorDataset(X, y)makes one from two tensors. For data on disk, you write a small class with__len__and__getitem__(Fashion-MNIST in the project comes ready-made). - A DataLoader turns a Dataset into batches:
DataLoader(ds, batch_size=32, shuffle=True)reshuffles at the start of every epoch, the fix for lesson 6.9's wrong way. Loop over it and each item is one batch: a tensor of inputs and 32 labels.
Validation data doesn't need shuffling: the accuracy is the same in any order.
The training loop
Now the whole script. The loop is the four numbered lines inside for xb, yb in train_loader::
"""Lesson 6.9's digits network in PyTorch: Dataset, DataLoader, nn.Module and the training loop.""" import torch from sklearn.datasets import load_digits from sklearn.model_selection import train_test_split from torch import nn from torch.utils.data import DataLoader, TensorDataset torch.manual_seed(0) X, y = load_digits(return_X_y=True) X_train, X_val, y_train, y_val = train_test_split(X / 16, y, test_size=0.25, random_state=0, stratify=y) train_set = TensorDataset(torch.tensor(X_train, dtype=torch.float32), torch.tensor(y_train)) val_set = TensorDataset(torch.tensor(X_val, dtype=torch.float32), torch.tensor(y_val)) train_loader = DataLoader(train_set, batch_size=32, shuffle=True) # a new shuffle every epoch val_loader = DataLoader(val_set, batch_size=256) class DigitNet(nn.Module): def __init__(self): super().__init__() self.hidden = nn.Linear(64, 32) self.out = nn.Linear(32, 10) def forward(self, x): return self.out(torch.relu(self.hidden(x))) model = DigitNet() loss_fn = nn.CrossEntropyLoss() optimizer = torch.optim.SGD(model.parameters(), lr=0.3) print("parameters:", sum(p.numel() for p in model.parameters())) def evaluate(loader): model.eval() # evaluation mode (lesson 7.7 and 7.8 need it) right = 0 with torch.no_grad(): # no graph: we won't call backward() for xb, yb in loader: right += (model(xb).argmax(dim=1) == yb).sum().item() return right / len(loader.dataset) for epoch in range(1, 21): model.train() # training mode total = 0.0 for xb, yb in train_loader: loss = loss_fn(model(xb), yb) # 1. predict and measure optimizer.zero_grad() # 2. clear the old gradients loss.backward() # 3. find the new ones optimizer.step() # 4. step total += loss.item() * len(xb) if epoch == 1 or epoch % 5 == 0: print(f"epoch {epoch:2}: loss {total / len(train_set):.3f}, validation accuracy {evaluate(val_loader):.3f}")
(.venv) $ python loop.py parameters: 2410 epoch 1: loss 1.885, validation accuracy 0.613 epoch 5: loss 0.226, validation accuracy 0.780 epoch 10: loss 0.114, validation accuracy 0.951 epoch 15: loss 0.077, validation accuracy 0.967 epoch 20: loss 0.058, validation accuracy 0.976
97.6% of the validation digits right after 20 epochs. (This split is different from lesson 6.9's, a quarter of all the digits rather than a fifth of the rest, so compare the shape of the run, not the exact numbers.) Step through the four lines on the smallest possible model, one weight:
for xb, yb in train_loader: loss = loss_fn(model(xb), yb) optimizer.zero_grad() loss.backward() optimizer.step()
- w
- 0
- loss
- —
- w.grad
- None
- steps
- 0
w starts at 0. Run the loop a line at a time.
loss.item() * len(xb) adds up each batch's loss weighted by its size, so the printed number is the mean over the epoch, even though the last batch is smaller.
model.train() and model.eval()
Some layers behave differently while training and while evaluating: dropout switches units off at random only in training (lesson 7.8), and batch norm uses the batch's own statistics only in training (lesson 7.7). model.train() and model.eval() flip every layer in the model into one mode or the other.
This network has neither kind of layer, so here the calls change nothing. Write them anyway, every time: put model.train() at the start of each epoch and model.eval() before measuring, so the loop is still right on the day you add a dropout layer.
torch.no_grad() is a separate thing: it stops PyTorch recording a graph, because you won't call backward() on the validation predictions. That saves memory and time. eval() changes how layers behave; no_grad() changes what's recorded. Evaluation wants both.
Wrong way: forgetting zero_grad()
Delete one line, optimizer.zero_grad():
"""The wrong way: loop.py with one line missing.""" import torch from sklearn.datasets import load_digits from sklearn.model_selection import train_test_split from torch import nn from torch.utils.data import DataLoader, TensorDataset torch.manual_seed(0) X, y = load_digits(return_X_y=True) X_train, X_val, y_train, y_val = train_test_split(X / 16, y, test_size=0.25, random_state=0, stratify=y) train_set = TensorDataset(torch.tensor(X_train, dtype=torch.float32), torch.tensor(y_train)) val_set = TensorDataset(torch.tensor(X_val, dtype=torch.float32), torch.tensor(y_val)) train_loader = DataLoader(train_set, batch_size=32, shuffle=True) # a new shuffle every epoch val_loader = DataLoader(val_set, batch_size=256) class DigitNet(nn.Module): def __init__(self): super().__init__() self.hidden = nn.Linear(64, 32) self.out = nn.Linear(32, 10) def forward(self, x): return self.out(torch.relu(self.hidden(x))) model = DigitNet() loss_fn = nn.CrossEntropyLoss() optimizer = torch.optim.SGD(model.parameters(), lr=0.3) print("parameters:", sum(p.numel() for p in model.parameters())) def evaluate(loader): model.eval() # evaluation mode (lesson 7.7 and 7.8 need it) right = 0 with torch.no_grad(): # no graph: we won't call backward() for xb, yb in loader: right += (model(xb).argmax(dim=1) == yb).sum().item() return right / len(loader.dataset) for epoch in range(1, 21): model.train() # training mode total = 0.0 for xb, yb in train_loader: loss = loss_fn(model(xb), yb) # 1. predict and measure loss.backward() # adds to every gradient so far optimizer.step() # 4. step total += loss.item() * len(xb) if epoch == 1 or epoch % 5 == 0: print(f"epoch {epoch:2}: loss {total / len(train_set):.3f}, validation accuracy {evaluate(val_loader):.3f}")
(.venv) $ python nozero.py parameters: 2410 epoch 1: loss 1.538, validation accuracy 0.589 epoch 5: loss 4.445, validation accuracy 0.100 epoch 10: loss 5.268, validation accuracy 0.102 epoch 15: loss 6.336, validation accuracy 0.096 epoch 20: loss 6.258, validation accuracy 0.102
The first epoch looks almost normal. Then the loss climbs, to over 6, worse than guessing (a uniform guess over 10 digits scores ), and the accuracy falls to 10%: chance. Each backward() added its gradient to all the previous ones, so by the end of epoch 1 each step was pushed by the sum of 43 batches' gradients, most of them out of date. The steps grow huge and the weights are thrown far from anywhere useful. The strip in step 4 shows the same thing on one weight: press Skip zero_grad().
The rule: in every step, zero_grad() before backward(), step() after it.
Check what you learned
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- PyTorch: A Gentle Introduction to torch.autograd: requires_grad, grad_fn and backward()
- PyTorch: Build the Neural Network: subclassing nn.Module
- PyTorch: Datasets and DataLoaders: Dataset, DataLoader, batches and shuffling
- PyTorch: torch.optim.Optimizer.zero_grad: why gradients accumulate until you clear them