Pretraining

Pretraining teaches a transformer general language patterns by running next-token prediction over enormous text corpora.

The Big Question

We now understand transformers, tokenisation, language modelling, and scaling. But there is still a practical question.

Suppose we want to build a language model from scratch. What actually happens?

Pretraining is the process of teaching a randomly initialized transformer general language patterns by exposing it to enormous amounts of text and training it with next-token prediction.

The Goal

Pretraining creates a foundation model. Like a child first learning language, facts, common sense, and patterns before specializing in medicine or programming, a pretrained model learns broad text structure before later fine-tuning or alignment.

Core Intuition

Pretraining is where the whole course finally runs end to end. Data becomes tokens. Tokens become embeddings. The transformer produces logits. Cross-entropy measures error. Backpropagation computes gradients. The optimizer updates weights.

One update teaches the model almost nothing. Trillions of tokens and countless updates gradually create a model that captures grammar, facts, code patterns, style, and many forms of reasoning.

The Entire Pipeline

1Collect raw textGather books, websites, code, papers, documentation, and multilingual data
2Clean the dataDeduplicate, filter spam, remove malformed documents, and improve quality
3TokeniseConvert text into token IDs
4Build examplesCreate prefixes and next-token targets
5Initialise transformerStart from random weights
6Forward passProduce logits for every vocabulary token
7LossUse cross-entropy on the correct next token
8BackpropagationCompute gradients for every parameter
9Optimiser updateAdjust weights using Adam or a related optimiser
10RepeatProcess enormous numbers of tokens

Interactive Demo

Pretraining pipeline lab

End-to-end pipeline

Data mixture

Books18B tokens

quality score after filtering

Web42B tokens

quality score after filtering

Code24B tokens

quality score after filtering

Docs16B tokens

quality score after filtering

Input prefixTarget next token
Jessieordered
Jessie ordereda
Jessie ordered aburger
Jessie ordered a burgeryesterday
Selected stage
Run the transformer

Embeddings, causal attention, feed-forward layers, and output logits.

One tiny update
loss before = 2.271
loss after = 2.135
delta = -0.136

One step changes the model slightly. Pretraining repeats this loop at enormous scale.

Toy tokens processed so far: 262,144. In real frontier training, this becomes trillions of tokens across many machines.

Important boundary

Pretraining creates a general text model. It does not automatically create a helpful assistant. Instruction following comes later.

Click each stage of the pipeline. The key idea is that pretraining is the same next-token objective repeated at industrial scale.

Mechanics

Data Collection

The first requirement is text. Modern language models train on mixtures of books, websites, encyclopedias, academic papers, code repositories, technical documentation, public forums, and multilingual text.

No manual question-answer labels are required. Ordinary text provides its own supervision because every next token is a target.

Data Cleaning

Raw internet text is messy. Pretraining data is filtered to reduce duplicated pages, spam, advertisements, boilerplate, corrupted documents, extremely repetitive text, and other low-quality material.

Dataset quality can matter almost as much as dataset size. A huge pile of duplicated or low-quality text teaches the model the wrong patterns.

Tokenisation And Examples

A sentence such as Jessie ordered a burger. becomes token IDs:

[1842,  9123,  71,  5302,  13][1842,\;9123,\;71,\;5302,\;13]

From a stream of token IDs, training examples are created by shifting the sequence:

input=x1,,xttarget=xt+1\text{input}=x_1,\ldots,x_t\qquad \text{target}=x_{t+1}

One document becomes many supervised next-token prediction problems.

One Optimisation Step

A single training step looks like this:

token IDs
embeddings
transformer
logits
softmax
cross-entropy loss
backpropagation
optimizer update
updated weights

If the model predicts probability 0.620.62 for the correct token, the loss is:

L=log(0.62)L=-\log(0.62)

Backpropagation computes LW\frac{\partial L}{\partial W} for every parameter. The optimizer updates weights:

WWηLW\leftarrow W-\eta\nabla L

The model becomes slightly better. Then the process repeats.

Tokens Instead Of Epochs

In many ML courses, training is described in epochs: one pass through the dataset. LLM training often reports progress using tokens processed, optimization steps, and compute used instead.

The datasets are enormous, mixed, filtered, and sampled in ways that make a simple epoch count less informative.

Distributed Training

Frontier models cannot be trained on one GPU. Training is distributed across many machines using several forms of parallelism:

Data parallelismEach GPU has a model copy and processes different mini-batches; gradients are averaged.
Model parallelismThe model itself is split across multiple GPUs.
Pipeline parallelismDifferent GPUs process different stages of forward and backward passes like an assembly line.

Distributed training changes how the computation is executed. It does not change the underlying objective: predict the next token and reduce cross-entropy loss.

What The Model Learns

Nobody labels examples as grammar, algebra, Python, or style. These abilities emerge because they help the model predict text. Over many updates, the model learns useful internal representations of language and knowledge.

What Pretraining Does Not Do

A pretrained model is not automatically a helpful assistant. It has learned to continue text. If prompted with a question, a raw pretrained model may continue in the style of internet text rather than provide a careful answer.

Instruction following and preference alignment come after pretraining.

Implementation

A miniature pretraining loop uses the same ingredients as a large one, just at toy scale.

import torch
from torch import nn

model = TinyLanguageModel(...)
optimizer = torch.optim.AdamW(model.parameters(), lr=3e-4)
criterion = nn.CrossEntropyLoss()

for step, batch in enumerate(dataloader):
    # batch shape: (batch_size, sequence_length)
    inputs = batch[:, :-1]
    targets = batch[:, 1:]

    logits = model(inputs)

    loss = criterion(
        logits.reshape(-1, vocab_size),
        targets.reshape(-1),
    )

    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

    if step % 100 == 0:
        print(step, loss.item())

The real version adds distributed training, checkpointing, data mixture scheduling, learning-rate schedules, monitoring, and fault recovery. But the core loop is the same.

Interview Discussion

What is pretraining?

Pretraining is training a model on a broad corpus, usually with next-token prediction, so it learns general language patterns before specialization.

Why does pretraining not require manually labelled data?

Ordinary text supplies labels automatically: each next token is the target for the previous context.

Describe one optimization step.

Token IDs become embeddings, the transformer produces logits, cross-entropy computes loss, backpropagation computes gradients, and the optimizer updates weights.

Why report tokens processed instead of epochs?

LLM datasets are enormous, mixed, filtered, and sampled, so token count and compute are often more informative than full passes through a fixed dataset.

What does distributed training do?

It spreads computation across many GPUs using data, model, and pipeline parallelism. It does not change the learning objective.

Why is a pretrained model not automatically ChatGPT?

Pretraining teaches text continuation. Instruction following and helpful assistant behavior require later fine-tuning and preference optimization.

Active Recall

1. Draw the complete pretraining pipeline from memory.

2. Why is next-token prediction considered self-supervised learning?

3. What happens during one optimization step?

4. Name the main forms of distributed training.

5. Why can dataset quality matter as much as dataset size?

6. Why is a pretrained language model not automatically an instruction-following assistant?

Common Mistakes

  • Thinking pretraining requires manually labelled question-answer data.
  • Confusing the dataset with the tokenizer vocabulary.
  • Believing one forward pass is training.
  • Assuming pretraining produces a helpful assistant by itself.
  • Thinking distributed training changes the learning objective.

Connection To Fine-tuning

Pretraining creates a powerful foundation model. The next lesson explains how fine-tuning adapts that model to tasks, domains, and instruction-following behavior.