AI / ML Theory
Chapter 5 · 20 min

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:

p(x1,x2,…,xT),xt∈V, V={1,…,V}.p(x_1, x_2, \dots, x_T), \qquad x_t \in \mathcal{V}, \ \mathcal{V} = \{1, \dots, V\}.

To train a language model, we need (a) a parametric family pθp_\theta, and (b) a loss function whose minimisation makes pθp_\theta 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 pθ(xt∣x<t)p_\theta(x_t \mid x_{<t}). 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 TT random variables, the chain rule of probability says:

 p(x1,x2,…,xT)=∏t=1Tp(xt∣x1,…,xt−1). \boxed{\ p(x_1, x_2, \dots, x_T) = \prod_{t = 1}^{T} p(x_t \mid x_1, \dots, x_{t - 1}). \ }

We write x<t=(x1,…,xt−1)x_{<t} = (x_1, \dots, x_{t-1}) for the prefix, with x<1=∅x_{<1} = \emptyset (the empty prefix). Then

p(x1,…,xT)=∏t=1Tp(xt∣x<t).p(x_1, \dots, x_T) = \prod_{t=1}^{T} p(x_t \mid x_{<t}).

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 TT conditionals p(xt∣x<t)p(x_t \mid x_{<t}). 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

p(x1,…,xT)=∏t=T1p(xt∣x>t),p(x_1, \dots, x_T) = \prod_{t = T}^{1} p(x_t \mid x_{> t}),

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:

  1. Inference matches generation. We want to produce text. Sampling left-to-right from p(xt∣x<t)p(x_t \mid x_{<t}) 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.
  2. Causal mask is implementable. With one-direction conditioning, every layer of the model can be written so that the representation at position tt depends only on positions ≤t\le t. This is the causal mask of Chapter 6.4 and is what lets us train on all TT positions in parallel from a single forward pass.
  3. 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 NN documents (or "examples"), where document nn is a token sequence x(n)=(x1(n),…,xTn(n))\mathbf{x}^{(n)} = (x_1^{(n)}, \dots, x_{T_n}^{(n)}). Assume documents are i.i.d. draws from the true (unknown) distribution p⋆p^\star. The maximum-likelihood estimator for a model family pθp_\theta maximises the log-likelihood of the corpus:

θ^MLE=arg⁡max⁡θ ∑n=1Nlog⁡pθ(x(n)).\hat\theta_\text{MLE} = \arg\max_\theta\ \sum_{n=1}^{N} \log p_\theta(\mathbf{x}^{(n)}).

Substitute the autoregressive factorisation:

log⁡pθ(x(n))=∑t=1Tnlog⁡pθ(xt(n)∣x<t(n)).\log p_\theta(\mathbf{x}^{(n)}) = \sum_{t=1}^{T_n} \log p_\theta(x_t^{(n)} \mid x_{<t}^{(n)}).

The negative log-likelihood, the standard quantity we minimise, is

 L(θ)=−∑n=1N∑t=1Tnlog⁡pθ(xt(n)∣x<t(n)). \boxed{\ \mathcal{L}(\theta) = -\sum_{n=1}^{N} \sum_{t=1}^{T_n} \log p_\theta(x_t^{(n)} \mid x_{<t}^{(n)}). \ }

Dividing by the total number of tokens ∑nTn\sum_n T_n 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):

 Ltoken(θ)=−E(x,t) log⁡pθ(xt∣x<t). \boxed{\ \mathcal{L}_\text{token}(\theta) = -\mathbb{E}_{(\mathbf{x}, t)}\, \log p_\theta(x_t \mid x_{<t}). \ }

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 L\mathcal{L} is maximising the probability that pθp_\theta assigns to the observed corpus. Under standard regularity conditions (compact parameter space, identifiability), MLE is consistent: θ^MLE→θ⋆\hat\theta_\text{MLE} \to \theta^\star as N→∞N \to \infty if the true distribution lies in the model family.

(b) Cross-entropy with the data distribution. Let p⋆p^\star be the true distribution. Then the population version of Ltoken\mathcal{L}_\text{token} is

Ex∼p⋆, t [−log⁡pθ(xt∣x<t)]=H(p⋆)+E[KL ⁣(p⋆(⋅∣x<t) ∥ pθ(⋅∣x<t))].\mathbb{E}_{\mathbf{x} \sim p^\star,\, t}\, \left[ -\log p_\theta(x_t \mid x_{<t}) \right] = H(p^\star) + \mathbb{E}\left[ \mathrm{KL}\!\left( p^\star(\cdot \mid x_{<t}) \,\|\, p_\theta(\cdot \mid x_{<t}) \right) \right].

(We saw this decomposition in 0.7 §3.) Since H(p⋆)H(p^\star) doesn't depend on θ\theta, 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:

 Ltoken(θ)≥H(p⋆)=−Ex∼p⋆, t log⁡p⋆(xt∣x<t). \boxed{\ \mathcal{L}_\text{token}(\theta) \ge H(p^\star) = -\mathbb{E}_{\mathbf{x} \sim p^\star,\, t}\, \log p^\star(x_t \mid x_{<t}). \ }

H(p⋆)H(p^\star) 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 Ltoken=H(p⋆)\mathcal{L}_\text{token} = H(p^\star), 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 zt∈RVz_t \in \mathbb{R}^V for each position tt — a VV-dim vector of unnormalised scores. The conditional distribution is the softmax:

pθ(xt=k∣x<t)=exp⁡(zt,k)∑j=1Vexp⁡(zt,j)=softmax(zt)k.p_\theta(x_t = k \mid x_{<t}) = \frac{\exp(z_{t,k})}{\sum_{j=1}^V \exp(z_{t,j})} = \text{softmax}(z_t)_k.

The loss at position tt, given the true target yt=xty_t = x_t, is the standard one-hot cross-entropy:

ℓt=−log⁡ softmax(zt)yt=−zt,yt+log⁡∑jexp⁡(zt,j).\ell_t = -\log\, \text{softmax}(z_t)_{y_t} = -z_{t, y_t} + \log \sum_j \exp(z_{t, j}).

We already derived the gradient of this in 1.8 §4: ∂ℓt/∂zt,k=softmax(zt)k−1[k=yt]\partial \ell_t / \partial z_{t, k} = \text{softmax}(z_t)_k - \mathbb{1}[k = y_t]. The "predicted minus target" form. For the full LM loss we sum (or average) ℓt\ell_t over all positions and all examples.

Numerical stability. The log⁡∑jexp⁡(zt,j)\log \sum_j \exp(z_{t, j}) 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:

 PPL=exp⁡(Ltoken)=exp⁡ ⁣(−1N∑tlog⁡pθ(xt∣x<t)). \boxed{\ \text{PPL} = \exp(\mathcal{L}_\text{token}) = \exp\!\left( -\frac{1}{N} \sum_t \log p_\theta(x_t \mid x_{<t}) \right). \ }

Three interpretations make the number tangible:

(a) Geometric average of 1/p1/p. Rewrite:

PPL=(∏t1pθ(xt∣x<t))1/N.\text{PPL} = \left( \prod_t \frac{1}{p_\theta(x_t \mid x_{<t})} \right)^{1/N}.

If the model assigns probability pp to each true token, perplexity is 1/p1/p. 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 1/V1/V to every token (no information) has PPL =V= V. A perfect model that always assigns 1 to the truth has PPL =1= 1. PPL is the "effective branching factor" at each position.

(c) Exponential of bits. Cross-entropy in nats ×log⁡2e\times \log_2 e = cross-entropy in bits. Perplexity =2bits/token= 2^{\text{bits/token}}. A model with 2 bits/token has PPL =4= 4. 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 TT times in parallel during training and TT times sequentially during inference:

  • Training (parallel). Take a document of length TT. Compute z1,…,zTz_1, \dots, z_T in a single forward pass using a causal mask (Chapter 6.4) so ztz_t depends only on x<tx_{<t}. Compute ℓt\ell_t at each position. Sum and backprop. One forward, one backward, TT supervised predictions.
  • Inference (sequential). Start with a prompt x1,…,xkx_1, \dots, x_k. Compute zkz_k, sample xk+1∼softmax(zk)x_{k+1} \sim \text{softmax}(z_k) (or take arg⁡max⁡\arg\max, or apply temperature/top-pp — see Chapter 10). Append xk+1x_{k+1} 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:

Ltoken(θ)=−1∣corpus∣∑(x,t) ∈ corpuslog⁡pθ(xt∣x<t),\mathcal{L}_\text{token}(\theta) = -\frac{1}{|\text{corpus}|}\sum_{(\mathbf{x}, t)\,\in\,\text{corpus}} \log p_\theta(x_t \mid x_{<t}),

with pθp_\theta a softmax over a vocabulary of size VV, and pθ(⋅∣x<t)p_\theta(\cdot \mid x_{<t}) computed by whatever architecture we are studying. The objective is fixed. The architectures evolve.

5.4 looks at the simplest possible architecture — the nn-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.

Self-test

(a) Show that the chain rule p(x1,…,xT)=∏tp(xt∣x<t)p(x_1, \dots, x_T) = \prod_t p(x_t \mid x_{<t}) follows from the definition of conditional probability and induction on TT. Why is no independence assumption needed?

(b) Compute the per-token cross-entropy in nats for a model that assigns probability 0.30.3 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 LA=2.0\mathcal{L}_A = 2.0 nats/token and LB=1.5\mathcal{L}_B = 1.5 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 Ltoken=0\mathcal{L}_\text{token} = 0?

(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 "…\dots" are missing). Argue from the factorisation why the model cannot directly answer this without prefix-suffix tricks.


References

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

    ↩