Large Language Models: Pretraining & Scaling
Next-token prediction at internet scale.
GPT-3 was trained to do one thing: predict the next token of web text. Yet it could translate, answer questions and continue a pattern from a few examples in its prompt. This lesson takes that objective apart: what it optimizes, what it costs, how loss scales with model and data, and why the same objective produces fluent falsehoods.
What you’ll learn
- Write the causal and masked language-modeling objectives, and prove that the expected log loss is minimized by the true conditional distribution.
- Estimate training compute, including the attention term that leaves out, and choose a compute-optimal model size.
- Describe in-context learning and the circuit-level and Bayesian accounts of it.
- Explain why a calibrated model must hallucinate some facts, how decoding changes the error rate, and why contamination inflates benchmark scores.
Two pretraining objectives
A language model factors the probability of a token sequence by the chain rule. Causal language modeling, the objective of the GPT series and of most large language models, fits it by maximum likelihood on raw text. The text supplies its own labels, which makes pretraining self-supervised:
Masked language modeling (BERT; Devlin et al., 2019) corrupts the input and predicts the corrupted tokens from both sides with a bidirectional encoder. BERT selects 15% of positions; of these, 80% become [MASK], 10% a random token and 10% stay unchanged, and the loss counts only the selected positions. T5 (Raffel et al., 2020) masks whole spans and has a decoder write them out.
| Objective | Predicts | Context | Typical use |
|---|---|---|---|
| Causal LM (GPT) | every next token | left only | generation, prompting |
| Masked LM (BERT) | 15% of tokens, from a corrupted input | both sides | representations for classification, retrieval, tagging |
| Span corruption (T5) | masked spans, written by a decoder | both sides (encoder) | sequence-to-sequence tasks |
Fix a context with true next-token distribution . The expected loss of a model splits into an entropy and a KL divergence (Information Theory for AI):
The KL term is nonnegative and vanishes only at . So the population minimizer of the pretraining loss is the true conditional distribution, context by context: a perfectly trained model is calibrated, not just right about the likeliest token.
By the chain rule the per-token loss can never fall below the entropy rate of text, the floor that the irreducible term of scaling laws tries to estimate. Grammar, facts, styles and arithmetic are learned only insofar as they lower this one number.
Why does BERT leave some selected tokens unchanged or random, instead of always inserting [MASK]?
- To make training faster
- So that any visible token might be a prediction target, forcing a good representation of every token, and because
[MASK]never appears at fine-tuning time - Because
[MASK]tokens would leak the answer - To add label noise as a regularizer
Show the answer
B. So that any visible token might be a prediction target, forcing a good representation of every token, and because [MASK] never appears at fine-tuning time
If the targets were always marked, the model could treat real tokens as mere context and learn less about representing them, and fine-tuning inputs contain no [MASK] at all. Mixing in unchanged and random tokens makes every position a possible target.
What pretraining costs
Training compute is about FLOPs for parameters and tokens (The Scaling Era & the Bitter Lesson). That count covers the weight matrices only; attention adds work that grows with the context length .
Per token and layer, the forward pass multiplies by the weights, FLOPs, and attends over the context: scores and mixing cost over a full context, about half that averaged over positions under a causal mask. Kaplan et al. (2020) count
Relative to the weight term, the attention term is
For GPT-3 (, ) that is , so is accurate. At with it would be : long-context training is dominated by attention unless that term is reduced (Efficient Attention & Long Context).
GPT-3 is the landmark of this regime (Brown et al., 2020): 175 billion parameters in 96 layers, trained on about 300 billion tokens of filtered web crawl, curated web text, books and Wikipedia, for about FLOPs. The mixture was weighted by quality rather than size, so Wikipedia was seen more than three times and most of the crawl less than once.
Scaling laws in practice
How should a budget be split between and ? The Scaling Era & the Bitter Lesson derived the answer from the fit of Hoffmann et al. (2022): grow both roughly as , about 20 tokens per parameter. Three consequences are worth computing.
With and , what is the compute-optimal model size for FLOPs, in billions of parameters?
Show the answer
91 B
, so , trained on tokens. Sanity check: Chinchilla's FLOPs give , its actual size.
- Diminishing returns. Each reducible term is a power law, so equal multiplicative investments buy equal fractional gains. With , doubling multiplies the model term by . Under Kaplan et al.'s single-variable fit , halving the loss would take times more parameters.
- Inference changes the optimum. Chinchilla-optimal minimizes training compute for a given loss, but a deployed model pays about FLOPs for every token it generates. A smaller model trained on more tokens can be cheaper overall: LLaMA (Touvron et al., 2023) trained a 7-billion-parameter model on a trillion tokens, about 140 per parameter, for this reason.
- Loss is not capability. Scaling laws predict average loss. Wei et al. (2022) called abilities absent in small models but present in large ones emergent, while Schaeffer, Miranda & Koyejo (2023) showed that many such jumps shrink or vanish under continuous metrics. Which abilities are genuinely abrupt is contested.
In-context learning
GPT-3's headline result was in-context learning: given a task description and worked examples in the prompt, with from zero to as many as fit in its 2,048-token context, the model performed the task on a new input with no gradient update. The gap between zero-shot and few-shot performance grew with model size: the largest model gained the most from its examples (Brown et al., 2020).
Translate English to French: // task description
sea otter => loutre de mer // demonstrations
bread => pain
cheese => fromage
peppermint => // query: the model continues the patternNothing marks this as a task. To the model it is text whose likeliest continuation is " menthe poivrée"; the examples are conditioning, not training data.
Two accounts of why this works are developed in the Deep Layer. In the Bayesian view (Xie et al., 2022), pretraining text mixes many latent "concepts", predicting the next token well requires inferring which one generated the current document, and demonstrations are evidence that sharpens that posterior. In the mechanistic view, specific circuits carry out the inference. The best understood is the induction head (Elhage et al., 2021; Olsson et al., 2022), a two-head circuit that completes [A][B] … [A] → [B]. Its first half is a previous-token head:
Hallucination and contamination
A hallucination is fluent output that is false or unsupported. The objective explains much of it: the loss rewards matching the distribution of text, not truth, and a well-trained model must spread probability over plausible continuations wherever its training data leave the answer open.
The intuition is Good–Turing (N-gram Models & Smoothing): facts seen once estimate the probability mass of facts never seen. A calibrated model must put about that much mass on unseen candidates and cannot tell true ones from false ones, so a matching share of its outputs is wrong. The bound says nothing about facts that recur often or about systematic knowledge such as arithmetic, and post-training can teach a model to abstain instead of guessing (Fine-Tuning, RLHF & Prompting). Decoding moves the error rate too:
Contamination is the evaluation-side failure. Web-scale corpora contain benchmark items, so a model can score well by recall. GPT-3's authors searched for 13-gram overlaps between benchmarks and training data, found contamination, and reported results on cleaned subsets after a filtering bug let some overlap through (Brown et al., 2020). Without the training data, detection becomes a membership inference problem, treated in Evaluating Language Models.
Key takeaways
- Causal LM maximizes over raw text; masked LM predicts corrupted tokens from both sides. The log loss is proper: its minimizer is the true conditional distribution, and the entropy rate of text is a floor.
- Training costs about FLOPs plus an attention fraction . Compute-optimal training grows and together, about 20 tokens per parameter, while inference costs push deployed models to be smaller and trained longer.
- Loss falls as a power law with diminishing returns; whether downstream abilities emerge abruptly, or only look abrupt under discontinuous metrics, is contested.
- In-context learning conditions on demonstrations without weight updates; induction heads and implicit Bayesian inference are the leading accounts.
- Calibrated next-token predictors must hallucinate arbitrary rare facts at roughly the once-seen rate; decoding settings move the error rate, and contamination inflates benchmark scores.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A model attains the minimum possible expected pretraining loss. For a context whose true next token is "yes" with probability 0.6 and "no" with 0.4, what does it output?
- Probability 1 on "yes", the likelier token
- 0.6 on "yes" and 0.4 on "no"
- 0.5 each, the maximum-entropy choice
- It depends on the temperature used in training
Show the answer
B. 0.6 on "yes" and 0.4 on "no"
The expected log loss is , minimized only at . Log loss rewards calibrated probabilities, not confident guesses.
Why does underestimate the training compute of a model trained on very long contexts?
- It assumes 32-bit arithmetic
- It counts only the backward pass
- It ignores attention scores and mixing, which add a fraction of about to the weight FLOPs
- It ignores the embedding table, which dominates large models
Show the answer
C. It ignores attention scores and mixing, which add a fraction of about to the weight FLOPs
Per token and layer, attention adds about forward FLOPs against for the weights: negligible at 2,048 tokens with , comparable to the rest at 100,000 tokens.
In Kalai and Vempala's analysis, which facts must a calibrated pretrained model hallucinate at a substantial rate?
- Arithmetic results, which follow rules
- Facts that appear many times in the training data
- Only facts that were stated wrongly in the training data
- Arbitrary facts of a kind that often appear only once, since the share of once-seen facts estimates the unseen mass
Show the answer
D. Arbitrary facts of a kind that often appear only once, since the share of once-seen facts estimates the unseen mass
By Good–Turing, the once-seen fraction estimates the mass of unseen facts, which a calibrated model must spread over candidates it cannot verify. The bound holds even with error-free data and gives nothing for systematic or often-repeated facts.
A model will generate trillions of tokens in deployment. Compared with the Chinchilla-optimal choice for its training budget, how should it be trained?
- Smaller, on more than 20 tokens per parameter
- Larger, on fewer tokens
- Exactly Chinchilla-optimal, since that minimizes the loss
- Smaller, on fewer tokens
Show the answer
A. Smaller, on more than 20 tokens per parameter
Each generated token costs about FLOPs, so a smaller saves inference compute, and extra training tokens recover the loss. LLaMA's 7-billion-parameter model saw about 140 tokens per parameter for this reason.
Go deeper
- Scaling Laws · Power laws in loss and compute-optimal training.
- In-Context Learning & Emergence · Learning from the prompt, and whether abilities “emerge”.
- Mechanistic Interpretability · Circuits, features and superposition inside transformers.
Further reading
- T. B. Brown et al., "Language models are few-shot learners," NeurIPS (2020).
- J. Devlin, M.-W. Chang, K. Lee & K. Toutanova, "BERT: Pre-training of deep bidirectional transformers for language understanding," NAACL (2019).
- J. Hoffmann et al., "Training compute-optimal large language models," NeurIPS (2022).
- A. T. Kalai & S. S. Vempala, "Calibrated language models must hallucinate," STOC (2024).