Velamuvi AIAcademy

Lesson 2 of 11 · Inside an LLM

Pretraining

How LLMs learn in pretraining: trillions of tokens, data cleaning, the next-token loss, perplexity, scaling laws and the compute it takes, with Python maths.

  • 7 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • What pretraining is and what a base model can do
  • Where pretraining data comes from and how it is cleaned
  • How the cross-entropy loss measures and drives learning
  • How much compute pretraining takes, and what scaling laws say

The biggest stage

The data

Pretraining data is measured in trillions of tokens. Typical sources:

  • Web pages, collected by crawlers (the largest share).
  • Books and long-form writing.
  • Code from public repositories, which also seems to help reasoning.
  • Scientific papers, encyclopaedias, maths.
  • Increasingly, synthetic data written by other models, for example worked maths problems.

Raw web data is messy, so a lot of work goes into cleaning it:

StepWhy
Remove duplicatesRepeated text wastes compute and gets memorised
Filter low qualitySpam, gibberish and boilerplate teach little
Remove harmful and personal contentSafety and privacy
Balance the mixDecide how much code, maths, languages and so on
Remove test questionsSo benchmark scores are not inflated by memorised answers

The loss: how the model knows it is wrong

At every position in the training text, the model predicts probabilities for the next token. The actual next token is known, so the model can be scored on how much probability it gave to the right answer.

Training adjusts the parameters, a tiny bit at a time, in the direction that lowers the average loss. Over trillions of tokens, this simple pressure produces grammar, facts and skills.

Try it yourselfPython
import math

# The probability the model gave to the CORRECT next token, at 5 positions
before_training = [0.02, 0.01, 0.05, 0.03, 0.02]
after_training = [0.60, 0.35, 0.80, 0.45, 0.70]

def average_loss(probabilities):
    total = 0
    for p in probabilities:
        total += -math.log(p)          # cross-entropy loss for one token
    return total / len(probabilities)

for name, probabilities in [("before", before_training), ("after", after_training)]:
    loss = average_loss(probabilities)
    print(f"{name:6}  average loss {loss:.3f}   perplexity {math.exp(loss):.1f}")

Before training, the model gives the right token only 1% to 5% probability: a perplexity of about 44 means it is as unsure as if it were choosing among 44 equally likely options. After training, the loss has dropped sharply and the perplexity is under 2.

How much compute?

A useful rule of thumb: training takes about 6 operations per parameter per token. The program below estimates the cost of training an 8-billion-parameter model on 15 trillion tokens, roughly the scale of some well-known open models.

Try it yourselfPython
parameters = 8e9         # an 8-billion-parameter model
tokens = 15e12           # trained on 15 trillion tokens

# Rule of thumb: training takes about 6 operations per parameter per token
operations = 6 * parameters * tokens

gpu_speed = 4e14         # useful operations per second from one modern GPU (rough)
gpu_hours = operations / gpu_speed / 3600

print(f"Training compute: {operations:.1e} operations")
print(f"About {gpu_hours:,.0f} GPU-hours")
print(f"That is about {gpu_hours / 1000 / 24:.0f} days on 1,000 GPUs")
print(f"Tokens per parameter: {tokens / parameters:,.0f}")

Hundreds of thousands of GPU-hours, for a model that is small by today's standards. The largest models need many times more, which is why only a handful of organisations can pretrain them from scratch.

Scaling laws

A 2022 study from DeepMind (often called the Chinchilla paper) found that for a fixed compute budget, the best results came from about 20 tokens per parameter. Since then, many models are trained on far more tokens than that, like the 1,875 per parameter above, because a smaller model trained for longer is cheaper to run for millions of users, even if training cost more.

Common mistakes

Practice exercise

Work out the training loss a model gets on three tokens.

Your solutionPython
import math

# Probabilities the model gave to the correct next token at 3 positions
probabilities = [0.5, 0.25, 0.8]

# Print the average cross-entropy loss (the average of -log(p))
# with 3 decimal places
Knowledge check

During pretraining, what does the cross-entropy loss measure?

Summary

  • Pretraining teaches a model to predict the next token over trillions of tokens; the result is a base model.
  • Data comes from the web, books, code and more, and is heavily cleaned and balanced.
  • The cross-entropy loss punishes low probability on the right token; perplexity is its exponential.
  • Training costs roughly 6 operations per parameter per token: huge amounts of compute.
  • Scaling laws make results predictable; many models now train on far more than 20 tokens per parameter to be cheaper to run.

Next: how a base model becomes a helpful chat model.

Finished reading? Tick it off to track your progress.