Months of training, one simple question
A large language model starts as millions of random numbers. Weeks or months later it can write an email. In between, it answered one question billions of times: what comes next?
This first stage is called pretraining. You will run a small one in the lab and read its loss curve like an engineer.
By the end of this lesson
Note
I can read a pretraining loss curve and say when a model stops getting better.
Key words
| Word | What it means | Example |
|---|---|---|
| Pretraining | next-token training on a very large corpus | |
| Corpus | the collection of text a model learns from | |
| Validation set | text kept out of training to check the model | |
| Loss curve | the loss plotted against training steps | |
| Perplexity | e to the power of the loss | loss 1.253 gives 3.5 |
| Overfitting | learning the training text so well that new text gets worse |
The cells students fill in are left blank in this preview.
Starter
Have a go
Starter
4 questionsA corpus is cleaned before it is used
Pretraining uses the same loop as module 90: guess the next token, measure the surprise, nudge the numbers. What changes is the corpus: web pages, books, code and more, often trillions of tokens.
Raw text is messy. Teams remove exact and near copies, drop pages that are mostly menus or spam, and filter out personal data and harmful text. A part is kept back as a validation set and never trained on.
Worked example: cleaning a small corpus
| Step | Lines left | Why |
|---|---|---|
| Start | 1,000 | Text gathered from many pages |
| Remove exact copies | 820 | A page copied 50 times would be learnt 50 times |
| Remove junk | 700 | Menus, cookie banners and lists of links teach little |
| Keep back 5% | 665 to train, 35 to check | The check must use text the model never saw |
The cells students fill in are left blank in this preview.
Check
Have a go
Check
3 questionsTry it: perplexity and the cost of training
import math
# Perplexity: the loss turned back into "how many choices".
for loss in [3.219, 1.253, 0.531]:
print("loss", loss, "perplexity", round(math.exp(loss), 1))
# Training compute: about 6 operations per parameter per token.
params = 1000000000 # one billion parameters
tokens = 20 * params # 20 tokens for each parameter
operations = 6 * params * tokens
print("tokens", tokens, "operations", operations)
# A machine doing 100 million million operations a second:
seconds = operations / 100000000000000
print("days", round(seconds / 86400, 1))
# Change params to 7000000000. How many days now?
Make a free account to save your work and track your progress.
Two loss curves tell you more than one
During training you watch two numbers. The training loss is measured on text the model is learning from. The validation loss is measured on the text kept back.
Early on, both fall. Later the training loss keeps falling while the validation loss stops, then rises. The model is now learning the training text by heart, which is overfitting. The best point is where the validation loss was lowest.
Write the pretraining script into the lab
docker exec jupyter sh -c "printf '%s\n' 'import numpy as np' 'lines = [' ' \"the bus to the station leaves at nine\",' ' \"the bus to the market leaves at ten\",' ' \"the train to the city leaves at eight\",' ' \"the canteen opens at noon and shuts at two\",' ' \"the library opens at nine and shuts at six\",' ' \"the shop opens at eight and shuts at five\",' ' \"the bus to the park leaves at noon\",' ' \"the train to the coast leaves at six\",' ' \"the gym opens at seven and shuts at ten\",' ' \"the bus to the school leaves at eight\",' ']' 'train = \" . \".join(lines[:8]) + \" .\"' 'valid = \" . \".join(lines[8:]) + \" .\"' 'chars = sorted(set(train + valid))' 'V = len(chars)' 'def questions(t):' ' ids = [chars.index(c) for c in t]' > steps/pretrain.py"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Finish writing the script
docker exec jupyter sh -c "printf '%s\n' ' return np.array([ids[k] * V + ids[k + 1] for k in range(len(ids) - 2)]), np.array(ids[2:])' 'xt, yt = questions(train)' 'xv, yv = questions(valid)' 'W = np.zeros((V * V, V))' 'def loss(x, y):' ' p = np.exp(W[x]) / np.exp(W[x]).sum(axis=1, keepdims=True)' ' return -np.log(p[np.arange(len(y)), y]).mean(), p' 'print(\"train characters\", len(train), \"valid characters\", len(valid), \"vocabulary\", V)' 'for step in range(401):' ' lt, p = loss(xt, yt)' ' if step % 50 == 0:' ' lv = loss(xv, yv)[0]' ' print(\"step\", step, \"train\", round(lt, 3), \"valid\", round(lv, 3), \"perplexity\", round(float(np.exp(lv)), 1))' ' p[np.arange(len(yt)), yt] -= 1' ' np.add.at(W, xt, -10.0 * p / len(yt))' >> steps/pretrain.py"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Train on eight lines, check on two
docker exec jupyter python3 steps/pretrain.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
What pretrain.py printed
| Step | Training loss | Validation loss | Perplexity |
|---|---|---|---|
| 0 | 3.219 | 3.219 | 25.0 |
| 50 | 1.042 | 1.400 | 4.1 |
| 100 | 0.742 | 1.267 | 3.6 |
| 150 | 0.636 | 1.253 | 3.5 |
| 250 | 0.563 | 1.267 | 3.5 |
| 400 | 0.531 | 1.293 | 3.6 |
The cells students fill in are left blank in this preview.
Check
Have a go
Check
3 questionsA common mistake
Warning
Many people think a lower training loss always means a better model. It only means the model fits the text it has seen. Judge a model on text it has not seen, which is why the validation set is never trained on.
Scale is parameters times tokens
Training cost grows with two things: the number of parameters and the number of tokens read. A common rule of thumb is about 6 operations per parameter per token.
A widely cited 2022 study found that, for a fixed budget, about 20 tokens per parameter gave the lowest loss. Many models since train on far more tokens, because a smaller model is cheaper to run afterwards.
Worked example: the rule of thumb
| Parameters | Tokens | Operations, about |
|---|---|---|
| 1 million | 20 million | 120 million million |
| 1 billion | 20 billion | 120 billion billion |
| 1 billion | 1 trillion | 6,000 billion billion |
The cells students fill in are left blank in this preview.
Check
Have a go
Check
3 questionsMatch each word to its meaning
Have a go
Loading…
Your answers are marked here and are not kept. An account keeps your marks.
Assignment: check a pretraining run
Write four small checks a team runs around pretraining.
dedupe(lines) keeps the first copy of each line, comparing lines after .strip() and .lower(). perplexity(loss) is e to the power of the loss. best_step(steps, losses) returns the step with the lowest validation loss, the earlier one on a tie. train_flops(params, tokens) uses the rule of 6 operations per parameter per token.
import math
def dedupe(lines):
# Keep the first copy of each line. Two lines are copies when they match
# after .strip() and .lower(). Return the lines kept, as they were written.
return lines
def perplexity(loss):
# math.exp of the loss.
return 0
def best_step(steps, losses):
# The step with the lowest validation loss. On a tie, the earlier step.
return steps[-1]
def train_flops(params, tokens):
# About 6 operations per parameter per token.
return 0
Make a free account to save your work and track your progress.
Exit quiz
Have a go