Skip to Content
Chapter 7

Pre-training: Compressing the internet

Tomas Reimers 16 minute read

Everything so far has been about the function: the trained network that maps a context to a next-token prediction. This part of the book is about how the function gets made — and it starts with the strangest industrial process of our era: take a rough copy of the internet, and spend months of time on tens of thousands of GPUs compressing it into weights.

The framing is not a metaphor. Chapter 2 noted that cross-entropy loss counts the bits needed to encode text under the model’s beliefs (in base-2 logs the unit is bits; under the natural logs used in practice, nats, the same idea, a constant factor apart), so a model that predicts text well literally compresses it well. Pre-training is lossy compression of humanity’s written output into a few terabytes of parameters, and the “loss” in this lossy compression is exactly the stuff the model gets wrong.

Why “pre”-training? The name is a fossil.

Pre-training is “pre” relative to the training that was supposed to matter. In the older recipe, you first trained a network on some big generic objective to give it a foundation, then did the real, task-specific training on top — the generic phase was mere preparation, so it got the prefix. The LLM era kept the name and inverted the emphasis: the “preparation” grew into 99% of the compute and essentially all of the capability, while the “real” training shrank into the comparatively tiny shaping pass of Chapter 8, leaving the prefix behind as a fossil.

Chapter 4 left us with a fully-planned run: an 8B model, 15 trillion tokens, your 1,000 GPUs, about a month. This chapter runs it:

  1. Build the dataset — which practitioners will tell you is most of the actual work, and where frontier labs guard their edge.
  2. Run the loop — still Chapter 1’s ten lines, executed a few million times.
  3. Keep it alive — a single stateful job, weeks long, on hardware that fails constantly.
  4. Ship the artifact — a base model, which knows nearly everything and is almost unusable.

The data: most of the work

The romantic image of pre-training is the GPU cluster. The real product is the dataset. Your plan needs 15T tokens of good text, and good text does not exist in a downloadable file; it has to be refined out of ore. The raw material is web crawl (Common Crawl  alone is petabytes of scraped HTML), plus code, books, papers, and licensed corpora. Between raw crawl and training corpus sits a brutal funnel:

  • Extraction: strip the HTML boilerplate (nav bars, cookie banners, consent popups, SEO sludge) to get at actual prose. Harder than it sounds; extraction quality measurably moves final model quality.
  • Filtering: heuristics (language ID, length, symbol ratios) followed by model-based quality classifiers — small models trained to score “is this page educational/informative?”, used to grade every document. Each generation of models curates data for the next.
  • Deduplication: the web is mostly copies, and repeated data wastes compute and, worse, encourages memorization over generalization (Chapter 1’s overfitting, at internet scale).
  • Decontamination: scrub the test sets of public benchmarks out of the training data. Imperfect, consequential, and the reason Chapter 9 (evaluation) exists.
raw crawl
petabytes of HTML
extracted text
boilerplate stripped
filtered
language + quality classifiers
deduplicated
the web is mostly copies
final mix
~15T tokens, composed by hand
The pre-training data funnel, proportions after FineWeb: most of the crawl doesn't survive. The curation decisions in this funnel are a lab's most guarded asset.

The open FineWeb  project documents this funnel end-to-end (96 Common Crawl snapshots distilled down to exactly the 15T curated tokens your run needs) and is the best public look at decisions labs usually keep private. (For the historical baseline, The Pile  was the canonical open corpus of the GPT-3 era.)

Every stage of that funnel also makes a legal and ethical call. Common Crawl honors robots.txt, but nearly everything it gathers was written by people who never agreed to train a model, and books and news archives have drawn a wave of copyright suits against AI labs. Labs answer with licensing deals, opt-out mechanisms, and filters that strip personal data. Early rulings have split the question: training on lawfully acquired text has fared better than training on pirated copies, and the law is still settling. If you build a dataset, its provenance is part of the product.

What survives the funnel then gets composed into a data mix: what fraction code, what fraction multilingual, how much math. These ratios are product decisions as much as research ones:

50%
25%
17%
8%
general knowledge — 50%
math & reasoning — 25%
code — 17%
multilingual — 8%
The data mix is a product decision: Llama 3's published pre-training ratios. Every 2026 model is good at code because its makers chose code to be a sixth of everything it ever read — a choice that also, for reasons still debated, appears to improve reasoning in general.

Unlike Chapter 1’s MNIST digits, looped over dozens of times, your run will see this data roughly once — one epoch.

Why only one epoch?

With MNIST, Chapter 1 happily looped over 60,000 images dozens of times. At internet scale the economics invert: when data is abundant relative to compute, a fresh token teaches more than a repeated one, so you spend your FLOPs on text the model hasn’t seen. Repetition also has a measured cost curve: a few epochs over high-quality data are nearly as good as fresh data, but returns decay fast, and heavy repetition actively hurts — the model starts memorizing documents instead of generalizing from them (overfitting, again). In practice labs repeat only the best slices (textbook-grade prose, verified code) a handful of times and show everything else once. This is also why Chapter 4’s data wall (the point where fresh usable text runs out) bites: “just do more epochs” is not an escape hatch.

Here’s Chapter 1’s promised surprise: dropout has quietly vanished from LLM configs. The defining anti-overfitting technique of the deep learning era is set to zero in essentially every modern pre-training run — when the model sees each example once, memorization barely gets a chance to start, and paying a regularization tax to prevent it is pure waste. A concept that was in every architecture diagram for a decade, retired by a change in the data economics.

The objective: unchanged

Amid all this scale, the training loop is identical to Chapter 1’s ten lines: predict the next token everywhere in a batch, take the cross-entropy loss, backprop, step. There are no labels — the internet is its own supervision. That’s the trick that unlocked everything: labeled data is scarce and expensive, but text that continues is free and unlimited.

Put your run’s numbers on the loop. Your cluster does 1,000 GPUs × ~101510^{15} peak FLOPs each × 40% MFU (Chapter 4) ≈ 4×10174 \times 10^{17} useful FLOPs per second; at Chapter 4’s ~6 FLOPs per parameter per token (6×8B=4.8×10106 \times 8\text{B} = 4.8 \times 10^{10} per token), that’s about 8 million tokens per second — 720 billion tokens a day, 15T in roughly three weeks. Each step processes one global batch (a few million tokens spread across all thousand GPUs), so the whole run is Chapter 1’s loop executed about 4 million times. That’s the entire algorithm. Everything else in this chapter is logistics.

The ritual before the run

On paper, training is “run the loop until the loss is low.” In practice, training is staring at the loss curve — knowing what to check, in what order, when it isn’t doing what you want. The ritual predates scale: it’s the same one you’d run on Chapter 1’s MNIST net, and cheap models are where you learn it — but skip it at your scale and the tuition is GPU-months.

First number: the loss at initialization. Before any training, a model with random weights should spread its probability uniformly. Cross-entropy is the negative log of the probability given to the correct answer (Chapter 1), and a uniform guess over KK classes gives the correct one 1/K1/K — so the initial loss should be almost exactly −ln⁡(1/K)=ln⁡K-\ln(1/K) = \ln K: for a 10-digit MNIST classifier, ln⁡10≈2.3\ln 10 \approx 2.3; for your tokenizer’s 128,256-entry vocabulary (Llama 3’s, which your run borrowed), ln⁡(128,256)≈11.8\ln(128{,}256) \approx 11.8. Check it. If it’s far higher, your initialization is broken; if it’s far lower, or if the loss collapses implausibly fast in the first few steps, you have a bug, probably data leaking answers into the input. This one free check catches most setup errors before the run spends its first GPU-minute.

First milestone: overfit one batch. Take a tiny batch and train on just it until the loss is ~0. With millions of weights and a handful of examples, the network has vastly more capacity than the task needs, so gradient descent can simply memorize the right answers — brute-forcing the loss to zero without learning anything general. Normally memorization is the failure mode you fight (Chapter 1’s overfitting); here it’s a diagnostic. A network that can’t memorize one batch has a plumbing problem (wrong shapes, a broken loss, gradients not flowing), and no amount of data or patience will fix plumbing.

Then: watch the shape. With the plumbing verified, start real training and read the curve. There are only three shapes (diverging, crawling, or the healthy steady descent you want), and the learning rate (how big a step each weight update takes: Chapter 1’s η\eta) usually picks between them:

training stepslossloss at init ≈ ln(10) ≈ 2.3learning rate too high: divergestoo low: crawlshealthy: fast drop, long tail
The three loss curves every practitioner learns to read at a glance. Almost always, the knob that separates them is the learning rate.

When the curve diverges, lower the learning rate; when it crawls, raise it. The standard move is a sweep over powers of ten — nobody, at any level of seniority, guesses it correctly on the first try. (At frontier scale even the sweep is priced in scaling-law fashion: fit the best learning rate on small models, extrapolate the trend.)

What matters, in order. For a fixed dataset, the learning rate dwarfs everything else; after that, training longer and making the model bigger; after that, the architecture tweaks people love to argue about. And looming over all of it: more and better data beats all of the above — the hierarchy that was Chapter 4’s thesis, and the reason this chapter opened with the funnel rather than the cluster. Karpathy’s A Recipe for Training Neural Networks  is the canonical write-up of this discipline, and it transfers almost unchanged from MNIST to frontier models.

Keeping a months-long run alive

What separates pre-training from every other computation you’ve operated is that it’s a single, stateful, weeks-long job on hardware that fails constantly. During Llama 3’s training, Meta reported  unexpected interruptions roughly every three hours across its 16K-GPU cluster — mostly GPU and memory failures. Scale that to your 1,000 GPUs and you should still budget for a failure every day or two, each one a potential run-killer if you can’t recover. Here is your month, compressed:

24812loss (log)ln(128,256) ≈ 11.8spike → clip, skip, rewind2.03 — as predictedlrtraining progress — 0 to 15T tokens (~1 month)
step zero: loss = ln(128,256) ≈ 11.8 — every token equally likely. Warmup ramps the learning rate so the violent early gradients don’t wreck the initialization
A month in the life of the run Chapter 4 planned: the 8B model, 15T tokens, 1,000 GPUs. Top: loss (log scale) — from ln(vocab) ≈ 11.8 at initialization, down the power-law glide, over one spike, to the final decay dive. Bottom: the WSD learning-rate schedule driving it. Mechanics illustrative; endpoints real.

Three load-bearing practices behind that picture:

  • The learning-rate schedule. Runs begin with a warmup, ramping the learning rate up from zero. At step zero the loss sits at its uniform-guess baseline of ln⁡(128,256)≈11.8\ln(128{,}256) \approx 11.8, the surface is steep in nearly every direction, and the first gradients are huge; full-size steps would wreck the initialization. Runs end with a decay (shrinking steps as you approach the minimum: Chapter 1’s overshooting lesson, applied on schedule). Between the classical cosine shape (one smooth half-cosine glide from peak to near zero) and the newer WSD (warmup–stable–decay), the difference is operational. A cosine glide is drawn over the whole planned run, so every mid-run checkpoint sits mid-glide, usable only for the endpoint you committed to at the start. WSD holds the rate flat instead — so any checkpoint plus a short decay is a finished model, branchable at any token count.
training progress (tokens)learning ratecosineWSD← warmup
The two learning-rate schedules you'll meet in every technical report: warmup + cosine decay, and warmup–stable–decay (WSD), whose long flat stretch lets labs branch models off mid-run checkpoints.
  • Loss spikes. Every practitioner’s scar tissue: the loss occasionally jumps violently, from a bad data batch or numerical instability. Defenses, in escalating order: gradient clipping (cap the gradient norm every step, as routine hygiene), skipping the offending batch, and, worst case, rewinding to a checkpoint and skipping forward past the suspect data (replaying identically would just hit the same batch again). A curious finding from PaLM ’s team, who rewound ~100 steps and skipped a few hundred batches per spike: replaying the same data from a different checkpoint usually produced no spike — a spike needs the conjunction of a bad batch and a vulnerable optimizer state (the running averages Adam carries), not the batch alone. Nobody relies on that; you skip anyway.
  • Checkpoints and precision. The run’s state is saved frequently enough that a failure costs hours, not weeks. Weights and activations are kept in 16-bit floats (bf16) — already half the size of the 32-bit floats classical training used — with the newest hardware pushing parts of the computation to 8-bit (fp8), halving memory and doubling throughput again, at the cost of numerical-stability engineering. (Why memory is the thing you’re trying to save is Chapter 10.)

Anatomy of a checkpoint.

A checkpoint holds far more than the weights. Mixed-precision training with AdamW keeps, per parameter: the bf16 working weights (2 bytes), a full-precision master copy (4 bytes), and Adam’s two moment buffers (4 + 4 bytes) — roughly 14 bytes per parameter. For your 8B model that’s ~112 GB per checkpoint; for a 405B model, ~5.7 TB. Writing that to storage every few hours, from a thousand machines, without pausing training, is its own systems problem — and it’s why “optimizer state” keeps appearing in Chapter 10’s memory arithmetic: during training, the optimizer’s bookkeeping outweighs the model itself.

The optimizer wars, finally interesting again

For a decade, the optimizer slot in every config file said AdamW (Chapter 1) and nobody debated it. The reason it held: at scale, an optimizer must be boring — a 2% efficiency win is worthless if it adds instability risk to a $500M run. AdamW’s cost is memory (those two moment buffers in the checkpoint arithmetic above), a fact that shapes the parallelism strategies in Chapter 10.

The “W”: what AdamW actually fixed.

Chapter 1 introduced weight decay — shrink every weight slightly toward zero each step, so large weights must be earned — and promised the fix’s details here. The subtle bug: the traditional implementation adds the shrinking pressure into the gradient. Under plain SGD the two formulations are mathematically identical. Under Adam they are not — Adam divides every gradient by its running magnitude, and the decay term gets divided along with it. The result: weights with large, active gradients barely decay, while quiet weights decay hard; the regularization strength you set silently varies from parameter to parameter.

AdamW decouples the two (the paper is literally titled “Decoupled Weight Decay Regularization”): the gradient goes through Adam’s adaptive machinery, and the decay is applied to the weights directly, outside it. Same ingredients, consistent regularization — and the default optimizer of every LLM config since.

Then, in 2024–25, the slot actually changed for the first time. Muon  came out of the nanoGPT speedrun community rather than a lab — an open competition to train a small GPT-2 as fast as possible, which became a proving ground for training tricks. Muon’s idea, stripped of detail: for the matrix-shaped parameters, take the gradient smoothed by a running average of recent steps (Chapter 1’s momentum) and orthogonalize it (rescale the update so no single direction of the matrix dominates and every direction moves by a comparable amount) before stepping, yielding meaningfully better loss per token. Moonshot AI then demonstrated it scales  and trained Kimi K2 (a trillion-parameter frontier model) with a Muon variant. Hobbyist speedrun to frontier run in about a year: proof that individual researchers outside the big labs can still move the field’s foundations. (The optimizer zoo beyond this — Shampoo, from whose lineage Muon descends, plus Sophia and Lion — you can safely file under “a sentence each.”)

Mid-training: the director’s cut

Between the big run and the post-training of Chapter 8 sits a phase with a mumbled name — mid-training: continued pre-training on curated data to reshape a finished base model.

  • Context extension: the main run trains at a short context (say 8K) for two good reasons: attention’s cost grows with the square of sequence length, and genuinely long documents are rare in the corpus anyway, so pre-training at 128K would spend a fortune teaching mostly-padding. But a model trained at 8K breaks past 8K. Under Chapter 5’s RoPE, offsets beyond anything the model saw spin the query and key rotations into never-visited angles, so attention scores go out of distribution. The fix is a two-step retrofit. First, rescale the RoPE frequencies — slow every pair’s rotation down so that the new 128K range of positions sweeps through the same angles the model knew from 8K; familiar geometry, now sampled more densely (published rescaling recipes tune this carefully; YaRN is the standard one). Second, train briefly (tens of billions of tokens, not trillions) on a mix upweighted with genuinely long documents such as books and full repositories so the model learns to actually use the denser positions. Total cost: well under 1% of the main run, which is why long context ships as a point release. Whether the result genuinely uses its window is a different question — Chapter 9’s needle-in-a-haystack evals exist because the answer is often “partially.”
  • Domain infusion: continued training on a domain corpus (medical, legal, your company’s stack) — same loop, targeted data.
  • Annealing on quality: end training with a pass over the highest-quality data (textbooks, verified solutions) while the learning rate decays — the metallurgy borrow is apt: the decaying rate is the slow cool. What the model sees last counts extra because nothing later overwrites it, and it’s absorbed during the small, careful final steps. (This is why the WSD decay phase and the best data get scheduled together.)

What you get: the base model

The artifact at the end of your month is a base model, and it is not an assistant. It’s a document completer — ask it “What’s the capital of France?” and it may answer, or continue with nine more geography questions, because both are plausible internet documents. All the knowledge is in there; what’s missing is any notion that it should be helpful, or that it’s in a conversation at all.

The base model is the compressed internet. Turning it into something you’d want to talk to costs a percent or two of the compute you just spent and is the subject of the next chapter. Almost all the capability comes from here; almost all the behavior comes from what’s next.

Further reading

Last updated on