Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

Pretraining a language model

After this lesson: I can read a pretraining loss curve and say when a model stops getting better.

70 min lesson3 commandsJupyterLab data science lab: pandas, Matplotlib and scikit-learn in the browser

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

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

WordWhat it meansExample
Pretrainingnext-token training on a very large corpus
Corpusthe collection of text a model learns from
Validation settext kept out of training to check the model
Loss curvethe loss plotted against training steps
Perplexitye to the power of the lossloss 1.253 gives 3.5
Overfittinglearning 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 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

A 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

StepLines leftWhy
Start1,000Text gathered from many pages
Remove exact copies820A page copied 50 times would be learnt 50 times
Remove junk700Menus, cookie banners and lists of links teach little
Keep back 5%665 to train, 35 to checkThe 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 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Try it: perplexity and the cost of training

Code: python
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

Command
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

Command
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

Command
docker exec jupyter python3 steps/pretrain.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

What pretrain.py printed

StepTraining lossValidation lossPerplexity
03.2193.21925.0
501.0421.4004.1
1000.7421.2673.6
1500.6361.2533.5
2500.5631.2673.5
4000.5311.2933.6

The cells students fill in are left blank in this preview.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

A 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

ParametersTokensOperations, about
1 million20 million120 million million
1 billion20 billion120 billion billion
1 billion1 trillion6,000 billion billion

The cells students fill in are left blank in this preview.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Match 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.

Code: python
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

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teaching a class? Set this module for your students with a teacher guide, marked assignments and a lab for every student.