5.3 — The language-modeling objective
Goal: State the autoregressive factorisation p(x_1, …, x_T) = ∏ p(x_t | x_{<t}), derive next-token cross-entropy as the MLE loss, and connect both to perplexity and the entropy lower bound.
1. Why this session exists
A language model is any probability distribution over token sequences:
To train a language model, we need (a) a parametric family , and (b) a loss function whose minimisation makes close to the true distribution underlying the data. This session derives both from first principles. The factorisation is universal — it works for any sequence — and the loss is precisely the cross-entropy minimisation we already saw in 0.7 and 1.8, now lifted to sequences.
After this session, the rest of Chapter 5 (and all of Chapters 6–9) operates under the autoregressive objective. Every architecture we look at is a different parameterisation of . Attention, MLP, normalisation, residuals — these are all design choices for the same function we define here.[2, 3]
2. The chain rule of probability
For any joint distribution over random variables, the chain rule of probability says:
We write for the prefix, with (the empty prefix). Then
This is an identity, not a modelling choice. It is true for any joint distribution. The chain rule reorganises the joint probability as a product of conditionals.
What is a modelling choice is the autoregressive parameterisation: we choose to model the joint by directly parameterising each of the conditionals . Equivalently, we let one model produce a categorical distribution over the next token given the prefix, and the joint emerges by multiplication.
2.1 Why this factorisation and not another
The chain rule is symmetric in its choice of ordering. We could equally well write
a "right-to-left" factorisation. Or any other permutation, though only the strict left-to-right and right-to-left orderings preserve the causal structure of text.
Three reasons left-to-right wins for practical language modelling:
- Inference matches generation. We want to produce text. Sampling left-to-right from is the natural way: extend a prefix one token at a time. Right-to-left would force you to know the end of the sentence before the beginning.
- Causal mask is implementable. With one-direction conditioning, every layer of the model can be written so that the representation at position depends only on positions . This is the causal mask of Chapter 6.4 and is what lets us train on all positions in parallel from a single forward pass.
- The conditional structure matches human language production. Words are written and spoken in time order. The causal direction matches the data-generating process.
Masked language modelling (BERT-style) drops autoregression and conditions each token on both sides simultaneously — a bidirectional factorisation. This is excellent for representation learning (encoder tasks like classification, retrieval, NER) but it doesn't directly support generation. Modern decoder-only LLMs (GPT, LLaMA, Claude) use the autoregressive factorisation throughout.
3. From the joint to the loss: maximum likelihood
Suppose we have a corpus of documents (or "examples"), where document is a token sequence . Assume documents are i.i.d. draws from the true (unknown) distribution . The maximum-likelihood estimator for a model family maximises the log-likelihood of the corpus:
Substitute the autoregressive factorisation:
The negative log-likelihood, the standard quantity we minimise, is
Dividing by the total number of tokens converts this to a per-token negative log-likelihood, often called the next-token cross-entropy loss (the multiclass CE of 1.8, applied at each time step):
Every modern LLM minimises this loss. There is no auxiliary objective for the main pretraining stage of GPT-style models — just predict the next token, averaged over every position in every document.
3.1 Why this loss is "right"
Two equivalent justifications:
(a) Maximum likelihood. As derived above, minimising is maximising the probability that assigns to the observed corpus. Under standard regularity conditions (compact parameter space, identifiability), MLE is consistent: as if the true distribution lies in the model family.
(b) Cross-entropy with the data distribution. Let be the true distribution. Then the population version of is
(We saw this decomposition in 0.7 §3.) Since doesn't depend on , minimising the cross-entropy is equivalent to minimising the average KL divergence of the model from the truth, position by position. That is the strongest "fit the data" criterion we have.
3.2 The lower bound
Both of these views agree that the loss has a non-zero floor:
is the entropy of natural language, the irreducible per-token uncertainty inherent in the data. No language model can drive its loss below this floor — even the true distribution achieves , not zero. Empirically, the per-token entropy of English from a well-trained LM is around 1.5–2.5 nats (corresponding to 2–4 bits), depending on tokeniser and domain.
4. Per-token cross-entropy in practice
Concretely, the model outputs logits for each position — a -dim vector of unnormalised scores. The conditional distribution is the softmax:
The loss at position , given the true target , is the standard one-hot cross-entropy:
We already derived the gradient of this in 1.8 §4: . The "predicted minus target" form. For the full LM loss we sum (or average) over all positions and all examples.
Numerical stability. The term must be computed with the log-sum-exp trick from 0.10 §4, or training underflows immediately. Frameworks do this automatically when you call cross_entropy(logits, targets).
5. Perplexity
The most common single number used to report LM quality is perplexity — the exponentiated per-token loss:
Three interpretations make the number tangible:
(a) Geometric average of . Rewrite:
If the model assigns probability to each true token, perplexity is . A perplexity of 20 means "on average, the model is as uncertain as if it were uniformly choosing between 20 options."
(b) Effective vocabulary size. A model that assigns probability to every token (no information) has PPL . A perfect model that always assigns 1 to the truth has PPL . PPL is the "effective branching factor" at each position.
(c) Exponential of bits. Cross-entropy in nats = cross-entropy in bits. Perplexity . A model with 2 bits/token has PPL . Empirically, modern LLMs on web English clock in at 1–2 bits/token (PPL 2–4).
PPL is the standard benchmark number for pretraining experiments. Across papers, the conventions about tokenisation, document boundaries, and corpus differ enough that PPL is most meaningful as a relative comparison (model A vs model B trained and evaluated identically), not as an absolute number.
[1, 4]6. The structural picture
The autoregressive setup gives one model with one input/output interface, applied times in parallel during training and times sequentially during inference:
- Training (parallel). Take a document of length . Compute in a single forward pass using a causal mask (Chapter 6.4) so depends only on . Compute at each position. Sum and backprop. One forward, one backward, supervised predictions.
- Inference (sequential). Start with a prompt . Compute , sample (or take , or apply temperature/top- — see Chapter 10). Append to the prefix. Repeat. One step per generated token.
The parallel training step is the source of the GPU efficiency that makes Transformer pretraining feasible. It is also why we use the left-to-right causal factorisation: only this ordering admits the trick of "supervise every position from a single forward pass."
7. What we keep going forward
For the rest of the course, when we say "the language model loss" we mean:
with a softmax over a vocabulary of size , and computed by whatever architecture we are studying. The objective is fixed. The architectures evolve.
5.4 looks at the simplest possible architecture — the -gram model — and quantifies how badly it fails. 5.5 looks at recurrent networks, the family that LLMs replaced. Chapter 6 introduces attention and the model that actually works at scale.
(a) Show that the chain rule follows from the definition of conditional probability and induction on . Why is no independence assumption needed?
(b) Compute the per-token cross-entropy in nats for a model that assigns probability to the true next token at every position, and convert it to bits and to perplexity.
(c) Two models trained on the same corpus achieve cross-entropies nats/token and nats/token. By what factor is model B's per-token probability of the truth higher than model A's? What is the ratio of perplexities?
(d) The empirical per-token cross-entropy of English is roughly 1.5 nats. What does this mean operationally about the floor of pretraining loss for English text? Can a model achieve ?
(e) Suppose a model is trained on documents using the autoregressive loss above, but at inference time you ask it to fill in the middle of a sentence (the words "" are missing). Argue from the factorisation why the model cannot directly answer this without prefix-suffix tricks.
References
- [1]
Luo, W., Li, Y., Urtasun, R., & Zemel, R. (2016). "Understanding the effective receptive field in deep convolutional neural networks". NeurIPS. arXiv:1701.04128 — Effective vs theoretical receptive field; Gaussian shape (4.2 §5.3).
↩ - [2]
Jurafsky, D., & Martin, J. H. (2024). Speech and Language Processing (3rd ed., draft). — Canonical reference for tokenisation (5.1), n-grams and smoothing (5.4), and language-modeling fundamentals (5.3). stanford.edu/~jurafsky/slp3
↩ - [3]
Manning, C., et al. CS224N: Natural Language Processing with Deep Learning. Stanford. — Lectures on subword tokenisation and language modelling (5.1, 5.3).
↩ - [4]
Ouyang, L., Wu, J., Jiang, X., et al. (2022). "Training language models to follow instructions with human feedback" (InstructGPT). arXiv:2203.02155 — Canonical SFT + RM + PPO pipeline (9.1, 9.2, 9.8); per-token KL implementation (9.9); PPO-ptx mixing (9.8 §5.3).
↩