Lesson 5 of 186 min
The training loop
Training repeats five lines on batch after batch, epoch after epoch: work out the scores and the loss, clear the old slopes, find the new ones, and step; and after each epoch, check pictures the network never learns from.
After this lesson you can write forward, loss, backward and step in PyTorch.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
Why the slopes become None
zero_grad() doesn't fill .grad with zeros. It sets it to None, and step() skips a weight whose .grad is None. That's why the wrong order gives no error: the step just has nothing to use. Ask for zeros with set_to_none=False. PyTorch's zero_grad reference
w = nn.Linear(2, 1)
opt1 = torch.optim.SGD(w.parameters(), lr=0.1)
w(torch.ones(1, 2)).sum().backward()
opt1.zero_grad()
print(w.weight.grad)
before = w.weight.clone()
opt1.step()
print(torch.equal(before, w.weight))None True
Keep both losses each epoch
Real code keeps the training loss and the validation loss of every epoch, to plot them later. Add up each batch's loss times its size, then divide by the number of pictures. Run it with a fresh model and optimizer, as in the lesson's program. Plot them with plt.plot(history["train"]) and plt.plot(history["val"]).
history = {"train": [], "val": []}
for epoch in range(30):
model.train(); total = 0.0
for x, y in loader:
loss = F.cross_entropy(model(x), y)
opt.zero_grad(); loss.backward(); opt.step()
total += loss.item() * len(x)
history["train"].append(total / len(train))
model.eval()
with torch.no_grad(): history["val"].append(F.cross_entropy(model(x_val), y_val).item())print(round(history["train"][-1], 3), round(history["val"][-1], 3))0.118 0.171
Predict with inference_mode
For code that only predicts, PyTorch offers torch.inference_mode(), a stricter no_grad(). It keeps no record and runs a little faster. What it makes can't go into a backward pass later, so keep no_grad() for a check inside training. PyTorch's inference_mode reference
model.eval()
with torch.inference_mode():
scores = model(x_val)
print(scores.requires_grad, scores.is_inference())
print((scores.argmax(1) == y_val).float().mean().item())False True 0.9555555582046509
Keep a test set for the end
You watch the validation set every epoch, and you choose things by it. So its score flatters the model a little. Real projects keep a third set, the test set, and open it once, at the very end. Split twice: first the test set, then the validation set from what is left.
X_rest, X_test, y_rest, y_test = train_test_split(
Xn, digits.target, test_size=0.2, stratify=digits.target, random_state=0)
X_tr2, X_va2, y_tr2, y_va2 = train_test_split(
X_rest, y_rest, test_size=0.2, stratify=y_rest, random_state=0)
print(len(X_tr2), len(X_va2), len(X_test))1149 288 360
The same loop in Keras
Keras writes the loop for you: compile names the optimizer and the loss, and fit runs forward, loss, backward and step, batch after batch, epoch after epoch. Keras 3 can run on PyTorch. Hugging Face's Trainer and PyTorch Lightning do the same: these five lines are inside them. Keras's fit reference
import os; os.environ["KERAS_BACKEND"] = "torch"
import keras
keras.utils.set_random_seed(0)
net = keras.Sequential([keras.Input((64,)),
keras.layers.Dense(32, activation="relu"), keras.layers.Dense(10)])
net.compile(optimizer=keras.optimizers.Adam(0.001), metrics=["accuracy"],
loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True))
fit = net.fit(X_tr, y_tr, batch_size=32, epochs=30,
validation_data=(X_va, y_va), verbose=0)
print(round(fit.history["val_loss"][-1], 3), round(fit.history["val_accuracy"][-1], 3))0.173 0.953
Run on Python 3.13.3, PyTorch 2.15.0, scikit-learn 1.9.1 and Keras 3.16.0. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: Stochastic gradient descent
The same work, two ways: one step on all 1,000 examples, or 20 steps on batches of 50 picked at random. Which usually ends lower?
2 of 3
A training loop runs loss.backward(), then opt.zero_grad(), then opt.step(). Nothing crashes. For 30 epochs, the loss prints 2.33. What is wrong?
3 of 3
The loader shuffles the 1,437 training pictures and hands them out in batches of 64. Training runs for 10 epochs. How many steps does it take in all?
The ideas in this lesson
- The training loop
- For each batch: scores, loss, clear the slopes, backward, step. Batch after batch, epoch after epoch.
- Checking each epoch
- After each epoch, score the validation set in evaluation mode, with no graph recorded; then switch back to training.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
The training loop
Here's a challenge. A network learns in small steps, again and again. Each step is the same five lines of code. Put two of them in the wrong order. The code can still run, with no error at all. The network just never learns. So what does each line do, and in what order?
Keep your guess
Hold on to your guess. These five lines will train the digits network, on the pictures it learns from. There are almost fifteen hundred of them. Let's run them one at a time.
Forward, then the loss
One training step works on one batch: thirty-two pictures of handwritten digits. The first line runs the network on them. That's the forward pass, and it gives ten scores for each picture. The second line turns the scores into one number for how wrong they were: the loss. Two point three seven. That's about two point three, the loss of a network that hasn't learned anything yet.
Clear, backward, step
Then three more lines: clear the old slopes, find new ones, and take a step.
Opt dot zero grad empties every weight's dot grad, because backward adds new slopes to the old ones.
Loss dot backward fills it with this batch's slopes. Here are the slopes of the last layer, lit up. Then opt dot step moves every weight a small step downhill. The optimizer is Adam. Adam got all the weights to take care of, from model dot parameters. And the same thirty-two pictures now give two point three six: a little lower.
The order breaks it
Now, back to the order. Swap two lines: put zero grad after backward. What goes wrong?
Backward fills the slopes. Then zero grad empties them. So the step has no slopes to use. The same thirty-two pictures still give two point three seven. And there's no error.
Zero grad can go first, or last, once the step has used the slopes. Never between backward and step.
Batch after batch: an epoch
One step barely moves it. So the loader shuffles all the pictures, and hands them out in batches of thirty-two. How many steps does it take to go through every picture once?... Forty-five, and the last batch has only twenty-nine. That's one epoch. A loop over the batches sits inside a loop over thirty epochs. That's thirteen hundred and fifty steps, in under a second.
The loss falls
How can you tell it's learning? Watch the loss. Each batch's loss jumps around, so watch its average over each epoch. Before training, that's about two point three. After one epoch, a little lower. After thirty, zero point one two. And with zero grad in the wrong place, every one of those steps stays at about two point three.
Check on pictures it never learns from
A training loop goes through its pictures, batch by batch, epoch after epoch, and its loss falls. But is it learning digits, or only these pictures?
So after each epoch, score the three hundred and sixty pictures set aside, which it never learns from. That's the validation set. After thirty epochs, how many will it get right?
After one epoch, forty-six percent. And after thirty... Just over ninety-five percent. And the loss on those pictures falls to zero point one seven.
Three lines around the check
Three lines go around that check. Model dot eval puts the network in test mode.
Some layers act differently while training: one kind switches off neurons at random. This network doesn't have any yet, but a network that has them needs this line. Torch dot no grad tells PyTorch not to keep its record of every box. There's no backward after it, so the record isn't needed. That saves time and memory.
And model dot train switches back to training mode, before the next epoch. Forget it, and those layers stay in test mode while the network learns.
In code
Here's the whole program. The loader, the optimizer, the loop with its five lines, and the check after each epoch, with a print. Its last line is epoch thirty. The loss on the pictures set aside is zero point one seven. And just over ninety-five percent are right.
And here's nanochat. It's a script that trains a small model like ChatGPT, from scratch. It runs the same lines: backward, then step, then zero grad, last. For a bigger model, you change the model, the data and the loss. The loop stays the same.
Five lines and a check
So, each step works out the scores and the loss, clears the slopes, runs backward, then takes a step. The loop does that batch after batch, for epoch after epoch. And after each epoch, it checks the network on pictures it never learns from.
The lab
That's the end of this unit. In the lab, you use these two lessons to train the digits network yourself.
Five lines
These five lines, in this order, are how a network learns. Now try it on this lesson's page, and take the quiz. Leave out the line that clears the slopes, and train.
You use this lesson in Lab 2: Train the digit reader, which comes next.
Facts last checked on .
