llm.guideChapter 8Pretraining at Scale

Pretraining at Scale

Data pipelines, scaling laws, the 6ND cost math and distributed training.

Part 2: Foundations. 9 sections, about 15 minutes.

The dataCrawlbillions of pagesExtracttext from HTMLFilterlanguage, qualityDeduplicateexact and nearTokenize≈15T tokensEach step throws text away; most of the engineering is here.The run, for Llama 3 8B8 × 10⁹parameters15 × 10¹²tokens× 6FLOP perparameter pertoken≈ 7.2 × 10²³ FLOPthe compute budget, from 6ND (section 8.5)≈ 1.3 million H100 GPU-hoursas reported in Meta’s model card
Crawl → Extractbillions of pages, text from HTMLFilter → Deduplicatelanguage, quality, copiesTokenize≈ 15 trillion tokens for Llama 3× 8 billion parameters × 6≈ 7.2 × 10²³ FLOPThe run≈ 1.3 million H100 GPU-hours, reported
Pretraining in two halves, with Llama 3 8B’s published figures. The data pipeline decides what the model can learn; 6 × parameters × tokens decides what the run costs.

Chapter 7 trained a model on one megabyte of text in six minutes. A frontier model is trained on trillions of tokens over weeks, on thousands of GPUs. The algorithm is the same, and almost everything around it changes. This chapter covers what scale adds: where the data comes from, how to pick a model size for a compute budget, what a run costs, and how one model is spread across many machines.

Most teams should never pretrain a model, and the last section says why. The reason to know this material is to read model cards, estimate costs, and judge the claims people make about both.

8.1Data

The web, extracted, filtered and deduplicated.

A language model learns from text, and at this scale the text is mostly the public web. Turning a crawl into training data is a pipeline with a few standard stages:

  • Extract. Strip menus, ads and markup from each page and keep the main text.
  • Filter. Keep the languages you want; drop pages that are too short, repetitive, machine-generated or otherwise low in quality. The filters are a mix of simple rules and small classifiers.
  • Deduplicate. Remove exact copies and near-copies. The web repeats itself heavily, and repeated text is memorized instead of generalized from.
  • Tokenize and shuffle. Encode the text, mix it thoroughly, and write it into shards the training job can stream.
100%The crawlCommon Crawl48%Extract, identify languagemostly non-English removed23%Filter for qualityrules on repetition, length, linesabout 11%Deduplicatefuzzy and exact copies
100%The crawl48%Extractidentify language23%Filter for qualityabout 11%Deduplicate
Figure 8.1 Published figures from the RefinedWeb pipeline (Penedo and colleagues, 2023), built by the team that later made FineWeb: the share of the crawl’s documents left after each stage. Nearly nine in ten documents are discarded.

A public example is FineWeb: about 15 trillion tokens of English text, cleaned and deduplicated from the Common Crawl archive. Production training sets add other sources to the web text, mainly code, books, scientific papers and, increasingly, text written by other models.

Every stage discards a large share of what came in, and the model improves anyway. Two cautions belong here. Copies of public benchmarks end up in training data, which inflates scores on those benchmarks (Chapter 23). And what may be collected is a legal question as well as a technical one: site opt-outs, licensing and copyright all shape a real pipeline.

Common take“More data is better.”

Sharper take“Cleaner data is better. Filtering and deduplication throw away much of the crawl, and the model trained on what is left is stronger.”

8.2Scaling

Bigger models need more data, and you can see it at any size.

How much data can a model use? The question can be answered on a laptop with the counting models from Chapter 4, because a longer n-gram is a bigger model: it has more contexts to fill. I trained 2-, 3-, 4- and 6-gram models on samples of the Shakespeare text from ten thousand characters to a million.

1.52.02.510K100K1Mvalidation losscharacters of training text2-gram3-gram4-gram6-gram
1.52.02.510K100K1Mvalidation losscharacters of training text2-gram3-gram4-gram6-gram
Figure 8.2 Real experiment; note the logarithmic horizontal axis. The smallest model is finished learning almost at once: 2.58 to 2.49 across a hundredfold increase in data. The largest keeps improving at a steady rate, 2.27 to 1.57, with no sign of leveling off.

Three things in this small figure hold for language models of every size.

  • A small model saturates. Past a point, more data does nothing for it; its capacity is the limit.
  • A large model is wasted on little data. At ten thousand characters the 6-gram scores 2.27 and the 4-gram 2.26: the extra capacity has nothing to work with.
  • Returns are steady on a logarithmic scale. Each tenfold increase in data buys the large model a similar drop in loss. Constant gains for multiplied cost is what a scaling law looks like.

Common take“A bigger model is always better.”

Sharper take“A bigger model is better if it is fed enough. On ten thousand characters the largest model here was no better than a smaller one. On a million it was far ahead.”

8.3Chinchilla

For a fixed compute budget there is a best model size.

Section 5.9 gave the cost of training: about 6 FLOPs per parameter per token. For a model with N parameters trained on D tokens,

compute ≈ 6 · N · D

Fix the compute and you face a choice: a large model that sees little data, or a small model that sees a lot. In 2022 a DeepMind team trained over 400 models to map this trade and fitted a formula for the loss as a function of N and D. Plotted for three budgets, it looks like this:

2.02.53.03.510M1B100Bpredicted lossmodel parameters10¹⁹ FLOPs10²¹ FLOPs10²³ FLOPs
2.02.53.03.510M1B100Bpredicted lossmodel parameters10¹⁹ FLOPs10²¹ FLOPs10²³ FLOPs
Figure 8.3 Curves computed from the fitted formula in the Chinchilla paper. Each line is one compute budget spent on models of different sizes. Too small, and capacity is the limit; too large, and the model is starved of data. The best size grows with the budget.

The paper’s headline is that parameters and data should grow together, at about 20 tokens per parameter; its table of optimal sizes pairs a 1B-parameter model with about 20B tokens and a 10B model with about 205B. The fitted formula drawn above leans further toward data, 33 to 84 tokens per parameter across these budgets. The exact ratio depends on how the fit is done. The U shape does not.

The finding corrected a habit. GPT-3 had 175B parameters and was trained on about 300B tokens, under 2 tokens per parameter. The paper’s own model, Chinchilla, used 70B parameters and 1.4 trillion tokens, and outperformed a 280B-parameter model trained with the same compute.

Common take“The best model for a budget is the biggest one you can afford to train.”

Sharper take“For a fixed budget there is a best size, and it is smaller than instinct says. Going bigger on the same compute means less data and a worse model.”

8.4Past the optimum

Why production models train on far more data than Chinchilla suggests.

Chinchilla answers one question: what is the cheapest way to train to a given loss? A model that will be used heavily has a second cost, which is running it. A smaller model trained for longer costs more to train and less to serve on every request afterward.

That is why small models are deliberately overtrained. Llama 3’s 8B model was trained on about 15 trillion tokens, close to 1,900 tokens per parameter and nearly a hundred times the Chinchilla ratio. Past the optimum each extra token buys less, but the improvement is baked into a model that is cheap to run for its whole life.

1101001,000GPT-3 175B (2020)1.7Chinchilla 70B (2022)20Llama 2 7B (2023)286Llama 3 70B (2024)214Gemma 2 9B (2024)889Llama 3 8B (2024)1,875Qwen2.5 7B (2024)2,368Chinchilla 20:1
1101001,000GPT-3 175B (2020)1.7Chinchilla 70B (2022)20Llama 2 7B (2023)286Llama 3 70B (2024)214Gemma 2 9B (2024)889Llama 3 8B (2024)1,875Qwen2.5 7B (2024)2,368Chinchilla 20:1
Figure 8.4 Published parameter and training-token counts, divided. Since 2023, open models train ten to a hundred times past the compute-optimal ratio, because a smaller model trained longer is cheaper to serve. The scale is logarithmic.

Common take“Chinchilla says 20 tokens per parameter, so that is how models are trained.”

Sharper take“Chinchilla minimizes training cost alone. A model that will serve billions of requests is cheaper overall if it is smaller and trained far past that point.”

8.5Cost

6ND turns a model card into a bill.

The same formula prices a training run. Divide the FLOPs by what a GPU delivers and multiply by its hourly price. The estimates below assume 4 × 10¹⁴ useful FLOPs per second from one current data-center GPU, about 40% of its peak, at $2.50 per GPU-hour, the price used in Chapter 1.

Training runCompute (FLOPs)GPU-hoursCompute cost
1.9B parameters, 38B tokens4.3 × 10²⁰301$750
7B parameters, 140B tokens (20 per parameter)5.9 × 10²¹4,100$10,000
8B parameters, 15 trillion tokens7.2 × 10²³500,000$1.2 million
70B parameters, 15 trillion tokens6.3 × 10²⁴4,375,000$10.9 million

The first row is a check against a published figure. The nanochat repository reports training a model of that size on that many tokens in about 33 hours on a machine with eight GPUs, 264 GPU-hours, for about $800. The formula gives 301 GPU-hours and $752.

These are compute costs for one successful run. A real project multiplies them: failed runs, hyperparameter searches, evaluation, data processing and storage, and the team. The experiments around a run commonly cost several times the run itself.

For a mixture-of-experts model (section 5.8), use the active parameter count in the formula, since only the active experts compute on each token.

Figure 8.5 Computed live in your browser with compute ≈ 6 × parameters × tokens. The defaults are shaped like Llama 3 8B on an H100-class GPU; the price is illustrative. Meta reported about 1.3 million GPU-hours for that model, more than this estimate: real runs lose time to restarts, evaluation and lower utilization.

Common take“Training a language model costs hundreds of millions of dollars.”

Sharper take“The compute for one run is 6 × parameters × tokens. A 7B model at 20 tokens per parameter is about ten thousand dollars of GPU time; the same model on 15 trillion tokens is over a million. I price the tokens, then multiply for the experiments around the run.”

8.6Precision and memory

Train in 16 bits, keep 32 where it matters.

Section 3.4 counted the memory of training: weights, gradients and two optimizer statistics per weight, about 16 bytes per parameter. Large runs reduce time and memory with mixed precision. The forward and backward passes run in 16-bit numbers, which are faster and half the size. The master copy of the weights and the optimizer’s statistics stay in 32 bits, because tiny updates added to large weights vanish in 16.

The 16-bit format of choice is bfloat16. It covers the same range as a 32-bit float with fewer digits of precision, which avoids the overflow problems of the older half-precision format.

The other large consumer of memory is activations: every layer’s output for every token in the batch has to be kept for the backward pass. For long sequences this exceeds the weights. The standard relief is gradient checkpointing, which keeps only some layers’ activations and recomputes the rest during the backward pass, trading about a third more compute for much less memory.

Even so, a 7B-parameter model carries about 112 GB of training state, more than one 80 GB GPU holds. Past a few billion parameters, a model has to be split across devices.

FP32BF16FP16FP8 E4M3orange sign; blue exponent, the range; green mantissa, the precisionTraining with Adam, bytes per parameterweights2, in 16 bitsgradients2master copy4, in 32 bitsAdam moments8, in 32 bits16 bytes
Figure 8.6 Where the bytes go. BF16 keeps FP32’s range with less precision, which is why it trains stably; Adam’s state, not the weights, is most of the memory.

Common take“Lower precision means a worse model.”

Sharper take“The forward and backward passes tolerate 16 bits well. What needs 32 is the accumulation of small updates, so that part stays in 32.”

8.7Many GPUs

Three ways to split one training run.

Data parallelbatch Abatch BTensor parallelGPU 1GPU 2Pipeline parallelGPU 1GPU 2whole model on eachevery layer splitlayers split in order
Figure 8.7 Three kinds of parallelism. Dark blocks are the parts of the model a GPU holds. Large runs combine all three.
  • Data parallelism. Every GPU holds a full copy of the model and processes a different slice of the batch; the gradients are averaged. It is simple and scales well, but the model must fit on one GPU.
  • Sharded data parallelism removes that limit. The weights, gradients and optimizer state are divided among the GPUs, and each layer’s weights are gathered just before they are needed and released afterward. This is the idea behind ZeRO and PyTorch’s FSDP.
  • Tensor parallelism. Each layer’s matrices are split across GPUs, which compute their parts of the same layer at the same time. It needs very fast links, so it is used among the GPUs inside one machine.
  • Pipeline parallelism. Consecutive groups of layers live on different GPUs, and small batches flow through them like an assembly line.

In every scheme the scarce resource is communication. GPUs spend part of each step waiting for weights or gradients to cross the network, which is why training clusters are built around their interconnect and why throughput does not grow in proportion to the number of GPUs.

Common take“Twice the GPUs, half the time.”

Sharper take“Up to the point where communication dominates. I measure tokens per second per GPU as the cluster grows; when that number starts falling, more GPUs are buying less.”

8.8Keeping runs alive

Checkpoints, loss spikes, and small experiments first.

A run that lasts weeks on thousands of machines will meet hardware failures, so it saves a checkpoint regularly: the weights, the optimizer’s state and the position in the data. Resuming from one must reproduce the run exactly. The model in Chapter 7 was itself trained in two sessions joined by a checkpoint.

The characteristic failure at scale is the loss spike: the loss jumps suddenly and may or may not recover. Usual causes are a batch of unusual data, a learning rate that is too high for the current stage, or the optimizer’s running statistics going stale. The usual responses are to go back to the last checkpoint and skip the offending data, lower the learning rate, or tighten gradient clipping. Catching one early depends on logging more than the loss: gradient norm, the size of updates relative to weights (section 3.11), and throughput.

Because a full run is too expensive to repeat, design choices are tested at small scale first. Teams train models a hundred or a thousand times smaller to compare data mixtures, learning rates and architectural options, then carry over what holds up. The scaling behavior in sections 8.2 and 8.3 is what makes that extrapolation possible.

1.52.53.50k25k50k75k100ktraining losstraining stepscheckpoint at 55kspike at 60kresumed, bad batch skipped
1.52.53.50k25k50k75k100ktraining losstraining steps
  • the run that spiked
  • resumed from the checkpoint
Figure 8.8 Illustrative, not a real run: the routine response to a loss spike. Roll back to the last good checkpoint, skip the data that triggered it, lower the learning rate if it recurs, and continue.

Common take“Launch the big run and watch the loss.”

Sharper take“The big run is the last step. Before it come the small-scale experiments that chose its settings, a tested resume path, and alerts on gradient norm and throughput as well as loss.”

8.9The decision

Why most teams should not pretrain.

The compute bill is rarely what stops a team. What stops them is everything else: assembling and cleaning data at scale, the experiments needed to find settings that work, the people who know how to do both, and the months it takes while hosted models keep improving.

GoalUsually the right tool
General language tasksA hosted model, or open weights you serve (Chapter 1)
Your domain’s vocabulary, format or styleFine-tune open weights (Chapter 17)
Answers grounded in your documentsRetrieval (Chapter 14)
A lower serving costA smaller model, distilled or fine-tuned for the task
A kind of data no model has seen: a new modality, a scientific domain, a language with little public textPretraining may be justified

Fine-tuning an open model reuses the trillions of tokens someone else paid for and typically costs a thousandth as much or less. Pretraining earns its cost only when the knowledge you need is not in any existing model and you hold the data to supply it.

Common take“To own our model we have to train it from scratch.”

Sharper take“Owning the weights starts with fine-tuning open ones. Pretraining is for the case where no existing model has seen our kind of data at all.”

Key takeaways

  • Pretraining data is the web after extraction, filtering and deduplication. Each stage discards much of its input and the model improves.
  • A small model saturates and a large one is wasted on little data. In the experiment, the 2-gram moved from 2.58 to 2.49 over a hundredfold more data while the 6-gram went from 2.27 to 1.57.
  • Training compute ≈ 6 × parameters × tokens.
  • For a fixed compute budget there is a best model size. Chinchilla’s rule of thumb is about 20 tokens per parameter.
  • Production models train far past that ratio, because a smaller model trained longer is cheaper to serve: Llama 3 8B saw about 1,900 tokens per parameter.
  • Mixed precision runs the passes in 16 bits and keeps weights and optimizer state in 32.
  • One run is split across GPUs by data, by tensor and by pipeline, and communication is the limit.
  • Long runs need exact checkpoints, monitoring beyond the loss, and settings chosen by small-scale experiments.
  • Most teams should adapt an existing model. Pretraining is for data no model has seen.

Check your understanding

  1. Your team has 2 × 10²¹ FLOPs for one training run. One proposal is a 20B-parameter model; another is a 2B-parameter model. How many tokens does each get, how many tokens per parameter is that, and which does the scaling evidence favor? What changes if the model will serve a billion requests?

    Answer outline

    Tokens = compute ÷ (6 × parameters). The 20B model gets about 1.7 × 10¹⁰ tokens, under 1 token per parameter, which is badly starved. The 2B model gets about 1.7 × 10¹¹ tokens, about 83 per parameter, which is in the range the fitted curves favor for this budget. The 2B model should reach a lower loss. Heavy serving strengthens the case: the smaller model is also cheaper on every request, and if anything argues for going smaller still and training longer.

  2. A vendor says their 30B-parameter model was trained on 10 trillion tokens for under one million dollars. Check whether that is plausible and list the questions you would ask.

    Answer outline

    6 × 3 × 10¹⁰ × 10¹³ = 1.8 × 10²⁴ FLOPs. At 4 × 10¹⁴ useful FLOPs per GPU-second that is about 1.25 million GPU-hours, roughly three million dollars at $2.50 an hour. Under one million would need a price below about 80 cents per GPU-hour or about three times the efficiency. Possible explanations: owned hardware priced at cost, newer GPUs, or a mixture-of-experts model where 30B is the total and far fewer parameters are active. Ask for total versus active parameters, the hardware, the price basis, and whether the figure covers one run or the whole project.

  3. Two weeks into a three-week run, the loss jumps from 2.1 to 4.8 and stays there. What do you look at, and what are your options?

    Answer outline

    Look at the gradient norm and per-layer update sizes in the steps before the jump, the learning-rate schedule at that point, and the data in the batches around it. Options: restore the last good checkpoint and skip or reshuffle the suspect data; resume with a lower learning rate or tighter clipping; adjust the optimizer’s stability settings. Which one depends on what the logs show, and all of them depend on having a recent checkpoint, which is the reason to save them often.

Further reading

  • Hoffmann et al. (2022), “Training Compute-Optimal Large Language Models”: the Chinchilla paper. The figures are worth more than the text.
  • Hugging Face, “The Smol Training Playbook” (2025): a candid account of training a small model family, including the ablations and the things that went wrong.
  • Stanford CS336: the lectures on data, scaling laws and systems for training.
  • Chip Huyen, AI Engineering, chapter 2: the sections on training data and model size.

↑↓ to move↵ to openesc to close