Level 3 In-Depth AI · Transformers and Language Models
Pretraining Large Language Models
Pretraining is the long, expensive first stage of building an LLM, in which a Transformer learns to predict the next token on trillions of tokens of text. This chapter covers where the data comes from, how much compute it takes, how training runs at scale, and what you get at the end, a base model.
- Level
- ●●●●● Intermediate
- Reading
- 13 min
- To learn it well
- 1 hour to read
- Builds on
- 32 concepts →
- Quiz
- 5 questions ↓
Read first
GPT and Decoder-Only ModelsThe full path from zero — 32 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- Python for AI
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- The Chain Rule
- Dot Product, Norms and Similarity
- Tokenization
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Language Modeling and Next-Token Prediction
- Supervised Learning
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Recurrent Neural Networks
- Backpropagation
- Activation Functions
- Vanishing and Exploding Gradients
- Normalization Layers: BatchNorm and LayerNorm
- LSTMs and GRUs
- Residual Connections
- Sequence-to-Sequence Models
- Attention
- Self-Attention and Multi-Head Attention
- Positional Encodings
- The Transformer
- GPT and Decoder-Only Models
- Pretraining Large Language Models
Read them roughly in this order. See it on the concept map →
Why it matters
Every chatbot begins as a base model produced by pretraining: a decoder-only Transformer trained to predict the next token on an enormous amount of text. Pretraining is where nearly all of a model's knowledge and skill comes from. The later stages, Instruction Tuning and Chat Models and RLHF and Preference Optimization, mostly shape how the model uses what it already learned, and they cost a small fraction as much.
Pretraining is also where most of the money goes. Meta reported using about 30 million GPU-hours on H100 GPUs to pretrain Llama 3.1 405B, on clusters of up to 16,000 GPUs. GPT-3's pretraining in 2020 took about floating-point operations; frontier runs in 2024 used roughly a hundred times more. Decisions made at this stage (what data, how much, how big a model, how long) are the most consequential and expensive in the whole process.
Even if you never pretrain a large model yourself, understanding it explains a lot: why models know what they know, why they have a knowledge cutoff, where biases and memorised text come from, why "open weights" doesn't mean "open data", and why compute became the central resource of AI (AI Hardware: GPUs, TPUs and Accelerators, The Energy Cost of AI).
The intuition
Think of pretraining as giving a student an absurd reading assignment: a large share of everything ever published on the open web, plus books, encyclopaedias, scientific papers and code, and a single exercise repeated trillions of times: "cover the next word; guess it; check; adjust."
Three things determine how well that goes:
- What's in the library (data). Spam, duplicates and garbled text teach bad habits. Careful selection matters as much as sheer size.
- How big the student's brain is (parameters). A bigger network can absorb more patterns.
- How long they study (tokens processed, and hence compute). Reading each page costs effort, and effort is measured in floating-point operations.
At the end the student is extraordinarily well read but has never been taught manners or how to hold a conversation. That's a base model: it continues text in the style of whatever document you start, it does not answer you.
Key idea Pretraining = next-token prediction on trillions of tokens of carefully filtered text. It uses most of the compute, provides most of the knowledge, and produces a base model that continues documents rather than following instructions.
How it works
1. Data: from the web to tokens
The bulk of pretraining text comes from the web, mostly via Common Crawl, a non-profit that has crawled the public web since 2008 and publishes snapshots of billions of pages, free for anyone. Raw crawl data is mostly unusable: navigation menus, cookie banners, spam, machine-generated pages, endless duplicates. Turning it into training data is a pipeline of filters.
- Text extraction pulls the main text out of each page's HTML.
- Language identification labels each document's language with a fast classifier, so you can keep the languages you want.
- Quality filtering removes junk. Heuristic rules catch the obvious cases: too short, too many symbols, too repetitive, no ordinary function words like "the" and "and". Learned classifiers then score how much a page resembles reference text such as Wikipedia or educational material. For example, Hugging Face's FineWeb-Edu kept pages that a classifier, trained on labels from an LLM, judged educational.
- Deduplication removes exact copies and near-copies, often with MinHash, a technique that finds documents sharing most of their word sequences without comparing every pair. Duplicates waste compute and make models memorise and regurgitate text.
- Safety and privacy filtering removes or masks toxic content and personal data such as email addresses.
The cleaned web text is combined with other sources into a data mixture: code (from public repositories), books, scientific papers, maths, Wikipedia and, increasingly, synthetic data generated by other models (Synthetic Data). The proportions are tuned by training small models on candidate mixtures and comparing them. Many runs end with a short annealing phase on the highest-quality data while the learning rate decays.
Finally everything is tokenized, shuffled and packed into fixed-length sequences, say 8,192 tokens, with special end-of-text tokens between documents.
The scale is hard to picture. FineWeb, an open English dataset released in 2024, distilled 96 Common Crawl snapshots into about 15 trillion tokens. Llama 3 was pretrained on about 15 trillion tokens. At roughly 0.75 words per token, that is around 11 trillion words. Reading 8 hours a day at 300 words a minute, a person would need about 200,000 years to get through it.
2. Compute: the 6ND rule
How much computation does pretraining take? A good rule of thumb, from OpenAI's 2020 scaling-laws paper (Scaling Laws), is
where is the total number of floating-point operations (FLOPs: additions and multiplications), the number of parameters and the number of training tokens. Why 6? For each token, every parameter takes part in about one multiplication and one addition in the forward pass (2 FLOPs), and the backward pass (Backpropagation) costs about twice the forward pass (4 FLOPs).
Worked example: GPT-3. , :
The GPT-3 paper reports . To turn FLOPs into time, divide by what the hardware actually sustains. An NVIDIA H100 GPU peaks at roughly FLOP/s for the 16-bit matrix maths used in training, but real runs achieve only 30 to 50% of peak, a ratio called model FLOPs utilisation (MFU), because time is lost to communication, memory movement and everything else. At 400 TFLOP/s per GPU, GPT-3's compute would take about 9 days on 1,000 GPUs.
For Llama 3 8B, FLOPs, more than GPT-3, for a model 22 times smaller, because it read 50 times more tokens. Meta reported 1.3 million H100 GPU-hours for it.
3. Training at scale
The training loop is the same one you'd write for a small model: sample a batch, compute the cross-entropy loss, backpropagate, update with an optimizer. What changes is everything around it.
- Optimizer and schedule. Almost everyone uses AdamW with weight decay, gradient clipping, a short learning-rate warm-up and then a slow decay, often a cosine curve (Learning Rate Schedules).
- Huge batches. Batches are measured in tokens: GPT-3 used 3.2 million tokens per step, and Llama 3 405B ramped up to 16 million. Large batches keep thousands of GPUs busy.
- Mixed precision. Matrix maths runs in 16-bit bfloat16, with sensitive quantities kept in 32-bit (Mixed Precision Training).
- Parallelism. No single GPU can hold a large model and its optimizer state, let alone do the work alone. Runs combine data parallelism (each group of GPUs processes different batches, with model and optimizer state sharded across them), tensor parallelism (each matrix split across GPUs) and pipeline parallelism (different layers on different GPUs). See Distributed Training.
- Checkpoints and failures. At this scale hardware fails constantly. Meta reported hundreds of unexpected interruptions during a 54-day stretch of Llama 3 405B training, mostly GPU and memory faults. Runs save checkpoints (snapshots of all weights and optimizer state) regularly and resume automatically.
4. Watching the loss curve
The main health signal is the training loss: the average cross-entropy per token (Language Modeling and Next-Token Prediction). A healthy run looks like the curve below: a steep early drop as the model learns the basics, then a long, slowly flattening tail.
Things to watch for:
- A loss spike, a sudden jump in loss. Small spikes recover on their own. Big ones can derail training; the usual fix is to roll back to an earlier checkpoint and skip the batches that triggered it, or lower the learning rate.
- Divergence: loss shooting up or becoming
NaN. Usually a learning rate that is too high or a numerical overflow. - Validation loss rising while training loss falls means Overfitting and the Bias–Variance Tradeoff. With trillions of tokens seen mostly once, this rarely happens in pretraining, but it does on small datasets, as in our tiny example.
Teams also evaluate checkpoints on benchmark tasks along the way (Evaluating LLMs and Benchmarks), because loss alone doesn't say which skills are improving.
5. What you get: a base model
The result is a set of weights that assigns probabilities to the next token remarkably well. Prompted with the start of a news article, it writes a plausible article; with a function signature, the code; with a few examples of a task, more of the same (in-context learning). Prompted with a question, it may answer, or may add more questions, because that's also a likely continuation. It can reproduce biases in its data and occasionally regurgitate memorised passages. Its knowledge stops at the date its data was collected, the knowledge cutoff.
In code
Two small pieces of a real pipeline: exact deduplication and a few rule-based quality filters (in the spirit of the rules DeepMind published for its Gopher model), then the 6ND compute estimate.
import hashlib, re
docs = [
"The Moon orbits the Earth about once every 27 days, and its phases follow a 29.5 day cycle.",
"The Moon orbits the Earth about once every 27 days, and its phases follow a 29.5 day cycle.",
"BUY NOW!!! $$$ CLICK HERE $$$ BEST PRICE ON THE WEB $$$ AND FREE SHIPPING !!!",
"Home | About | Contact | Login | Sign up | Privacy",
"Photosynthesis turns light, water and carbon dioxide into sugar and oxygen in plants.",
"the the the the the the the the the the the the",
]
STOP = {"the", "be", "to", "of", "and", "that", "have", "with", "in", "is"}
def quality_ok(doc):
words = re.findall(r"[A-Za-z']+", doc)
if len(words) < 8: # too short to be useful prose
return False, "too short"
if sum(w.lower() in STOP for w in words) < 2: # real sentences use function words
return False, "no stop words"
if len(set(w.lower() for w in words)) / len(words) < 0.3:
return False, "repetitive" # the same word over and over
if sum(not c.isalnum() and not c.isspace() for c in doc) / len(doc) > 0.1:
return False, "too many symbols"
return True, "kept"
seen, kept = set(), []
for doc in docs:
h = hashlib.sha256(" ".join(doc.lower().split()).encode()).hexdigest()
if h in seen: # exact duplicate (after normalising)
print("duplicate |", doc[:40]); continue
seen.add(h)
ok, why = quality_ok(doc)
print(f"{why:16s} |", doc[:40])
if ok:
kept.append(doc)
print(len(kept), "of", len(docs), "documents kept")
# Compute budget: training FLOPs ≈ 6 × parameters × tokens
def train_flops(n_params, n_tokens):
return 6 * n_params * n_tokens
for name, N, D in [("GPT-3", 175e9, 300e9), ("Llama 3 8B", 8e9, 15e12)]:
C = train_flops(N, D)
days = C / (1000 * 400e12) / 86400 # 1,000 GPUs at 400 TFLOP/s each, sustained
print(f"{name}: {C:.2e} FLOPs, about {days:.0f} days on 1,000 GPUs")
# kept | The Moon orbits the Earth about once eve
# duplicate | The Moon orbits the Earth about once eve
# too many symbols | BUY NOW!!! $$$ CLICK HERE $$$ BEST PRICE
# too short | Home | About | Contact | Login | Sign up
# kept | Photosynthesis turns light, water and ca
# repetitive | the the the the the the the the the the
# 2 of 6 documents kept
# GPT-3: 3.15e+23 FLOPs, about 9 days on 1,000 GPUs
# Llama 3 8B: 7.20e+23 FLOPs, about 21 days on 1,000 GPUs
The 21-day estimate for Llama 3 8B corresponds to about 500,000 GPU-hours; Meta reported 1.3 million, which means their effective throughput was lower than the 400 TFLOP/s assumed here. That gap, between paper FLOPs and real throughput, is exactly what MFU measures. The training loop itself is in Build a GPT from Scratch, and Karpathy's nanoGPT scales the same code up to reproduce GPT-2.
Common pitfalls
- Benchmark contamination. If test questions leak into the training data, benchmark scores become meaningless. Serious pipelines search for and remove known benchmark text (Evaluating LLMs and Benchmarks).
- Over-filtering. Aggressive quality filters can remove dialects, minority languages and informal writing, making the model worse for the people who write that way (Bias and Fairness).
- Ignoring duplicates. Repeated documents get memorised and regurgitated, which raises copyright and privacy problems (Privacy, Data and Copyright).
- Comparing loss across tokenizers. A lower loss with a different vocabulary isn't necessarily a better model; compare bits per byte or downstream tasks.
- Underestimating engineering. Most failed runs fail on data bugs, numerical instability or infrastructure, not on model design. Test the whole pipeline on a small model first.
Watch out Pretraining a model from scratch is almost never the right move for an application. It costs from thousands of dollars (small models) to hundreds of millions (frontier models). Start from an existing open base model and fine-tune it, or use a hosted model through an API.
Where it leads
- Scaling Laws: how to split a fixed compute budget between model size and data, and how to predict the loss before you train.
- Instruction Tuning and Chat Models and RLHF and Preference Optimization: turning the base model into an assistant.
- Knowledge Distillation and Small Models: training small models on the outputs of large ones, an increasingly important part of pretraining small models.
- Distributed Training, Mixed Precision Training and GPUs and Why AI Needs Them: the engineering that makes large runs possible.
- Mixture of Experts: more parameters for the same compute per token.
A live question is data. Epoch AI has estimated that the stock of high-quality public human text, a few hundred trillion tokens, could be fully used by frontier training runs some time between 2026 and 2032. Repeating data for a few epochs, synthetic data and other modalities are the main responses.
A bit of history
Pretraining on unlabelled text to help downstream tasks goes back to word vectors (Word Embeddings, 2013) and to pretrained LSTM language models around 2015 to 2018. GPT-1 (2018) and BERT (2018) used about 1 to 3 billion words of books and Wikipedia. GPT-2 (2019) moved to filtered web text, 40 GB of it. GPT-3 (2020) mixed filtered Common Crawl with books, Wikipedia and WebText2 for 300 billion tokens. DeepMind's Gopher (2021) documented detailed quality rules, and its Chinchilla (2022) showed that models should be trained on far more tokens than had been usual. Meta's LLaMA (2023) trained on 1 to 1.4 trillion tokens of public data only, and open datasets such as RedPajama, Dolma and FineWeb followed. By 2024 leading models were pretrained on 15 trillion tokens or more, and the craft of curating data had become one of the most closely guarded parts of building a model.
Try it
- Use to estimate the compute for a 70-billion-parameter model trained on 15 trillion tokens. How many days would it take on 16,000 GPUs at 400 TFLOP/s each?
- Add a rule to
quality_okthat rejects documents where more than 30% of the lines are identical. Test it on a document made of the same line repeated.- Normalising before hashing catches "Hello World" versus "hello world". Write two near-duplicates the exact hash still misses, and explain why MinHash is needed.
Hint for 1: FLOPs. Divide by FLOP/s and then by 86,400 seconds per day: about 11 days.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Deep Dive into LLMs like ChatGPT
A 3.5-hour walk through the full stack of how chat models are built: pretraining, tokenization, post-training, RL and reasoning.
Stanford CS336: Language Modeling from Scratch
Build every part of an LLM yourself, from tokenizer to training, scaling and alignment.
The FineWeb Datasets: Decanting the Web for the Finest Text Data at Scale
A detailed, open account of turning Common Crawl into a 15-trillion-token pretraining dataset: extraction, filtering and deduplication.
Language Models are Few-Shot Learners
GPT-3: a 175B-parameter model that could do new tasks from a few examples in the prompt.
LLaMA: Open and Efficient Foundation Language Models
Meta's 7B to 65B models trained only on public data. Its recipe (pre-norm, RMSNorm, SwiGLU, RoPE) became the template for open models.
Epoch AI
Data and research on trends in AI compute, data, models and hardware.
nanoGPT
The simplest, fastest repository for training and fine-tuning medium-sized GPTs.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/llm/pretraining.md