The training loop: one step, one epoch
Backpropagation, gradient descent, batches, dropout and early stopping each have their own page on this site. This page is the map: it shows where each of those pieces sits inside one turn of the training code.
Short answer. Training is a loop that repeats: take a batch → make a guess → measure how wrong it is → compute the gradient of that error → nudge the weights a little. One update of the weights is one step. Using all the data once is one epoch. At the end of every epoch, the model is validated on data kept aside.
Each press of Next moves one box around the loop. Orange is the current box and the current batch ("now"), green with ✓ marks batches already used this epoch, and purple with dashes is validation. The numbers in the strip are sample numbers. The model has one weight, ŷ = w·x; the loss is the mean squared error; the learning rate is η = 0.05; the batch size is 4; there are 16 training samples and 4 separate validation samples. The data is made up (y ≈ 2x), and the shuffle uses a fixed seed, so it is the same every time you open the page.
Try this. ① The first box is the first batch of epoch 1 (samples #9 #8 #12 #4). Press Next four times: at the update box the gradient −6.16 moves w from 0 to 0.308, and the step count becomes 1. ② At box 20 (the update for batch 4), w = 0.988. On the next box the strip is used up, so the loop drops into validation and plots a validation loss of 1.78. w does not change in this box. ③ The box after that starts epoch 2 in a different shuffled order (#15 #16 #1 #13 …). ④ At the last box, 63, the step count is 12, w = 1.746, and the validation loss went 1.78 → 0.454 → 0.121, falling every epoch. w is on its way toward 2.
Definitions
The text below explains with an experiment and code. The textbook definitions are as follows. The training data are N examples (xᵢ, yᵢ), and w stands for one parameter (weight) of the model.
- training loop
- The process that repeats the following for a set number of epochs (or until it is stopped): take a batch, get the outputs with a forward pass, measure the loss, use backpropagation to get the gradient of the loss for each parameter, and update the parameters with the optimizer. In each epoch the training part is followed by a validation part.
- batch, batch size
- A batch is the group of examples that pass through the model before the parameters are updated once. The batch size B is the number of examples in that group.
- loss
- One number that sums up how far the model's outputs are from the answers. If ℓ is the loss of one example, the loss of a batch is the mean of the example losses in the batch. The experiment in the text uses squared error as ℓ.
- step
- One update of the parameters with the loss gradient of one batch. With gradient descent, each parameter moves against its gradient by the gradient times the learning rate η.
- epoch
- One round of training that uses every example in the training data once. With batch size B, one epoch is N divided by B, rounded up, steps.
- validation
- Measuring the loss on data held out from training. It computes no gradients and does not update the parameters. It is usually done at the end of each epoch.
1. What the training loop is
The PyTorch tutorial calls training a model "an iterative process". In each turn, the model makes a guess about the output, measures how wrong the guess is (the loss), collects the derivatives of the error with respect to its parameters (the gradients), and updates the parameters with gradient descent. For the model in experiment ①, that is:
ŷᵢ = w · xᵢ forward pass: the guess
L = (1/B) · Σᵢ (ŷᵢ − yᵢ)² loss: mean squared error over the batch
g = dL/dw = (1/B) · Σᵢ 2 (ŷᵢ − yᵢ) · xᵢ backward pass: gradient of the loss
w ← w − η · g update
w: the weight. It is the only value this model learns.xᵢ,yᵢ: the input and the answer of the i-th sample in the batch.ŷᵢ: the model's guess.B: the batch size. 4 in the experiment.Σᵢ: add up over the samples in the batch.L: the loss. How wrong the guesses are, as one number.g: the gradient. How much the loss changes when w grows a little.η: the learning rate. How much to change w at once. 0.05 in the experiment.
The experiment's model is short enough that we wrote out the derivative g directly. In a neural network with many layers, backpropagation splits this derivative into pieces and computes it box by box.
The tutorial calls each iteration of this loop an epoch and splits an epoch into two parts:
- The train part (Train Loop): iterate over the training data and try to converge to the best parameters.
- The validation/test part (Validation/Test Loop): iterate over the test data to check whether the model is improving.
In experiment ①, the five boxes at the top are the train part, and the dashed box is the validation part. The validation part only makes guesses and measures the loss. It does not change w. How to split the data is on Data splits and leakage, and how to use the validation loss to decide when to stop is on Early stopping.
2. Why clear the gradients?
The update box has two lines. optimizer.step() updates the parameters with the gradients collected so far, and optimizer.zero_grad() sets the gradients back to 0. In the tutorial's words: "Gradients by default add up; to prevent double-counting, we explicitly zero them at each iteration." When loss.backward() stores the gradient of the loss for each parameter, it does not wipe the old value. It adds on top of it.
Here are the first two steps of experiment ①:
| Step | This batch's gradient | Cleared: gradient used → new w | Not cleared: gradient used → new w |
|---|---|---|---|
| 1 (batch 1, w = 0) | g₁ = −6.16 | −6.16 → 0.308 | −6.16 → 0.308 |
| 2 (batch 2, w = 0.308) | g₂ = −6.017 | −6.017 → 0.609 | g₁ + g₂ = −12.177 → 0.917 |
Without clearing, the second step uses batch 1's gradient a second time, so it moves about twice as far. As the steps go on, the gradients of every earlier batch keep getting added again. The tutorial's code runs loss.backward() → optimizer.step() → optimizer.zero_grad(). Skipping the clear on purpose to collect gradients over several batches is covered on Batch size and gradient accumulation.
3. Epochs, batches and steps
| Word | Meaning | In experiment ① |
|---|---|---|
| Batch | The group of samples you look at before one update of the weights. In the tutorial's words, the batch size is "the number of data samples propagated through the network before the parameters are updated" | 4 samples, one bracket on the strip |
| Step | One update of the weights. One step per batch | The step count goes up by 1 at every update box |
| Epoch | Seeing every training sample once. In the tutorial's words, the number of epochs is "the number of times to iterate over the dataset" | When all 16 cells of the strip are used, validate and add 1 to epochs done |
| Learning rate | In the tutorial's words, "how much to update models parameters at each batch/epoch" | η = 0.05 |
steps per epoch = ⌈N ÷ B⌉
N: the number of training samples. 16 in the experiment.B: the batch size. 4 in the experiment.⌈ ⌉: round up. If N does not divide evenly, the last batch is smaller, and it still counts as a step.
In the experiment, one epoch is ⌈16 ÷ 4⌉ = 4 steps, and 3 epochs are 12 steps. With 18 samples it would be ⌈18 ÷ 4⌉ = 5 steps (the last batch has 2). What changes when you change the batch size is on Batch size and gradient accumulation.
4. The map: where to read more about each box
| Box | Code | What it does | More |
|---|---|---|---|
| Take a batch | for X, y in dataloader | Takes the next batch from the training data | Batch size and gradient accumulation |
| Forward pass | pred = model(X) | Makes a guess with the current weights | Neural networks |
| Loss | loss = loss_fn(pred, y) | Turns how wrong the guess is into one number. Classification and regression use different losses | Cross-entropy, Regression losses |
| Backward pass | loss.backward() | Computes the gradient of the loss for each parameter | Backpropagation |
| Update | optimizer.step()optimizer.zero_grad() | Moves a little against the gradient, then clears the gradient. The learning rate sets how far; when to lower the learning rate and a penalty that keeps weights small are set separately | Gradient descent, Learning rate schedules, Weight decay |
| Train and eval modes | model.train()model.eval() | Dropout and batch normalization behave differently in training and in evaluation | Dropout, Batch norm and layer norm |
| Validate and stop | torch.no_grad() | At the end of an epoch, measures the validation loss on held-out data, and stops when it no longer improves | Data splits and leakage, Early stopping, Overfitting |
5. In code: train_loop and test_loop
These are the PyTorch tutorial's two functions, cut down. Each line matches one box of experiment ①.
def train_loop(dataloader, model, loss_fn, optimizer):
model.train() # training mode: matters for dropout and batch norm
for X, y in dataloader: # take a batch
pred = model(X) # forward pass
loss = loss_fn(pred, y) # loss
loss.backward() # backward pass: adds a gradient to each parameter
optimizer.step() # update
optimizer.zero_grad() # gradients back to 0
def test_loop(dataloader, model, loss_fn):
model.eval() # evaluation mode
total = 0
with torch.no_grad(): # do not compute gradients
for X, y in dataloader:
total += loss_fn(model(X), y).item()
return total / len(dataloader) # mean of the per-batch losses
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
for epoch in range(epochs): # each epoch: the train part, then the validation part
train_loop(train_dataloader, model, loss_fn, optimizer)
val_loss = test_loop(val_dataloader, model, loss_fn)
model.eval() and torch.no_grad() do different jobs. The tutorial says torch.no_grad() "ensures that no gradients are computed during test mode", and that model.train() is "important for batch normalization and dropout layers".
Where it is used
Training a model, as the PyTorch tutorial describes it, is this loop repeated (section 1). Experiment ① has a single weight, but a neural network with many layers goes around the same boxes; only the gradient is split into pieces and computed box by box by backpropagation. When you read training code, match each line to a box of the loop, as with train_loop and test_loop in section 5. Where pieces like the loss, learning rate schedules, dropout and early stopping go is on the map in section 4. Values the loop cannot decide by itself, like the learning rate or the decay strength, are picked by a hyperparameter search, which runs the loop to the end for each candidate.
FAQ
Some code calls zero_grad before backward. Which is right?
Both work. The one rule is to clear the old gradients before the next backward(). The PyTorch tutorial clears them at the end of the loop, in the order backward → step → zero_grad. There is also a way to skip clearing on purpose and collect gradients over several batches (Batch size and gradient accumulation).
Do I need both model.eval() and torch.no_grad() when validating?
Yes. They do different jobs. model.eval() switches dropout and batch normalization to their evaluation behavior, and torch.no_grad() turns off gradient computation. With torch.no_grad() alone, dropout is still on while you validate (Dropout).
Why does the validate box never update the weights?
The validation data is held out to measure how well the model does on data it has not seen. If you updated on it, the model would have seen it, and the validation loss would no longer tell you how the model does on new data. The tutorial also describes the validation/test part as checking whether the model is improving.
Words
| Word used here | Other names in books and code |
|---|---|
| training loop | The tutorial calls it the optimization loop and splits one turn into a train loop and a validation/test loop |
| batch, batch size | mini-batch |
| step | update |
| one pass over all the data | epoch |
| making a guess | forward pass |
| computing the gradient | backward pass, backpropagation |
| the thing that updates the weights | optimizer |
| how far one update moves | learning rate |
| the values that are learned | parameters, weights |
| training mode, evaluation mode | model.train(), model.eval() |
Sources
- PyTorch tutorial: Optimizing Model Parameters (training is an iterative process; what epochs, batch size and learning rate mean; an epoch and its train loop and validation/test loop;
zero_grad,backward,stepand their order; gradients add up by default;model.train(),model.eval(),torch.no_grad()).