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
| 1 | Collect raw text | Gather books, websites, code, papers, documentation, and multilingual data |
| 2 | Clean the data | Deduplicate, filter spam, remove malformed documents, and improve quality |
| 3 | Tokenise | Convert text into token IDs |
| 4 | Build examples | Create prefixes and next-token targets |
| 5 | Initialise transformer | Start from random weights |
| 6 | Forward pass | Produce logits for every vocabulary token |
| 7 | Loss | Use cross-entropy on the correct next token |
| 8 | Backpropagation | Compute gradients for every parameter |
| 9 | Optimiser update | Adjust weights using Adam or a related optimiser |
| 10 | Repeat | Process enormous numbers of tokens |
Interactive Demo
End-to-end pipeline
Data mixture
quality score after filtering
quality score after filtering
quality score after filtering
quality score after filtering
| Input prefix | Target next token |
|---|---|
| Jessie | ordered |
| Jessie ordered | a |
| Jessie ordered a | burger |
| Jessie ordered a burger | yesterday |
Embeddings, causal attention, feed-forward layers, and output logits.
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:
From a stream of token IDs, training examples are created by shifting the sequence:
One document becomes many supervised next-token prediction problems.
One Optimisation Step
A single training step looks like this:
embeddings
transformer
logits
softmax
cross-entropy loss
backpropagation
optimizer update
updated weights
If the model predicts probability for the correct token, the loss is:
Backpropagation computes for every parameter. The optimizer updates weights:
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 parallelism | Each GPU has a model copy and processes different mini-batches; gradients are averaged. |
| Model parallelism | The model itself is split across multiple GPUs. |
| Pipeline parallelism | Different 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.