Chapter 13: The Training Loop¶
Figure 13.1: The model makes predictions, measures its error, and adjusts its weights to improve.
With our data batched and ready from Chapter 12, we have a model that can guess the next character, but right now, its guesses are no better than chance. In this chapter, we will write the loop that teaches it the patterns of the text it reads.
In this chapter you will:
- Understand gradient descent as walking down a hill.
- See what the learning rate does, by measuring three of them.
- Build the four-step training loop.
- Watch the model learn in real time, and read what its loss means.
Words to Know
- Optimizer: The algorithm that updates the model's weights. We use Adam, a popular and steady choice.
- Gradient: The direction we need to move our weights to increase the error. We move in the opposite direction to decrease it.
- Backpropagation: The mathematical process of calculating the gradient for every single weight in the model.
- Learning Rate: How far the optimizer moves the weights on each step. If it is too small, training crawls, and if it is too large, it can overshoot.
Theory¶
Walking Down the Hill¶
How does a model learn? Well, say you are on a bumpy hillside and you're blindfolded. You want to get to the bottom of that hill (where the loss is at its minimum).
You would not be able to see how far down that hill goes but you could feel the direction of the hill around you. If the hill was higher to your right you would know to step to your left.
Figure 13.2: The optimizer takes small steps down the loss landscape to lower the loss.
This is gradient descent (Figure 13.2). The slope under your feet is the gradient, calculated by backpropagation, and taking a small step downhill is the optimizer updating the weights.
The Four-Step Loop¶
Training is a repetitive cycle that we run thousands of times (Figure 13.3):
Figure 13.3: The four steps of the training loop.
- Forward Pass: We pass a batch of data through the model to get its predictions.
- Calculate Loss: We compare the predictions to the correct targets using cross-entropy.
- Backward Pass: PyTorch automatically works out the gradient for every weight in the model (
loss.backward()). The part of PyTorch that does this is called autograd. - Optimizer Step: The optimizer adjusts the weights slightly in the right direction (
optimizer.step()).
How Big Should the Step Be?¶
Gradient descent tells you which way is downhill but not how far to walk. That distance is the learning rate, and it is the one number beginners most often get wrong.
Our config sets it to 0.0003. To see where that comes from, train the same model three times from the same starting weights, changing only the learning rate:
| src/examples/ch13_learning_rate.py | |
|---|---|
$ python src/examples/ch13_learning_rate.py
lr=0.003 start 4.33 after 150 steps 2.35
lr=0.0003 start 4.33 after 150 steps 2.60
lr=3e-05 start 4.33 after 150 steps 3.31
Most people need the lesson on the bottom row. At 0.00003 we are taking such small steps that we have hardly moved by 150 steps. The loss is at 3.31 compared to 4.17 if we guessed randomly. So it's learning just extremely slowly.
You may wonder about the top row. With 10x the learning rate we got there faster with a loss of 2.35 versus our learning rate which reached 2.60. Why doesn't the book use this?
Because 150 steps is not 3,000 steps. When taking larger steps you run the risk of bouncing off the bottom of the valley or blowing up. Our example only ran for 150 steps so we don't know. 0.0003 will get us to 1.74 with the whole example. You could try running 0.003 for 3000 steps and see what happens.
The "Aha!" Moment: It Learned¶
At the beginning of training, loss is about 4.3. Recall from Chapter 11 that completely random guessing between 65 characters has an expected loss of 4.17. Initially our model is even worse than random!
But as the loop runs, the numbers start to move.
Figure 13.4: Over 3,000 steps, the training loss falls from 4.33 to 1.74.
The loss falls quickly (Figure 13.4). By step 300 it is already at 2.7, and by step 3,000 it reaches 1.74.
What the Loss Number Actually Means¶
It's pretty difficult to understand what a loss of 1.74 means by itself. So we can convert this to a probability.
As you can see there is only one value used for cross-entropy. It's the probability the model assigned to the actual next character. Cross-entropy takes this value and uses its negative logarithm as the loss. Undoing the logarithm allows us to get the probability that we can understand:
$ python src/examples/ch13_loss_meaning.py
random guessing loss 4.17 -> 1.5% on the right character
step 1 loss 4.33 -> 1.3% on the right character
step 300 loss 2.70 -> 6.7% on the right character
step 3000 loss 1.74 -> 17.6% on the right character
At the start, the model assigns around 1.3% probability to the correct character. This is slightly worse than the 1.5% we'd get if we picked from the 65 possible characters at random. At the end of training it has increased this probability 12x which is great. Though we still have our model guessing the wrong answer 4 out of every 5 times.
Keep this in mind when thinking about your model. It knows what letters follow other letters. It knows about word length, end of line and who is speaking. It doesn't know English. And it definitely doesn't know what any of this means. We will show you this in Chapter 17. Our model will write "Praviour soul to shall that that are the and not,". You can see Shakespeare but no meaning.
The "Training" section of our map is finished. Our model knows how to generate the next character in its corpus.
Code¶
The core loop is simple to write in PyTorch.
Run the full script to watch the loss fall:
$ python src/ch12_train.py
Chapter 13: The Training Loop
Model parameters: 824,832
Training on : cpu
Steps : 3,000
Batch size : 32
Block size : 128
Starting training... (eval every 300 steps)
step 1/3000 | train loss: 4.3280 | val loss: 4.2114 | elapsed: 3s | ETA: 7595s
step 300/3000 | train loss: 2.7016 | val loss: 2.5433 | elapsed: 55s | ETA: 496s
...
step 900/3000 | train loss: 2.2633 | val loss: 2.1889 | elapsed: 160s | ETA: 372s
step 1200/3000 | train loss: 2.1185 | val loss: 2.1053 | elapsed: 210s | ETA: 314s
step 1500/3000 | train loss: 2.0174 | val loss: 2.0078 | elapsed: 248s | ETA: 248s
What just happened:
- Line 1 creates an Adam optimizer to handle the weight updates.
- Line 3 shows 3,000 steps of training. Since the log above reached the halfway point after 248 seconds, the whole run took roughly eight minutes on the machine that generated it. On the author's 2020 laptop (described in the Preface), that same run took 20-30 minutes.
- Lines 11-13 compute gradients and perform the weight update. During the run you see the training loss drop from 4.33 to 1.74. Two losses are printed to the log. The train loss is calculated on text that the model sees as it trains. The val loss is calculated on the held-out text from Chapter 4.
- We saved the trained weights to a file so we can load them later.
Shape Check:
Table 13.1 lists the parameter count.
Table 13.1: Total adjustable parameters in the language model.
| Variable | Shape | Meaning |
|---|---|---|
model.parameters() |
824,832 |
The total number of individual numbers (weights) the optimizer is adjusting. |
Try It¶
We can see the mechanics of PyTorch's automatic gradients on a tiny scale.
Lines 19, 26, and 27 show PyTorch computing the gradient and using it to adjust the weight toward the target.
$ python src/examples/ch13_autograd_demo.py
Initial weight: 2.00
Step 1: Output=6.00, Loss=36.00, Gradient=-36.00
Step 2: Output=11.40, Loss=0.36, Gradient=-3.60
Step 3: Output=11.94, Loss=0.00, Gradient=-0.36
Final weight: 4.00
Try It
Open src/examples/ch13_autograd_demo.py. Change the starting weight to 10.0 and watch how the gradient pulls it down instead of pushing it up, always aiming for the target output of 12.
In Business
Training is where you make the investment. When your company trains its house-style assistant, it is paying for compute time to run this loop billions of times on thousands of documents. The loss curve becomes your lead dashboard metric because as long as validation loss continues to decrease, your assistant is improving its emulation of your corporate voice.
Watch Out
Always remember to run optimizer.zero_grad() before loss.backward(). By default, PyTorch accumulates gradients (it sums them). If you forget to zero them before starting the backward pass, your model will take a step based on a mix of the current batch and all the previous batches and will thus go in the wrong direction.
Key Takeaways¶
- Training is a loop of four steps: Forward, Loss, Backward, Step.
- Gradient descent finds the lowest loss by taking small steps downhill.
- We use the
torch.optim.Adamoptimizer to manage the complex math of updating the weights. - The model starts by guessing blindly (loss > 4.17), but over 3,000 steps, it learns the patterns of the text and the loss falls.
Check Your Understanding¶
- What are the four main steps inside the training loop?
- What does
loss.backward()actually do? - Why is a dropping loss curve a good sign?
Assignment¶
Assignment 13: Shrink the step
About 15 minutes. You change one number and write no new code. Work in this chapter's Colab notebook or on your own laptop.
- Run it. Run
src/examples/ch13_autograd_demo.pyas it is. Copy the five lines it prints: the initial weight, the three steps and the final weight. - Change one number. Find the line
weight -= 0.05 * weight.grad. The0.05is the learning rate: how far the weight moves on each step. Change0.05to0.0003and run the script again. - Compare. Which printed lines are the same in both runs? After three steps, how close does the output get to the target of 12 in each run? Is the loss still falling in the second run?
- Explain it. In two or three sentences a manager could follow, say what a learning rate that is too small for the job costs a company that pays for every training step.
Hand in: both sets of five lines, your answers to step 3, and your sentences.
Further Reading¶
How a network learns anything at all. When a network with layers in the middle gave a wrong answer, nobody could say which of the middle weights was at fault. This paper sent the error backwards through the network and gave each weight a share of the blame in proportion to how much it moved the result. Every model in this book learns that way, and so does every model in production today. In the training loop, loss.backward() does this job.
The optimizer on one line of your training loop. Backpropagation says which way each weight should move but not how far. Adam gives every weight its own step size, adapted from how that weight has been moving recently, so rarely used weights can take larger steps and volatile ones settle down. It is the default in the training loop in Chapter 13 and in most training loops elsewhere.
Kingma, D. P., & Ba, J. (2014). Adam: A method for stochastic optimization (arXiv:1412.6980). arXiv. https://doi.org/10.48550/arXiv.1412.6980
Rumelhart, D. E., Hinton, G. E., & Williams, R. J. (1986). Learning representations by back-propagating errors. Nature, 323, 533–536. https://doi.org/10.1038/323533a0
Next up: Chapter 14: Checkpointing