Lesson 4 · Building networks
The training loop, properly
The problem
The last lesson trained a tiny network for one step, on one example: forward pass, backprop, update. Real training repeats that step many times, on many examples. It also has to answer some practical questions:
- How many examples go into each step, and in what order?
- How do you know the network is learning something general, and not memorising?
- Which weights do you keep at the end?
- Does the code run on a laptop and on a GPU alike?
This lesson answers each one and puts the answers into one file: python/examples/04-neural-net-foundations/_shared/template.py. Every later lesson in the course imports this template and says exactly what it changes. The running example is the course's default: the 2-16-16-2 network on the 200 rush-hour deliveries. It trains with AdamW at learning rate 0.01, in batches of 32, with seed 0.
Batches and epochs
In ML fundamentals you met stochastic gradient descent: each step uses a small random minibatch of examples instead of the whole dataset. One pass through every training example is an epoch.
Picture the 200 training deliveries as a deck of cards. Each epoch, you shuffle the deck and deal it out in hands of 32. Each hand is one training step. Step through it:
Before training
200 training deliveries, in the order they were stored. ○ on time, × late.
Things to notice:
- Each batch goes all the way round the loop before the next one is dealt. The weights change 7 times in one epoch, not once.
- The last batch is small. , so an epoch is 6 full batches and one of 8.
- Each step helps its own batch. The step stage shows that batch's loss again with the new weights, and it's lower. Other batches may get a little worse.
- The order changes every epoch. So the network never sees the same 32 deliveries grouped together twice in a row.
Worked example
How many steps is 200 epochs?
One epoch: , so 6 full batches and a seventh of 8. That's steps.
In PyTorch: Dataset and DataLoader
PyTorch splits this job in two. A Dataset and a DataLoader work together:
- A
Datasetknows how many examples there are (__len__) and how to fetch example numberi(__getitem__). It knows nothing about batches. - A
DataLoaderwraps aDataset. It shuffles the indices, fetches a batch's worth of examples, and stacks them into tensors. Withshuffle=Trueit reshuffles at the start of every epoch.
Here's a Dataset for the deliveries, written out in full:
class Deliveries(Dataset):
"""The rush-hour deliveries as a Dataset: item i is (features, label) for delivery i."""
def __init__(self, x: np.ndarray, y: np.ndarray, mean: np.ndarray, std: np.ndarray) -> None:
self.x = torch.tensor((x - mean) / std, dtype=torch.float32) # (n, 2), standardised
self.y = torch.tensor(y, dtype=torch.long) # (n,), 0 = on time, 1 = late
def __len__(self) -> int:
return len(self.y)
def __getitem__(self, i: int) -> tuple[torch.Tensor, torch.Tensor]:
return self.x[i], self.y[i] # one delivery: a (2,) tensor and a label
def batch_sizes(batch_size: int = 32) -> list[int]:
"""Deal one epoch of the 200 training deliveries into batches, and return each batch's size."""
x_train, y_train, _, _ = load_rush_hour()
data = Deliveries(x_train, y_train, x_train.mean(axis=0), x_train.std(axis=0))
loader = DataLoader(data, batch_size=batch_size, shuffle=True) # a new order every epoch
return [len(y) for x, y in loader] # x: (batch, 2), y: (batch,)When your data already sits in tensors, TensorDataset does the same job in one line. The template uses it:
def rush_hour_loaders(batch_size: int = 32, seed: int = 0) -> tuple[DataLoader, DataLoader]:
"""Train and validation loaders for the rush-hour data, standardised with the training set's mean and std."""
x_train, y_train, x_val, y_val = load_rush_hour()
mean, std = x_train.mean(axis=0), x_train.std(axis=0)
def dataset(x, y):
x = torch.tensor((x - mean) / std, dtype=torch.float32)
return TensorDataset(x, torch.tensor(y, dtype=torch.long))
shuffle_gen = torch.Generator().manual_seed(seed) # the batch order is part of the seed
train = DataLoader(dataset(x_train, y_train), batch_size=batch_size, shuffle=True, generator=shuffle_gen)
val = DataLoader(dataset(x_val, y_val), batch_size=256)
return train, valThree details:
- The inputs are standardised with the training set's mean and standard deviation, for both loaders. The validation data must be measured with the same ruler.
- The shuffle has its own random generator, seeded, so the batch order is part of the seed.
- The validation loader doesn't shuffle, and its batch of 256 holds all 200 validation deliveries at once. Nothing is learned from them, so order and batch size don't matter.
One step, five lines
Each step of the loop is the same five lines. Tap a stage to see its lines in the template's train_one_epoch:
def train_one_epoch(model: nn.Module,loader: DataLoader,loss_fn: nn.Module,optimizer: torch.optim.Optimizer,device: torch.device,) -> tuple[float, float]:"""One pass over the training data. Returns the mean loss and the accuracy."""model.train() # dropout on, batch norm uses batch statisticstotal_loss, correct, count = 0.0, 0, 0for x, y in loader:x, y = x.to(device), y.to(device)optimizer.zero_grad() # 1. clear the last step's gradientslogits = model(x) # 2. forward passloss = loss_fn(logits, y) # 3. lossloss.backward() # 4. backward pass: fills every parameter's .gradoptimizer.step() # 5. update the weightstotal_loss += loss.item() * len(y)correct += (logits.argmax(dim=1) == y).sum().item()count += len(y)return total_loss / count, correct / count
1 clear
Wipe last step’s gradients. Without this, .grad keeps adding up every past gradient.
The order matters:
optimizer.zero_grad()clears the gradients from the last step.model(x)runs the forward pass on the batch.loss_fn(logits, y)turns the batch's logits into one number.loss.backward()runs backprop and fills every parameter's.grad.optimizer.step()moves every weight using its.grad.
This cycle is the training loop: deal a batch, run the five lines, repeat, and check on held-out data now and then. The optimiser here is AdamW: a version of Adam (Lesson 5) with weight decay done its own way (Lesson 7). The loop is the same for any optimiser.
The bookkeeping lines add up loss.item() * len(y), not loss.item(). Each batch's loss is a mean over its examples, so multiplying by the batch size gives a total. The small last batch of 8 then counts a quarter as much as a batch of 32, as it should.
Predict first
You forget optimizer.zero_grad(). What happens to the updates?
Watching training: training and validation loss
The network could get every training delivery right by memorising them, and still be poor on new deliveries. That's overfitting. So the loop also measures the loss on validation deliveries the network never trains on (see train, validation and test sets). Here, that's once per epoch.
Press play to train the default network, from the same starting weights as the PyTorch code. The map shows the boundary as it learns. Below it are the loss curves: one point per epoch, measured on all 200 training and all 200 validation deliveries.
Step 0 · epoch 0 · validation accuracy 51.5%
Press play: one point per epoch, measured in evaluation mode with no gradients.
Things to notice:
- Most of the learning happens early. In the first 20 epochs, the boundary bends into the 19:00 dip and validation accuracy climbs from about 50% to over 90%.
- After that, validation loss stops improving and wobbles up and down, while training loss keeps creeping down. The network is starting to fit details of the training deliveries that don't carry over.
- The best-validation marker moves. The best epoch is often not the last one. That's why the loop saves the best weights as it goes, which comes up below.
- Validation loss mostly sits below training loss here. That's luck, not a bug: 14 of the 20 flipped labels landed in the training set, so the training set is noisier.
- Without
zero_grad(), the loss jumps around and validation accuracy hovers near 50%. That's about as good as a coin toss.
Evaluation mode, and no gradients
Look at how the template measures validation loss:
@torch.inference_mode() # no graph, no gradients: faster, and nothing can change the weights
def evaluate(model: nn.Module, loader: DataLoader, loss_fn: nn.Module, device: torch.device) -> tuple[float, float]:
"""The mean loss and accuracy on a dataset, in evaluation mode."""
model.eval() # dropout off, batch norm uses its running averages
total_loss, correct, count = 0.0, 0, 0
for x, y in loader:
x, y = x.to(device), y.to(device)
logits = model(x)
total_loss += loss_fn(logits, y).item() * len(y)
correct += (logits.argmax(dim=1) == y).sum().item()
count += len(y)
return total_loss / count, correct / countTwo switches make evaluation honest and cheap.
model.eval(). Some layers act differently while training. Dropout switches off random units during training but not at test time. Batch norm uses each batch's statistics during training, and long-run averages at test time. A model is always in one of two states, set by model.train() and model.eval(). Each call sets every layer inside the model at once.
Our network has neither kind of layer, so the switch changes nothing yet. Call it anyway. Lessons 6 and 7 add both kinds of layer, and a forgotten model.eval() then gives wrong validation numbers with no error. train_one_epoch calls model.train() at its start, because evaluate left the model in evaluation mode.
torch.inference_mode(). Evaluation needs no gradients. torch.inference_mode() turns autograd's recording off, like torch.no_grad(). So no graph is built, which saves memory and time. The template uses it as a decorator on the whole evaluate function.
These two switches are separate. inference_mode doesn't put the model in evaluation mode, and model.eval() doesn't turn off gradients. Evaluation needs both.
DigressionWhy inference_mode rather than no_gradBoth turn off gradients. inference_mode skips some extra bookkeeping too, and is stricter about where its results can go. · 2 min
torch.no_grad() stops autograd recording operations. torch.inference_mode() does that, and also skips some bookkeeping autograd keeps on every tensor: a version counter that notices in-place changes, and tracking of views. Skipping it makes inference a little faster.
The price is a rule: a tensor made inside inference_mode can't be used later in a computation that autograd records. PyTorch raises an error if you try. For evaluation and prediction, that never happens, so inference_mode is the better default.
Use no_grad when the results will feed back into training. Updating weights by hand, as in the autograd primer, is the classic case.
Devices and seeds
A device is where tensors live and where their maths runs: the CPU, an NVIDIA GPU ("cuda"), or an Apple GPU ("mps"). A model and the data it reads must be on the same device, or PyTorch raises an error. .to(device) moves a model's parameters, or a tensor, to a device.
The template's setup picks the best device available, and seeds every random number generator:
def seed_everything(seed: int = 0) -> None:
"""Make a run repeatable: the same seed gives the same weights, batches and dropout masks."""
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
def get_device() -> torch.device:
"""Use a GPU if there is one; the book's examples are small enough for the CPU."""
if torch.cuda.is_available():
return torch.device("cuda")
if torch.backends.mps.is_available():
return torch.device("mps")
return torch.device("cpu")
def make_mlp(sizes: list[int] = [2, 16, 16, 2]) -> nn.Sequential: # noqa: B006 (never mutated)
"""Linear → ReLU for each hidden layer, then a final Linear that outputs logits."""
layers: list[nn.Module] = []
for i, (n_in, n_out) in enumerate(zip(sizes[:-1], sizes[1:])):
layers.append(nn.Linear(n_in, n_out))
if i < len(sizes) - 2:
layers.append(nn.ReLU())
return nn.Sequential(*layers)get_device()tries CUDA, then MPS, then falls back to the CPU. The course's networks are small enough that the CPU is fine.- The loop moves each batch with
x.to(device), because the loader builds batches on the CPU. seed_everything(0)callstorch.manual_seed, plus the seeds of Python's and NumPy's generators. The starting weights then come out the same on every run.
DigressionSeeds and reproducibility on CPU and GPUA seed fixes the random numbers. It doesn't always fix the result, especially on a GPU. · 2 min
On a CPU, the template gives the same numbers every run. The tests in python/examples/ rely on that.
On a GPU, a seed isn't enough. Some GPU operations add numbers in whatever order their threads finish. Floating-point addition gives slightly different answers in different orders, so two runs can drift apart. PyTorch's reproducibility notes list what you can do:
torch.use_deterministic_algorithms(True)makes PyTorch use deterministic versions of operations, or raise an error where none exists. Some CUDA operations also need an environment variable set, which the error message names.torch.backends.cudnn.benchmark = Falsestops cuDNN picking its fastest method by timing, which can vary from run to run.- With
num_workers > 0, each loader worker needs a seed too, set through theDataLoader'sgeneratorandworker_init_fn.
PyTorch's documentation is also clear that results may differ between CPU and GPU, between PyTorch versions, and between platforms, even with the same seed. So compare runs on the same setup.
Keeping the best weights
The live figure showed that the last epoch is often not the best. So the loop should keep the weights from the epoch with the lowest validation loss. This is half of early stopping; the other half, stopping early, is in Lesson 7.
A model's weights live in its state_dict(): a dictionary from each parameter's name (like "0.weight") to its tensor. torch.save writes it to a file:
def train_and_keep_best(path: Path, epochs: int = 200, seed: int = 0) -> list[dict]:
"""The template's loop, saving the weights whenever the validation loss reaches a new low."""
seed_everything(seed)
device = get_device()
train_loader, val_loader = rush_hour_loaders(batch_size=32, seed=seed)
model = make_mlp([2, 16, 16, 2]).to(device)
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.AdamW(model.parameters(), lr=0.01)
best_val_loss = float("inf")
history = []
for epoch in range(1, epochs + 1):
train_loss, train_acc = train_one_epoch(model, train_loader, loss_fn, optimizer, device)
val_loss, val_acc = evaluate(model, val_loader, loss_fn, device)
history.append({"epoch": epoch, "train_loss": train_loss, "val_loss": val_loss, "val_acc": val_acc})
if val_loss < best_val_loss:
best_val_loss = val_loss
torch.save(model.state_dict(), path) # only the weights: a dict of named tensors
return historyTo use the saved weights, build a network of the same shape, then load the dictionary into it:
def load_best(path: Path) -> nn.Sequential:
"""Rebuild the network, then pour the saved weights into it."""
device = get_device()
model = make_mlp([2, 16, 16, 2]).to(device) # same shape as the saved one
model.load_state_dict(torch.load(path, map_location=device)) # weights_only=True by default
model.eval() # ready to predict
return modelepoch 200: train loss 0.234, val loss 0.224, val acc 92.0%
best val loss 0.180 at epoch 157 (val acc 95.5%)
reloaded best model: (0.1799887716770172, 0.955)The last epoch has a validation loss of 0.224. The best one, epoch 157, had 0.180, and the reloaded model reproduces it exactly. Saving the best is cheap insurance.
Why save the state_dict and not the whole model object? The dictionary holds only tensors, so loading it can't run hidden code. Since PyTorch 2.6, torch.load refuses anything other than tensors and plain containers unless you pass weights_only=False. And the dictionary doesn't depend on how your model class was written, so it keeps working after you tidy up the code.
DigressionCheckpoints: what to save so you can resume exactlyThe weights alone let you predict. To carry on training, also save the optimiser, the epoch and the seed. · 2 min
The best weights are enough to make predictions. They aren't enough to carry on training as if nothing had stopped. AdamW keeps running averages of past gradients for every weight, and these live in the optimiser, not the model. Restart without them, and the first steps behave differently.
A checkpoint saves everything the loop needs:
def save_checkpoint(path: Path, model: nn.Module, optimizer: torch.optim.Optimizer, epoch: int, seed: int) -> None:
"""Everything needed to carry on training later, not just to predict."""
torch.save(
{
"model": model.state_dict(),
"optimizer": optimizer.state_dict(), # AdamW's running averages, step counts, lr
"epoch": epoch,
"seed": seed,
},
path,
)
def resume(path: Path, model: nn.Module, optimizer: torch.optim.Optimizer) -> int:
"""Load a checkpoint into a fresh model and optimizer; return the epoch to start from."""
checkpoint = torch.load(path, map_location=get_device())
model.load_state_dict(checkpoint["model"])
optimizer.load_state_dict(checkpoint["optimizer"])
return checkpoint["epoch"] + 1Optimisers have a state_dict() too. For a long run, save a checkpoint every few epochs, so a crash costs minutes rather than hours. Exact resumption also needs the random state, including the loader's generator. For the course's small runs, saving the seed and starting again is simpler.
Putting it together: the template
Here is the template's last piece, fit. It runs the loop for a number of epochs and records the history. It also keeps a copy of the weights from the epoch with the lowest validation loss, and loads them back at the end. So the model fit hands back is the best one, not the last one. The copy is in memory, with copy.deepcopy, because a state_dict() shares memory with the live weights and would change as training goes on.
def fit(
model: nn.Module,
train_loader: DataLoader,
val_loader: DataLoader,
*,
epochs: int = 200,
lr: float = 0.01,
weight_decay: float = 0.01,
device: torch.device | None = None,
log_every: int = 0,
) -> list[dict]:
"""Train with AdamW and cross-entropy; return one record per epoch.
The model ends with the weights from the epoch with the lowest validation loss, not the last.
"""
device = device or get_device()
model.to(device)
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=weight_decay)
history = []
best_val_loss, best_state = float("inf"), None
for epoch in range(1, epochs + 1):
train_loss, train_acc = train_one_epoch(model, train_loader, loss_fn, optimizer, device)
val_loss, val_acc = evaluate(model, val_loader, loss_fn, device)
history.append(
{"epoch": epoch, "train_loss": train_loss, "train_acc": train_acc, "val_loss": val_loss, "val_acc": val_acc}
)
if val_loss < best_val_loss: # a new best: copy the weights, since state_dict() shares their memory
best_val_loss, best_state = val_loss, copy.deepcopy(model.state_dict())
if log_every and epoch % log_every == 0:
print(f"epoch {epoch:4d} train loss {train_loss:.3f} acc {train_acc:.1%} val loss {val_loss:.3f} acc {val_acc:.1%}")
model.load_state_dict(best_state) # end with the best weights
return historyAnd here is how the template trains the default network from start to finish:
def main() -> None:
seed_everything(0)
train_loader, val_loader = rush_hour_loaders(batch_size=32, seed=0)
model = make_mlp([2, 16, 16, 2])
history = fit(model, train_loader, val_loader, epochs=200, lr=0.01, log_every=20)
best = min(history, key=lambda h: h["val_loss"]) # the epoch whose weights fit kept
print(f"last epoch: val loss {history[-1]['val_loss']:.3f}, acc {history[-1]['val_acc']:.1%}")
print(f"best epoch: {best['epoch']}, val loss {best['val_loss']:.3f}, acc {best['val_acc']:.1%}")epoch 20 train loss 0.327 acc 90.5% val loss 0.258 acc 90.5%
epoch 40 train loss 0.283 acc 91.5% val loss 0.234 acc 91.5%
epoch 60 train loss 0.257 acc 92.5% val loss 0.226 acc 93.5%
epoch 80 train loss 0.231 acc 92.5% val loss 0.211 acc 94.5%
epoch 100 train loss 0.225 acc 93.0% val loss 0.205 acc 94.5%
epoch 120 train loss 0.215 acc 93.0% val loss 0.224 acc 93.5%
epoch 140 train loss 0.212 acc 92.5% val loss 0.247 acc 89.0%
epoch 160 train loss 0.212 acc 93.5% val loss 0.241 acc 93.5%
epoch 180 train loss 0.201 acc 93.5% val loss 0.203 acc 95.0%
epoch 200 train loss 0.234 acc 91.5% val loss 0.224 acc 92.0%
last epoch: val loss 0.224, acc 92.0%
best epoch: 157, val loss 0.180, acc 95.5%Read it as the live figure's story in numbers:
- Accuracy passes 90% within 20 epochs. A straight line, the single neuron from Lesson 1, gets 76%.
- From about epoch 80 on, validation loss wanders between 0.20 and 0.25 while training loss drifts down. More epochs aren't buying much.
- The best epoch by validation loss is 157, with a loss of 0.180 and 95.5% accuracy, against 92% at the end. Those are the weights
fitkeeps, the same ones the save-the-best code found above. - Why pick by validation loss and not accuracy? With only 200 validation deliveries, one delivery is half a percentage point, so accuracy jumps around. Loss moves more smoothly.
That's the whole template: seed and device, data loaders, train_one_epoch, evaluate and fit. Each later lesson changes one piece, such as the optimiser in Lesson 5 or the layers in Lesson 6, and says exactly which.
Common misconceptions
"model.eval() turns off gradients." It only switches layers like dropout and batch norm to their test behaviour. Turning off gradients is torch.inference_mode() or torch.no_grad(). Evaluation needs both.
"One epoch is one step." An epoch is one pass through all the training data. With 200 deliveries in batches of 32, that's 7 steps.
"backward() replaces the old gradients." It adds to them. That's why every step starts with optimizer.zero_grad().
"The last epoch's weights are the best ones." Validation loss often bottoms out earlier and then wobbles or rises. Keep the best weights as you go.
"Validation loss below training loss means something is broken." It can happen by chance. Here, the training set holds most of the flipped labels. Layers like dropout can also make the training loss look worse, because they only act during training.
Recap
- Each epoch shuffles the training data and deals it into batches. Each batch is one step: clear the gradients, forward, loss, backward, step.
- After each epoch, measure the loss on validation data, in evaluation mode and with no gradients. Save the weights whenever it reaches a new low.
fitdoes this and ends with the best weights. zero_grad()matters: without it, each step uses the sum of every past gradient and training falls apart.template.pyholds the whole loop as functions (seed_everything,get_device,make_mlp,rush_hour_loaders,train_one_epoch,evaluate,fit). Later lessons import it and change one piece at a time.- PyTorch names in this lesson:
Dataset,TensorDatasetandDataLoader,torch.optim.AdamW,optimizer.zero_grad()andoptimizer.step(),model.train()andmodel.eval(),torch.inference_mode(),torch.deviceand.to(device),torch.manual_seed,state_dict(),torch.saveandtorch.load.