◆ AI All-in-One

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
↗ Plan a path here

Read first

GPT and Decoder-Only Models

This leads to

Knowledge Distillation and Small ModelsFine-TuningScaling Laws
The full path from zero — 32 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. Python for AI
  6. How Machines Learn
  7. Partial Derivatives and Gradients
  8. Matrices and Matrix Multiplication
  9. The Chain Rule
  10. Dot Product, Norms and Similarity
  11. Tokenization
  12. Supervised, Unsupervised and Reinforcement Learning
  13. Gradient Descent
  14. Language Modeling and Next-Token Prediction
  15. Supervised Learning
  16. Linear Regression
  17. The Perceptron
  18. Logistic Regression
  19. Neural Networks
  20. Recurrent Neural Networks
  21. Backpropagation
  22. Activation Functions
  23. Vanishing and Exploding Gradients
  24. Normalization Layers: BatchNorm and LayerNorm
  25. LSTMs and GRUs
  26. Residual Connections
  27. Sequence-to-Sequence Models
  28. Attention
  29. Self-Attention and Multi-Head Attention
  30. Positional Encodings
  31. The Transformer
  32. GPT and Decoder-Only Models
  33. 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 3.1×10233.1 \times 10^{23} 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:

  1. What's in the library (data). Spam, duplicates and garbled text teach bad habits. Careful selection matters as much as sheer size.
  2. How big the student's brain is (parameters). A bigger network can absorb more patterns.
  3. 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.

From the raw web to training tokens: a typical pretraining data pipeline Raw web crawl Common Crawl: billions of pages (HTML) Extract text strip menus, ads and markup Identify language a classifier labels each document Filter for quality rules + learned quality classifiers Remove duplicates exact and near-duplicates (MinHash) Safety and privacy filters toxic text, emails, phone numbers Mix and tokenize add code, books, papers, maths Example: FineWeb (2024) turned 96 Common Crawl snapshots into about 15 trillion English tokens. Each stage throws data away. Most of the raw crawl never reaches training.
Fig. 1 A typical pretraining data pipeline. Each stage discards data; what remains is mixed with curated sources and tokenized. The open FineWeb dataset is one carefully documented example.
  • 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

C≈6 N DC \approx 6\,N\,D

where CC is the total number of floating-point operations (FLOPs: additions and multiplications), NN the number of parameters and DD 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. N=175×109N = 175 \times 10^9, D=300×109D = 300 \times 10^9:

C≈6×1.75×1011×3×1011=3.15×1023 FLOPsC \approx 6 \times 1.75 \times 10^{11} \times 3 \times 10^{11} = 3.15 \times 10^{23} \text{ FLOPs}

The GPT-3 paper reports 3.14×10233.14 \times 10^{23}. To turn FLOPs into time, divide by what the hardware actually sustains. An NVIDIA H100 GPU peaks at roughly 101510^{15} 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, 6×8×109×15×1012=7.2×10236 \times 8 \times 10^9 \times 15 \times 10^{12} = 7.2 \times 10^{23} 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.

A real training run: the tiny GPT from “Build a GPT from Scratch” (0.8M parameters, laptop CPU) 1 2 3 4 0 100 200 300 400 500 600 700 training step cross-entropy loss (nats per character) ln 94 = 4.54 (random guessing) train 1.25 validation 1.45 fast early drop: learns which characters are common steady gains: spelling, common words, layout slow tail: train and validation begin to separate
Fig. 2 The loss curve of a real (tiny) training run: the character-level GPT from the Build a GPT chapter. The loss starts at the value for random guessing, ln 94 ≈ 4.54, drops fast, then improves slowly. Large runs have the same shape over trillions of tokens.

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

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

  1. Use C≈6NDC \approx 6ND 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?
  2. Add a rule to quality_ok that rejects documents where more than 30% of the lines are identical. Test it on a document made of the same line repeated.
  3. 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: 6×7×1010×1.5×1013=6.3×10246 \times 7 \times 10^{10} \times 1.5 \times 10^{13} = 6.3 \times 10^{24} FLOPs. Divide by 16,000×4×101416{,}000 \times 4 \times 10^{14} FLOP/s and then by 86,400 seconds per day: about 11 days.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. Using C ≈ 6ND, roughly how much compute does a 175-billion-parameter model trained on 300 billion tokens need?

  2. Why do pretraining pipelines spend so much effort on deduplication?

  3. Mid-way through a large run the loss suddenly jumps and does not recover. What is the usual fix?

  4. A startup wants an assistant for legal documents. What does the chapter advise?

  5. A run's estimated paper FLOPs say 21 days, but it actually takes much longer on the same GPUs. What explains the gap?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Video

Deep Dive into LLMs like ChatGPT

Andrej Karpathy · 2025 · Beginner · Free

A 3.5-hour walk through the full stack of how chat models are built: pretraining, tokenization, post-training, RL and reasoning.

Article

Epoch AI

Epoch AI · Intermediate · Free

Data and research on trends in AI compute, data, models and hardware.

Tool

nanoGPT

Andrej Karpathy · Advanced · Free

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