The Training Loop: Batches, Epochs and an Optimizer
Gradient descent lowers a loss one small step at a time. Training a real network takes thousands of those steps, over a dataset that can hold tens of thousands of examples, so the work has to be organised. Someone has to decide which examples each step looks at, how often the whole dataset is visited, which object applies the update, and in what order the parts of one update happen. This page explains each of those pieces in PyTorch, and how to make a run produce the same numbers every time you start it.
Mini-batches: many cheap steps instead of a few exact ones
A gradient tells you, for each weight, how much the loss changes when that weight is nudged up a little. To compute it for the loss of the whole dataset, the model has to predict every single example first. With 50,000 examples, one step costs 50,000 predictions, and the model moves only once for all that work.
The usual answer is a mini-batch: a small group of examples, often 32, 64 or 128 of them. You compute the loss on that group only, average it over its examples, compute the gradients of that average and take one step. Then you take the next group and do it again. Each step is far cheaper, so the model makes many more steps for the same amount of computing.
The price is that a batch is only a sample of the data. Its average loss is close to the average over all examples, but not equal to it. Here are eight examples with their losses, split into two batches of four:
| Examples used | Loss of each example | Average loss |
|---|---|---|
| All 8 | 2.0, 1.0, 3.0, 0.5, 1.5, 2.5, 1.0, 0.5 | 1.5 |
| Batch 1 | 2.0, 1.0, 3.0, 0.5 | 1.625 |
| Batch 2 | 1.5, 2.5, 1.0, 0.5 | 1.375 |
Each batch gives an estimate of the true average: one a little above it, one a little below. The gradient computed from a batch is an estimate in the same way, so each step points roughly downhill rather than exactly downhill. Over many steps the small errors in different directions tend to cancel out, and the loss still falls. That is the trade a mini-batch makes: many cheap, slightly noisy steps in place of a few exact, expensive ones.
The batch size sets the balance. A smaller batch gives cheaper and noisier steps; a larger batch gives steps closer to the exact gradient, each costing more. PyTorch's cross-entropy function already averages over the examples it receives (its default reduction='mean'), so the loss of a batch is one number whatever the batch size.
True or false?
The gradient from a mini-batch is exactly the gradient over the whole dataset, only cheaper to compute.
False. It is an estimate. A batch is a sample of the data, so its average loss and its gradients are close to those of the whole set but not equal to them.
With mini-batches, the parameters are updated many times during one pass over the data.
True. There is one update per batch, so a pass over the data in batches of 64 gives one update for every 64 examples.
Epochs: passes over the whole training set
Splitting the data into batches and taking one step per batch eventually uses every example once. That full pass over the training set is called an epoch. One epoch is rarely enough for a model to learn well, so training runs for several epochs, and each one visits every example again.
The number of steps follows from three numbers. Take 1,000 examples in batches of 64: 15 full batches use 960 examples, and the 40 left over form a 16th, smaller batch. So one epoch is 16 steps, and five epochs are 80 steps.
The number of epochs is a choice you make before training, like the batch size and the learning rate. Too few, and the model stops while it could still improve. How to tell when more epochs stop helping needs measurements on data the model did not train on, which is a separate topic.
The data loader serves the batches
Cutting a dataset into batches by hand means slicing tensors with start and end positions and taking care of the last, shorter batch. PyTorch does this for you with two objects from torch.utils.data.
A dataset is anything that can tell its length and hand out the example at a given position. When your inputs and labels are already tensors, TensorDataset(x, y) pairs them: example number i is x[i] together with y[i], so both tensors must have the same size along their first dimension.
A data loader, DataLoader, takes a dataset and serves it batch by batch. A for loop over the loader gives one batch each time round: a tensor of inputs and a tensor of labels, with the examples stacked along a new first dimension whose size is the batch size.
import torch
from torch.utils.data import TensorDataset, DataLoader
x = torch.randn(1000, 20) # 1,000 inputs, 20 numbers each
y = x[:, :3].argmax(dim=1) # a label from 0 to 2 for each
dataset = TensorDataset(x, y)
loader = DataLoader(dataset, batch_size=64, shuffle=True)
print(len(loader)) # 16 batches per epoch
for xb, yb in loader:
print(xb.shape, yb.shape) # torch.Size([64, 20]) torch.Size([64])
breakThe label here is simply which of the first three input numbers is the largest, so there is a real pattern for a model to learn. len(loader) is the number of batches in one epoch. With 1,000 examples and batch_size=64 the first 15 batches have 64 examples and the last has 40, because the loader keeps the incomplete last batch unless you pass drop_last=True.
A new order every epoch
With shuffle=True, the loader puts the examples in a new random order each time a for loop starts over it, that is, at the start of every epoch. It does not shuffle once when it is created. Here are ten examples, numbered 0 to 9, served in batches of four over three epochs:
| Epoch | Batch 1 | Batch 2 | Batch 3 |
|---|---|---|---|
| 1 | 7, 2, 9, 0 | 4, 8, 1, 5 | 3, 6 |
| 2 | 1, 5, 3, 8 | 0, 9, 6, 2 | 7, 4 |
| 3 | 6, 0, 4, 2 | 9, 3, 7, 1 | 8, 5 |
Every epoch uses all ten examples exactly once, but the groups change. That matters because datasets are often stored in some order, for instance all the examples of one class together. Read in that order, a batch could hold a single class and pull the model hard in one direction, then the next batch would pull it another way. Shuffling makes every batch a fair mix, and reshuffling each epoch stops the model from seeing the same groups, in the same order, again and again.
Shuffling is off unless you ask for it: without shuffle=True the loader serves the examples in their stored order. For data you only measure the model on, without training, the order makes no difference to the result, so such a loader is usually left unshuffled.
True or false?
A DataLoader shuffles the data unless you tell it not to.
False. Shuffling is off by default. Without shuffle=True the loader serves the examples in the order the dataset stores them.
With shuffle=True, each epoch serves the examples in a new order.
True. A new random order is drawn every time a for loop starts over the loader, so every epoch is shuffled differently.
The optimizer applies the update
Gradient descent written by hand moves every parameter against its gradient: the new value is the old value minus the learning rate times the gradient. With a weight of 0.50, a gradient of 0.20 and a learning rate of 0.1, the step is 0.1 times 0.20, which is 0.02, so the weight becomes 0.48. A positive gradient means the loss rises when the weight goes up, so the weight goes down.
One gradient descent step for one parameter
By hand, that rule takes some care. It has to be written out for every parameter. It has to run inside with torch.no_grad():, so the update itself is not recorded. And each gradient has to be cleared afterwards, since a new gradient is added to the stored one instead of replacing it. An optimizer is an object that owns this work. You give it the parameters it should update and a learning rate once; after that, optimizer.step() applies one step to all of them from their stored gradients, and optimizer.zero_grad() clears all their gradients.
with torch.no_grad():
weights -= lr * weights.grad
bias -= lr * bias.grad
weights.grad = None
bias.grad = Noneoptimizer = torch.optim.SGD([weights, bias], lr=0.1)
optimizer.step()
optimizer.zero_grad()The plainest rule is torch.optim.SGD, stochastic gradient descent. With its default settings it applies exactly the rule above. "Stochastic" means random: each gradient comes from a randomly drawn batch rather than from the whole dataset, though the same class works for any batch size. Other optimizers in torch.optim use cleverer rules, and they are used the same way.
Three details save confusion later:
- The parameters are passed as a list, such as
[weights, bias]. The optimizer keeps a reference to these tensors and changes them in place. step()already runs with gradient tracking switched off, so it needs nowith torch.no_grad():around it.zero_grad()does not fill the gradients with zeros by default: it sets each.gradtoNone, which uses less memory. Printingweights.gradjust after it showsNone.
Always pass lr yourself. SGD has a default learning rate of 0.001, so leaving it out gives no error, only a run that learns far more slowly than you expected.
True or false?
optimizer.step() has to be wrapped in with torch.no_grad(), like a hand-written update.
False. The optimizer switches gradient tracking off inside step() itself. The no_grad block is needed only when you update the tensors yourself.
Right after optimizer.zero_grad(), a parameter's .grad is None by default.
True. zero_grad() sets the gradients to None unless you call it with set_to_none=False, which fills them with zeros instead.
Creating torch.optim.SGD without lr raises an error.
False. lr defaults to 0.001. The run starts without complaint and simply learns slowly, which is why it is best always passed explicitly.
The training loop, line by line
The pieces now fit together as two loops, one inside the other. The outer loop counts epochs. The inner loop takes the batches the loader serves, and for every batch it does the same five things:
- Predict scores for the batch
- Measure the loss one average number
- Compute gradients loss.backward()
- Update optimizer.step()
- Clear gradients optimizer.zero_grad()
- Predict to Measure the loss
- Measure the loss to Compute gradients
- Compute gradients to Update
- Update to Clear gradients
- Clear gradients to Predict: next batch
Here is a complete loop for a small model made of a weight tensor and a bias, trained to tell the three classes of the data from the loader section apart:
import torch
import torch.nn.functional as F
from torch.utils.data import TensorDataset, DataLoader
torch.manual_seed(0)
x = torch.randn(1000, 20)
y = x[:, :3].argmax(dim=1)
loader = DataLoader(TensorDataset(x, y), batch_size=64, shuffle=True)
weights = (torch.randn(20, 3) * 0.01).requires_grad_()
bias = torch.zeros(3, requires_grad=True)
optimizer = torch.optim.SGD([weights, bias], lr=0.1)
for epoch in range(5):
total = 0.0
for xb, yb in loader:
scores = xb @ weights + bias
loss = F.cross_entropy(scores, yb)
loss.backward()
optimizer.step()
optimizer.zero_grad()
total += loss.item()
print(epoch, total / len(loader))Reading it from the top:
torch.manual_seed(0)fixes the random numbers the script uses, so it gives the same results each time it runs (the last section explains how far that goes).- The weights start as small random numbers and the bias as zeros. Both are marked with
requires_grad, so PyTorch records what is computed from them and can fill in their gradients. - The optimizer is created once, before training, with the two parameters and a learning rate of 0.1.
for epoch in range(5)runs five passes over the data.for xb, yb in loadertakes one batch of inputs and their labels at a time.scores = xb @ weights + biaspredicts: one score per class for every example in the batch.F.cross_entropyturns those scores and the correct labels into the batch's average loss.loss.backward()works backwards from the loss and stores a gradient inweights.gradandbias.grad.optimizer.step()moves both parameters against those gradients, andoptimizer.zero_grad()clears them so the next batch starts from nothing.loss.item()turns the loss into a plain Python number. Adding up the batch losses and dividing by the number of batches gives a running summary of how the epoch went, printed once per epoch.
When the loop works, the printed loss goes down from one epoch to the next, quickly at first and then more slowly. The exact values depend on the seed, the learning rate, the machine and the PyTorch version, so another computer may print slightly different ones.
Which orders are correct
Some steps have a fixed order: you cannot measure the loss before predicting, compute gradients before there is a loss, or update before there are gradients. Clearing is the step that can move, and where it goes decides whether the loop learns at all.
| Order for each batch | What happens |
|---|---|
| clear, predict, loss, backward, step | Correct. Each batch starts with no stored gradients. |
| predict, loss, backward, step, clear | Correct. Each batch leaves no stored gradients behind. |
| predict, loss, backward, clear, step | Wrong. The gradients are gone when step() runs, so it skips every parameter and nothing is learned. |
| predict, loss, backward, step | Wrong. Each new gradient is added to all the old ones, so the steps follow a sum over past batches and grow out of control. |
The first two orders both appear in PyTorch's own documentation, and they do the same thing: clearing at the start of one batch is the same moment as clearing at the end of the batch before. The rule to remember is that between backward() and step() nothing may touch the gradients, and that they must be cleared once per batch somewhere else.
The third order is easy to miss because it raises no error. Since zero_grad() sets the gradients to None, the optimizer finds no gradient for any parameter and leaves them all as they are. The loss then hovers around its starting value epoch after epoch.
True or false?
Clearing the gradients at the start of each batch and clearing them at the end of each batch are both correct.
True. Either way, every backward() starts from empty gradients and every step() sees the gradients of its own batch.
Calling optimizer.zero_grad() between loss.backward() and optimizer.step() raises an error.
False. It runs without any error. The step finds no gradients and skips every parameter, so the model silently never changes.
Making a run repeat exactly
Two parts of a training run depend on random numbers: the starting weights, and the order the loader shuffles the examples into at each epoch. Change either and every step afterwards changes, so the losses printed at the end come out different too. That makes it hard to tell whether a change you made helped, or the run was only luckier.
The numbers come from a random number generator, which produces a long sequence that looks random but is computed from a starting value called the seed. The same seed gives the same sequence. torch.manual_seed(0) sets the seed of PyTorch's main generator, and a shuffling loader draws its new order for each epoch from that same generator. So one call at the top of the script, before the weights are created and before the first epoch, fixes both the starting weights and every shuffle.
If you want the shuffling to stay the same even when other code draws extra random numbers, give the loader a generator of its own with a fixed seed:
torch.manual_seed(0) # starting weights and anything else random
g = torch.Generator().manual_seed(0) # a separate generator just for shuffling
loader = DataLoader(dataset, batch_size=64, shuffle=True, generator=g)A script that uses only PyTorch's random functions needs nothing more, as long as the loader keeps its default of loading the data in the script's own main process. Python's random module and NumPy have generators of their own, which need seeding only if your code or a library you use draws from them.
Same machine, same version
A seeded run repeats exactly when it runs again in the same environment: the same computer, the same PyTorch version. PyTorch does not promise identical results across releases or across different platforms, and results can also differ between a computer's processor and a graphics card (GPU), even with the same seed.
The reason lies in how computers store decimal numbers. They keep only a fixed number of digits, so every addition is rounded a tiny amount, and the rounding depends on the order of the additions. In Python, (0.1 + 0.2) + 0.3 gives 0.6000000000000001 while 0.1 + (0.2 + 0.3) gives 0.6. A different library version or a different processor may add up the thousands of products in a weighted sum in a different order, and that difference in the last digit grows a little over thousands of steps. The losses on another machine are therefore usually very close to yours, not identical, which is why any training number worth comparing is best read as "about" that value.
True or false?
torch.manual_seed(0) at the top of a script fixes the starting weights, but the loader still shuffles differently on every run.
False. Without a generator of its own, the loader draws each new order from the same main generator, so the seed fixes the shuffles too.
The same seeded script can print slightly different losses on two laptops with different PyTorch versions.
True. A seed repeats a run in the same environment only. Another version or platform may compute in a different order and round differently.