Simple Algorithm
Artificial Intelligence · Hidden Layer · 24 min

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 C≈6NDC\approx6ND 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:

LCLM(θ)=−Ex∼D∑t=1Tlog⁡pθ(xt∣x<t)\loss_{\text{CLM}}(\theta)=-\E_{\mathbf x\sim\data}\sum_{t=1}^{T}\log p_\theta(x_t\mid x_{<t})
With a causal mask, one forward pass scores all TT positions (Attention & Transformers). Divided by TT this is the per-token cross-entropy, whose exponential is the perplexity (From N-grams to Embeddings).

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.

ObjectivePredictsContextTypical use
Causal LM (GPT)every next tokenleft onlygeneration, prompting
Masked LM (BERT)15% of tokens, from a corrupted inputboth sidesrepresentations for classification, retrieval, tagging
Span corruption (T5)masked spans, written by a decoderboth sides (encoder)sequence-to-sequence tasks
Bidirectional context helps on understanding tasks, but an encoder has no natural way to write text left to right. Causal models read and write with one network, and every token is a training target, not 15%; as of the mid-2020s general-purpose LLMs are almost all decoder-only.
DerivationThe log loss is a proper scoring rule
  1. Ex∼p(⋅∣c)[−log⁡q(x∣c)]=H(p(⋅∣c))+DKL(p(⋅∣c) ∥ q(⋅∣c))\E_{x\sim p(\cdot\mid c)}\big[-\log q(x\mid c)\big]=H\big(p(\cdot\mid c)\big)+\KL\big(p(\cdot\mid c)\,\big\|\,q(\cdot\mid c)\big)

    Fix a context cc with true next-token distribution p(⋅∣c)p(\cdot\mid c). The expected loss of a model qq splits into an entropy and a KL divergence (Information Theory for AI):

  2. arg min⁡q Ec Ex∣c[−log⁡q(x∣c)]=p(⋅∣c)whenever p(c)>0\argmin_q\ \E_c\,\E_{x\mid c}\big[-\log q(x\mid c)\big]=p(\cdot\mid c)\quad\text{whenever }p(c)>0

    The KL term is nonnegative and vanishes only at q=pq=p. 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.

  3. 1T LCLM ≥ 1T∑t=1TH(Xt∣X<t)=1T H(X1,…,XT)\frac1T\,\loss_{\text{CLM}}\ \ge\ \frac1T\sum_{t=1}^TH(X_t\mid X_{<t})=\frac1T\,H(X_1,\dots,X_T)

    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.

Check your understanding

Why does BERT leave some selected tokens unchanged or random, instead of always inserting [MASK]?

  1. To make training faster
  2. 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
  3. Because [MASK] tokens would leak the answer
  4. 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 C≈6NDC\approx6ND FLOPs for NN parameters and DD tokens (The Scaling Era & the Bitter Lesson). That count covers the weight matrices only; attention adds work that grows with the context length nctxn_{\text{ctx}}.

DerivationThe attention term in the FLOP count
  1. Cfwd≈2N+2 L nctx dper token,N≈12Ld2C_{\text{fwd}}\approx2N+2\,L\,n_{\text{ctx}}\,d\quad\text{per token},\qquad N\approx12Ld^2

    Per token and layer, the forward pass multiplies by the weights, 2×12d22\times12d^2 FLOPs, and attends over the context: scores and mixing cost 4nctxd4n_{\text{ctx}}d over a full context, about half that averaged over positions under a causal mask. Kaplan et al. (2020) count

  2. 2Lnctxd2N=2Lnctxd24Ld2=nctx12 d\frac{2Ln_{\text{ctx}}d}{2N}=\frac{2Ln_{\text{ctx}}d}{24Ld^2}=\frac{n_{\text{ctx}}}{12\,d}

    Relative to the weight term, the attention term is

  3. 204812×12,288≈0.014,128,00012×8192≈1.3\frac{2048}{12\times12{,}288}\approx0.014,\qquad\frac{128{,}000}{12\times8192}\approx1.3

    For GPT-3 (nctx=2048n_{\text{ctx}}=2048, d=12,288d=12{,}288) that is 1.4%1.4\%, so 6ND6ND is accurate. At nctx=128,000n_{\text{ctx}}=128{,}000 with d=8192d=8192 it would be 130%130\%: 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 3×10233\times10^{23} 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 CC be split between NN and DD? The Scaling Era & the Bitter Lesson derived the answer from the fit L(N,D)=E+A/Nα+B/DβL(N,D)=E+A/N^{\alpha}+B/D^{\beta} of Hoffmann et al. (2022): grow both roughly as C\sqrt C, about 20 tokens per parameter. Three consequences are worth computing.

Predict before you look

With D≈20ND\approx20N and C≈6NDC\approx6ND, what is the compute-optimal model size for C=1024C=10^{24} FLOPs, in billions of parameters?

Show the answer

91 B

C=6N⋅20N=120N2C=6N\cdot20N=120N^2, so N=1024/120≈9.1×1010N=\sqrt{10^{24}/120}\approx9.1\times10^{10}, trained on D≈1.8×1012D\approx1.8\times10^{12} tokens. Sanity check: Chinchilla's 5.9×10235.9\times10^{23} FLOPs give N≈7×1010N\approx7\times10^{10}, its actual size.

  • Diminishing returns. Each reducible term is a power law, so equal multiplicative investments buy equal fractional gains. With α≈0.34\alpha\approx0.34, doubling NN multiplies the model term A/NαA/N^\alpha by 2−0.34≈0.792^{-0.34}\approx0.79. Under Kaplan et al.'s single-variable fit L∝N−0.076L\propto N^{-0.076}, halving the loss would take 21/0.076≈1042^{1/0.076}\approx10^4 times more parameters.
  • Inference changes the optimum. Chinchilla-optimal minimizes training compute for a given loss, but a deployed model pays about 2N2N 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 kk worked examples in the prompt, with kk 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).

text
Translate English to French:        // task description
sea otter => loutre de mer          // demonstrations
bread => pain
cheese => fromage
peppermint =>                       // query: the model continues the pattern

Nothing 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 ∑tlog⁡pθ(xt∣x<t)\sum_t\log p_\theta(x_t\mid x_{<t}) 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 6ND6ND FLOPs plus an attention fraction nctx/(12d)n_{\text{ctx}}/(12d). Compute-optimal training grows NN and DD 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.

Question 1

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?

  1. Probability 1 on "yes", the likelier token
  2. 0.6 on "yes" and 0.4 on "no"
  3. 0.5 each, the maximum-entropy choice
  4. 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 H(p)+DKL(p ∥ q)H(p)+\KL(p\,\|\,q), minimized only at q=pq=p. Log loss rewards calibrated probabilities, not confident guesses.

Question 2

Why does C≈6NDC\approx6ND underestimate the training compute of a model trained on very long contexts?

  1. It assumes 32-bit arithmetic
  2. It counts only the backward pass
  3. It ignores attention scores and mixing, which add a fraction of about nctx/(12d)n_{\text{ctx}}/(12d) to the weight FLOPs
  4. 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 nctx/(12d)n_{\text{ctx}}/(12d) to the weight FLOPs

Per token and layer, attention adds about 2nctxd2n_{\text{ctx}}d forward FLOPs against 24d224d^2 for the weights: negligible at 2,048 tokens with d=12,288d=12{,}288, comparable to the rest at 100,000 tokens.

Question 3

In Kalai and Vempala's analysis, which facts must a calibrated pretrained model hallucinate at a substantial rate?

  1. Arithmetic results, which follow rules
  2. Facts that appear many times in the training data
  3. Only facts that were stated wrongly in the training data
  4. 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.

Question 4

A model will generate trillions of tokens in deployment. Compared with the Chinchilla-optimal choice for its training budget, how should it be trained?

  1. Smaller, on more than 20 tokens per parameter
  2. Larger, on fewer tokens
  3. Exactly Chinchilla-optimal, since that minimizes the loss
  4. Smaller, on fewer tokens
Show the answer

A. Smaller, on more than 20 tokens per parameter

Each generated token costs about 2N2N FLOPs, so a smaller NN 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

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).