The language-modelling objective¶
Every large language model is trained, first and mostly, to do one thing: assign a probability to the next token. This page derives that objective from scratch, shows why cross-entropy is the only sensible loss for it, and explains why "just predicting the next word" turns out to be a general-purpose learning signal.
10,000 ft
Pre-training is self-supervised: the text supplies its own labels, because every token is the answer to "what comes next?" for the tokens before it. That one trick removed the bottleneck that had limited supervised learning (human labels) and let models learn from trillions of tokens of raw text. The objective sits between tokenisation, which decides what a "token" is, and the transformer, which is merely the function that turns a prefix into a distribution. Everything downstream depends on it: scaling laws are laws about this loss, decoding is how you draw text from the distribution it learns, and post-training starts from a model it produced.
2,000 ft
Write the probability of a whole sequence as a product of next-token probabilities (the chain rule). Train a network to output, at every position, a distribution over the vocabulary. Score it by the negative log-probability it gave to the token that actually came next, averaged over all positions. Minimising that average is maximum-likelihood estimation, which is the same as minimising the KL divergence from the true distribution of text to the model, which is the same as making the model a good compressor of text.
- Factorise: \(p(x_1,\dots,x_T)=\prod_t p(x_t\mid x_{<t})\). No assumption is made; this is just probability.
- Predict in parallel: a causal mask lets one forward pass produce all \(T\) conditional distributions at once.
- Score: the loss at position \(t\) is \(-\log p_\theta(x_{t+1}\mid x_{\le t})\); average it.
- Read the number: loss in nats per token; \(e^{\text{loss}}\) is perplexity; divide by \(\ln 2\) for bits.
- Know the floor: the loss can never go below the entropy of text itself; what sits above that floor is the model's KL gap.
Ground level¶
The chain rule turns "model language" into "predict the next token"¶
A language model is a probability distribution over sequences of tokens. Sequences are an astronomically large space (a 1,000-token document over a 50,000-token vocabulary has \(50{,}000^{1000}\) possibilities), so nobody models \(p(x_1,\dots,x_T)\) directly. Instead we use the chain rule of probability, which holds for any joint distribution:
This is the whole trick. A hard problem (a distribution over \(V^T\) objects) becomes \(T\) easy-looking problems, each a distribution over just \(V\) objects: given everything so far, which token comes next? A classifier with \(V\) classes can answer that. A model that answers it well for every prefix is a model of the joint distribution, with nothing lost.
Two things make this the right factorisation for text, though not the only valid one:
- Generation is trivial. To sample a sequence, sample \(x_1\), feed it back, sample \(x_2\), and so on. This is ancestral sampling, and it produces exact samples from the model's joint distribution. Decoding is all about how you choose at each step.
- Likelihood is exact. You can compute \(\log p(\text{document})\) exactly by summing per-token log-probabilities. Compare VAEs or diffusion models, where the likelihood is only bounded (see Generative modelling).
Shannon's guessing game
In 1951 Claude Shannon measured the information content of English by asking people to guess a text letter by letter and counting their guesses. Using statistics over eight letters he got about 2.3 bits per letter; with human readers using long-range context, the estimate fell to roughly one bit per letter (Shannon, 1951). A language model plays exactly this game, with a probability for every possible guess instead of a single one. Seventy-five years later, the loss curves of frontier models are still a measurement of how well a machine plays Shannon's game.
What the network actually outputs¶
At every position \(t\) the network produces a vector of \(V\) real numbers, the logits \(\mathbf{z}_t\in\mathbb{R}^V\). A softmax turns them into a distribution:
For a batch of \(B\) sequences of length \(T\), the logits tensor has shape \((B, T, V)\). For GPT-2 small (\(V = 50{,}257\)) with \(B=8\), \(T=1024\), that is 412 million numbers per step, which is why the final projection and the softmax are among the most memory-hungry parts of training.
The targets are the same token ids shifted left by one. If the input row is
[The, cat, sat, on, the], the target row is [cat, sat, on, the, mat]. Position 0 is trained to
predict "cat" from "The"; position 4 is trained to predict "mat" from all five tokens. A
causal mask inside attention guarantees that position \(t\) cannot look at
positions after \(t\), so all \(T\) predictions are honest and come out of one forward pass. A
sequence of length 1,024 therefore yields 1,024 training examples for the price of one, which is a
large part of why decoder-only pre-training is so efficient.
A worked example: scoring one sentence¶
Suppose a model reads "The cat sat on the mat" as six tokens and assigns these probabilities to the token that actually came next at each step (the first one conditioned on a beginning-of-text token):
| step | context | true next token | \(p_\theta\) | \(-\ln p_\theta\) (nats) |
|---|---|---|---|---|
| 1 | ⟨bos⟩ | The | 0.05 | 2.996 |
| 2 | The | cat | 0.01 | 4.605 |
| 3 | The cat | sat | 0.20 | 1.609 |
| 4 | The cat sat | on | 0.60 | 0.511 |
| 5 | The cat sat on | the | 0.70 | 0.357 |
| 6 | The cat sat on the | mat | 0.30 | 1.204 |
The sum is 11.282 nats, so \(p_\theta(\text{sentence}) = e^{-11.282}\approx 1.3\times10^{-5}\). The mean loss is \(11.282/6 = 1.880\) nats per token. Three things to read off:
- "cat" dominates the loss. One surprising token (probability 0.01) costs 4.6 nats, more than the four easy tokens together. Log-loss punishes confident mistakes and rewards hedging, which is what you want from a predictor that will be sampled from later.
- Perplexity is \(e^{1.880}=6.56\). Read it as: on average the model was as uncertain as if it were choosing uniformly among 6.56 tokens.
- Bits per token is \(1.880/\ln 2 = 2.713\). An ideal entropy coder driven by this model would spend 2.713 bits per token, about 16.3 bits for the sentence.
Units: nats, bits, perplexity and bits per byte¶
The same loss shows up in four guises, and papers switch between them without warning.
| quantity | formula | used by |
|---|---|---|
| loss (nats/token) | \(\mathcal{L}=-\frac1N\sum\ln p_\theta(x_t\mid x_{<t})\) | PyTorch cross_entropy, training curves |
| bits/token | \(\mathcal{L}/\ln 2\) | information theory, compression |
| perplexity | \(e^{\mathcal{L}}\) (equivalently \(2^{\text{bits}}\)) | older NLP, WikiText benchmarks |
| bits per byte (BPB) | \(\frac{N_\text{tokens}}{N_\text{bytes}}\cdot\frac{\mathcal{L}}{\ln 2}\) | comparing models with different tokenisers |
Bits per byte matters because per-token loss is not comparable across tokenisers. A tokeniser with bigger tokens packs more text into each prediction, so its per-token loss is higher even if the model is better. Normalising by bytes of raw text fixes that: a model with loss 3.0 nats/token whose tokeniser averages 4.2 bytes/token achieves \(3.0/(0.693\times4.2)=1.03\) bits per byte. The Pile and Chinchilla papers report bits per byte for exactly this reason. For scale: Chinchilla reached a WikiText-103 perplexity of 7.16 against Gopher's 7.75 (Hoffmann et al., 2022), i.e. 1.969 versus 2.048 nats per token on the same tokeniser.
Loss at initialisation is a free sanity check
A freshly initialised model with small output weights predicts nearly uniformly, so its loss should be about \(\ln V\): 4.17 for a 65-character vocabulary, 10.82 for GPT-2's 50,257 tokens. If your first logged loss is 30, your initialisation is producing over-confident logits. If it is exactly \(\ln V\) and never moves, your targets are probably misaligned with your inputs.
From counting to neural networks¶
The objective is older than neural networks. An n-gram model assumes \(p(x_t\mid x_{<t})\approx p(x_t\mid x_{t-n+1},\dots,x_{t-1})\) and estimates it by counting. Counting is maximum likelihood for that model family, so n-grams minimise exactly the same cross-entropy; they just have a crippled function class. On Tiny Shakespeare (65 characters), the code in Build it gives these held-out losses:
| model | val loss (nats/char) | perplexity | bits/char |
|---|---|---|---|
| uniform | 4.174 | 65.00 | 6.022 |
| unigram | 3.347 | 28.43 | 4.829 |
| bigram | 2.484 | 11.99 | 3.583 |
| trigram | 2.046 | 7.74 | 2.951 |
| 4-gram | 1.784 | 5.95 | 2.574 |
Each extra character of context buys less, and the count table grows as \(V^n\) (\(65^4\approx 1.8\) million cells already, most of them never seen). Two problems kill n-grams at scale: sparsity (most long contexts never occur, so you need smoothing tricks) and no generalisation ("the cat sat" teaches nothing about "the dog sat").
Bengio et al. (2003) fixed the second problem by learning an embedding for each word and predicting the next word with a neural network over the concatenated embeddings of the previous few words. Similar words get similar vectors, so evidence is shared. Recurrent networks removed the fixed window (RNNs and LSTMs); transformers removed the sequential bottleneck and made every past position directly reachable through attention. The objective never changed. A 2026 frontier model and a 1990s trigram model minimise the same number; what changed is the function class, the data and the compute.
The family of objectives¶
"Predict the missing text" has several variants. They differ in which tokens are hidden and what the model may look at.
- Causal (autoregressive) LM: the GPT family (Radford et al., 2018; 2019; Brown et al., 2020). Every token is a target, it gives an exact likelihood, and the trained model can generate. This won.
- Masked LM: BERT (Devlin et al., 2018) hides about 15% of tokens and predicts them from both sides. Bidirectional context makes better representations for classification, but only the hidden 15% produce a learning signal, and the model is not a generator. It remains the right tool for embedding and retrieval encoders (Embeddings and vector search).
- Span corruption: T5 (Raffel et al., 2019) replaces spans with sentinel tokens and has an encoder-decoder reconstruct them.
- Fill-in-the-middle (FIM): cut a document into prefix, middle and suffix, then train on
prefix + suffix + middlewith ordinary next-token prediction. Bavarian et al. (2022) showed that training on a 50% FIM mixture teaches infilling without hurting left-to-right ability (their "FIM-for-free" property). It is why code assistants can complete the middle of a file. - Multi-token prediction: Gloeckle et al. (2024) attach \(n\) output heads to a shared trunk, each predicting a token further ahead, and report better sample efficiency, especially for code and larger models. The extra heads can also be used to draft tokens for faster decoding.
Note that FIM and multi-token prediction are still built from next-token cross-entropy. The causal objective is the trunk; the others are re-orderings or auxiliary terms.
Why next-token prediction is such a general signal¶
It looks like a narrow task. It is not, for a reason that is worth stating precisely: to lower the loss on a token you must model whatever process produced that token. Predicting the next token of a chess game in algebraic notation rewards knowing the rules; predicting the next line of a proof rewards following the argument; predicting what a character says next rewards modelling the character. The loss is a single number, but the data contains every task humans write down, so minimising it pushes the model to learn many skills at once. GPT-2's paper title, "Language Models are Unsupervised Multitask Learners", is this argument in six words.
There are two precise ways to say this.
Prediction is compression. By Shannon's source-coding theorem, a model that assigns probability \(p\) to a token can be turned (by arithmetic coding) into a code that spends \(-\log_2 p\) bits on it, to within two bits for the whole message. So a model's cross-entropy is the size of the file it could compress your data into. Delétang et al. (2023) took this literally: Chinchilla 70B, used as an arithmetic coder, compressed ImageNet patches to 43.4% and LibriSpeech audio to 16.4% of raw size, beating PNG (58.5%) and FLAC (30.3%), although it was trained only on text. Lowering the loss means finding regularities, and regularities are knowledge.
Maximum likelihood is KL minimisation. Derived below: minimising expected cross-entropy against the data is the same as minimising \(D_\text{KL}(p_\text{data}\,\|\,p_\theta)\). The only way to reach the floor is to match the data distribution everywhere it has mass.
Teacher forcing and exposure bias¶
During training, every position is conditioned on the true prefix, never on the model's own earlier predictions. This is called teacher forcing, and it is what makes the parallel, one-pass training possible. At generation time, however, the model conditions on its own samples. If it makes an unusual choice early, it is now in a prefix that looks unlike anything it was trained on. This mismatch is called exposure bias. In practice, large models trained on enough data are surprisingly robust to it, and the remaining symptoms (repetition loops, drift in long generations) are mostly handled at decoding time and in post-training with methods that train on the model's own samples.
First principles¶
Why the log, and why nothing else¶
Suppose you want a loss \(\ell(q, x)\) that scores a predicted distribution \(q\) when outcome \(x\) happens. Ask for three properties:
- Proper: if the truth is \(p\), the expected loss \(\mathbb{E}_{x\sim p}[\ell(q,x)]\) is minimised only at \(q=p\). You want the model rewarded for reporting its real beliefs, not for exaggerating.
- Local: the loss depends only on the probability given to the outcome that happened, \(\ell(q,x)=f(q_x)\), not on how the rest of the mass was spread.
- Additive over independent pieces: predicting two things in sequence should cost the sum of the two costs, which is what lets a document's loss be a sum over tokens.
For more than two outcomes, the logarithmic score \(-\log q_x\) is the only smooth score that is both proper and local (up to an affine change). Additivity follows because \(\log\) turns the chain-rule product into a sum. Accuracy is not proper (it ignores confidence); squared error on probabilities (the Brier score) is proper but not local. So cross-entropy is not a convention: given these three wishes it is forced.
Why minimising it learns the distribution¶
Three equivalent statements, each useful at a different moment:
- Maximum likelihood: choose \(\theta\) to maximise the probability of the training corpus.
- Cross-entropy minimisation: minimise \(H(p_\text{data}, p_\theta)\), the average code length of data under the model's code.
- KL minimisation: minimise \(D_\text{KL}(p_\text{data}\,\|\,p_\theta)\), because \(H(p_\text{data},p_\theta) = H(p_\text{data}) + D_\text{KL}(p_\text{data}\,\|\,p_\theta)\) and the first term does not depend on \(\theta\).
The direction of the KL matters. \(D_\text{KL}(p_\text{data}\,\|\,p_\theta)\) is huge wherever data has mass and the model has almost none, so the model is pushed to cover every mode of the data, including rare ones. It is not punished much for putting a little mass where real text never goes. This "mass-covering" behaviour is why a raw pre-trained model will happily produce low-quality text when sampled naively, and why decoding truncates the tail. You can watch both KL directions disagree in the figure below.
What breaks if you change it¶
- Drop the softmax normalisation and the model can lower the loss by inflating every logit. Normalising is what makes probabilities compete: raising one token's probability must lower others.
- Train on accuracy-like targets (e.g. only reward the arg-max) and you lose calibration and the ability to sample sensibly.
- Let positions see the future (forget the mask) and the loss collapses towards zero on the training set because the model copies the answer. The model learns nothing usable; a training loss that drops implausibly fast is the classic sign of a leaking mask.
- Average per document instead of per token and long documents are under-weighted. Most pre-training code averages over all target tokens in the batch, which weights every token equally.
The maths¶
Setup and shapes¶
| symbol | meaning | shape |
|---|---|---|
| \(x_{1:T}\) | token ids of one sequence | \((T,)\) integers in \([0, V)\) |
| \(\mathbf{z}_t\) | logits at position \(t\) | \((V,)\); batch tensor \((B,T,V)\) |
| \(\mathbf{p}_t=\operatorname{softmax}(\mathbf{z}_t)\) | predicted distribution for \(x_{t+1}\) | \((V,)\) |
| \(\mathbf{y}_t\) | one-hot vector of the true \(x_{t+1}\) | \((V,)\) |
| \(N\) | number of target tokens averaged over | \(B(T-1)\) (or \(BT\) with a shifted window) |
The training loss for a batch is
Derivation: maximum likelihood = cross-entropy = KL + entropy
Let the corpus be \(N\) draws from the true conditional distributions. Maximum likelihood chooses
where \(c_i\) is the context of the \(i\)-th target. The log is monotone, so the arg max is unchanged, and dividing by \(N\) changes nothing either. By the law of large numbers the average converges to an expectation:
Add and subtract \(\log p_\text{data}(x\mid c)\) inside the expectation:
Gibbs' inequality says \(D_\text{KL}\ge 0\) with equality iff the two distributions are equal, so the loss is bounded below by the conditional entropy of text and reaches it exactly when the model matches the data. In the snippet below, a true distribution \((0.5, 0.25, 0.125, 0.125)\) and a model \((0.4, 0.4, 0.1, 0.1)\) give \(H = 1.7500\) bits, \(D_\text{KL} = 0.0719\) bits and cross-entropy \(1.8219\) bits, which is their sum.
Derivation: the gradient of softmax cross-entropy is p − y
Drop the position index. With \(\mathbf{p}=\operatorname{softmax}(\mathbf{z})\) and true class \(k\), the loss is \(\ell = -\log p_k = -z_k + \log\sum_u e^{z_u}\). Differentiate with respect to logit \(z_j\):
So \(\nabla_{\mathbf{z}}\ell = \mathbf{p}-\mathbf{y}\). Read it: the gradient pushes up the logit of the correct token by \(1-p_k\) and pushes down every other logit by its own probability. Its entries sum to zero (shifting all logits by a constant changes nothing). Once the model gives the right token probability 1, the gradient vanishes. Averaged over \(N\) targets, each row is divided by \(N\). This is the error signal that backpropagation sends into the whole network, and it is checked numerically in Build it.
Perplexity and its geometric-mean reading¶
Perplexity is the reciprocal of the geometric mean probability the model gave to the right answers. A uniform model over \(V\) tokens has perplexity exactly \(V\); a perfect model has perplexity 1. In the worked example the geometric mean of \((0.05, 0.01, 0.20, 0.60, 0.70, 0.30)\) is \(1/6.56 = 0.152\).
Bits per byte¶
If a text of \(N_\text{bytes}\) bytes tokenises into \(N_\text{tok}\) tokens and the loss is \(\mathcal{L}\) nats per token, the total code length is \(N_\text{tok}\mathcal{L}/\ln 2\) bits, so
The tokeniser's compression ratio \(N_\text{bytes}/N_\text{tok}\) cancels out the advantage of long tokens, so BPB compares a character model, a BPE model and a byte model fairly.
Numerical stability: never compute softmax and then log¶
\(\log\operatorname{softmax}(\mathbf{z})_k = z_k - \log\sum_u e^{z_u}\). Computing \(e^{z_u}\) directly
overflows for \(z_u > 88\) in float32. Subtract \(m=\max_u z_u\) first:
\(\log\sum_u e^{z_u} = m + \log\sum_u e^{z_u-m}\), which is exact and safe because every exponent is
now \(\le 0\). This is the log-sum-exp trick (floating point and log-sum-exp).
Frameworks fuse it into cross_entropy(logits, targets); call that, not log(softmax(...)).
Build it¶
Two NumPy programs. Both run in well under a second.
1. n-gram language models are compressors. Train unigram to 4-gram character models on Tiny
Shakespeare by counting, score the held-out 10%, and compare with general-purpose compressors.
Download the text first: curl -O https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt.
import numpy as np, gzip, bz2, lzma
text = open("input.txt").read()
chars = sorted(set(text)); V = len(chars)
stoi = {c: i for i, c in enumerate(chars)}
ids = np.array([stoi[c] for c in text])
n = int(0.9 * len(ids)); train, val = ids[:n], ids[n:]
def ngram_nll(order, k=0.1):
"""Average -ln p(x_t | previous order-1 chars), add-k smoothing."""
ctx = order - 1
counts = np.zeros((V,) * order)
np.add.at(counts, tuple(train[i:len(train) - ctx + i] for i in range(order)), 1)
probs = (counts + k) / (counts + k).sum(axis=-1, keepdims=True)
p = probs[tuple(val[i:len(val) - ctx + i] for i in range(order))]
return -np.log(p).mean()
print(f"vocab V = {V}; uniform model: {np.log(V):.3f} nats/char")
for order, name in [(1, "unigram"), (2, "bigram"), (3, "trigram"), (4, "4-gram")]:
nll = ngram_nll(order)
print(f"{name:8s} val NLL {nll:.3f} nats ppl {np.exp(nll):6.2f} {nll/np.log(2):.3f} bits/char")
raw = text[n:].encode()
for name, f in [("gzip", gzip.compress), ("bz2", bz2.compress), ("lzma", lzma.compress)]:
print(f"{name:5s} {8 * len(f(raw)) / len(raw):.3f} bits/char")
vocab V = 65; uniform model: 4.174 nats/char
unigram val NLL 3.347 nats ppl 28.43 4.829 bits/char
bigram val NLL 2.484 nats ppl 11.99 3.583 bits/char
trigram val NLL 2.046 nats ppl 7.74 2.951 bits/char
4-gram val NLL 1.784 nats ppl 5.95 2.574 bits/char
gzip 3.191 bits/char
bz2 2.635 bits/char
lzma 2.943 bits/char
The 4-gram model's cross-entropy (2.574 bits/char) is a smaller code than bz2 manages on the same text. The comparison flatters the model a little, because it learned its statistics from the other 90% of the file while the compressors start cold, but that is exactly the point: a language model is a compressor with a learned prior. A small transformer (Build a GPT from scratch) pushes this to about 1.47 nats (2.1 bits) per character: that is the best validation loss nanoGPT's README reports for its small character model.
2. Cross-entropy, its gradient, and the entropy floor.
import numpy as np
rng = np.random.default_rng(0)
def log_softmax(z):
z = z - z.max(axis=-1, keepdims=True) # stability: shift by the max
return z - np.log(np.exp(z).sum(axis=-1, keepdims=True))
def cross_entropy(logits, targets): # logits (B,T,V), targets (B,T)
lp = log_softmax(logits)
return -np.take_along_axis(lp, targets[..., None], axis=-1).mean()
B, T, V = 2, 3, 5
logits = rng.normal(size=(B, T, V)); targets = rng.integers(0, V, size=(B, T))
loss = cross_entropy(logits, targets)
# analytic gradient: (softmax - onehot) / (B*T)
p = np.exp(log_softmax(logits))
grad = (p - np.eye(V)[targets]) / (B * T)
# finite-difference check on every logit
num = np.zeros_like(logits); eps = 1e-6
for idx in np.ndindex(*logits.shape):
d = np.zeros_like(logits); d[idx] = eps
num[idx] = (cross_entropy(logits + d, targets) - cross_entropy(logits - d, targets)) / (2 * eps)
print(f"loss {loss:.4f} max |analytic - numeric| = {np.abs(grad - num).max():.2e}")
print(f"largest |row sum| of the gradient: {np.abs(grad.sum(-1)).max():.1e}")
# cross-entropy = entropy + KL
p_data = np.array([0.5, 0.25, 0.125, 0.125]); q = np.array([0.4, 0.4, 0.1, 0.1])
H = -(p_data * np.log2(p_data)).sum(); CE = -(p_data * np.log2(q)).sum()
KL = (p_data * np.log2(p_data / q)).sum()
print(f"H(p) = {H:.4f} bits, CE(p,q) = {CE:.4f} bits, KL(p||q) = {KL:.4f} bits, H+KL = {H+KL:.4f}")
print(f"GPT-2 vocab 50257: loss at a uniform init = ln V = {np.log(50257):.3f} nats")
loss 1.8776 max |analytic - numeric| = 2.71e-10
largest |row sum| of the gradient: 4.9e-17
H(p) = 1.7500 bits, CE(p,q) = 1.8219 bits, KL(p||q) = 0.0719 bits, H+KL = 1.8219
GPT-2 vocab 50257: loss at a uniform init = ln V = 10.825 nats
Things to try
- Change the smoothing
kfrom 0.1 to 1.0 and to 0.001. Which order suffers most, and why does the 4-gram need less smoothing mass per cell than you might expect? - Add a 5-gram with a dictionary of counts instead of a dense \(65^5\) array. Does validation loss keep falling, or does sparsity win?
- Interpolate the bigram and trigram (\(\lambda p_3 + (1-\lambda)p_2\)) and tune \(\lambda\) on validation data. This is the simplest form of the smoothing that kept n-grams competitive until about 2010.
- In the second program, set one logit to 1000 and compute the loss with a naive
np.log(np.exp(z)/np.exp(z).sum()). Then explain why the stable version survives. - Compute bits per byte for the bigram model. Characters here are ASCII, so it should equal bits per character; check why.
Common misconceptions¶
\"It only predicts the next word, so it cannot plan\"
The objective is local, but the function that minimises it is not. To put high probability on the next token of a rhyming couplet, a well-trained model benefits from representing where the line is going. "Trained on next-token prediction" says what is scored, not what is computed inside. Interpretability work on planning inside models is covered in Mechanistic interpretability.
\"Lower perplexity always means a better model\"
Only on the same tokeniser and the same evaluation text. Across tokenisers, compare bits per byte. And loss is not usefulness: post-training can raise perplexity on raw web text while making the model far more helpful, because the target distribution has changed on purpose.
\"Loss near zero would be ideal\"
Not on held-out text. Language has genuine uncertainty (the entropy floor). A model whose loss on new text heads towards zero is almost certainly being evaluated on text it memorised. See Contamination.
Check yourself¶
Write the loss for one sequence of length T in terms of logits, and give its tensor shapes.
\(\mathcal{L} = -\frac{1}{T-1}\sum_{t=1}^{T-1}\left(z_{t,x_{t+1}} - \log\sum_v e^{z_{t,v}}\right)\).
Logits are \((T, V)\) (or \((B,T,V)\) batched); targets are the input ids shifted left by one, shape
\((T-1,)\) or \((B, T-1)\). In code you usually feed x[:, :-1] and use x[:, 1:] as targets.
A model reports a loss of 2.3 nats/token. What are its perplexity and bits/token? If its tokeniser averages 4 bytes per token, what is its bits per byte?
Perplexity \(e^{2.3}\approx 9.97\). Bits per token \(2.3/0.693\approx 3.32\). Bits per byte \(3.32/4 \approx 0.83\).
Why does the gradient with respect to the logits sum to zero, and what does that tell you about the softmax?
Because \(\sum_j (p_j - y_j) = 1 - 1 = 0\). The softmax is invariant to adding the same constant to every logit, so there can be no gradient along the all-ones direction. Only differences between logits matter.
Why is per-token loss not comparable between a model with a 32k vocabulary and one with a 256k vocabulary?
The larger vocabulary usually has longer tokens, so each prediction covers more text and is harder; per-token loss rises even if the model compresses text better. Normalise to bits per byte (or per character) on the same raw text to compare.
Which KL direction does maximum-likelihood training minimise, and what behaviour does that produce?
\(D_\text{KL}(p_\text{data}\,\|\,p_\theta)\), the forward or "mass-covering" direction. The model is heavily penalised for giving near-zero probability to anything that occurs in data, so it spreads mass to cover every mode, including some implausible continuations. That tail is why naive sampling produces junk and why top-p and min-p truncation exist.
Masked LM gets to see both sides of the gap. Why did causal LM, which sees only the left, win for large generative models?
Three reasons. Every token is a target in causal LM (versus about 15% in BERT), so each forward pass yields more learning signal. It defines an exact joint likelihood and can generate by ancestral sampling, so one model both scores and writes. And in-context learning, where a task is specified in the prompt and the answer is the continuation, falls out of the causal setup naturally.
Hard: a model trained with teacher forcing gets 1.5 nats/token on validation, but its own samples look worse than that number suggests. Give two reasons.
(1) Exposure bias: at generation time it conditions on its own samples, drifting into prefixes unlike the training data, which validation loss never measures. (2) Forward KL makes the model mass-covering: it keeps small probability on many bad continuations, and pure sampling picks some of them; a sequence of 500 tokens gives the tail 500 chances. Validation loss measures average log probability on real text, not the quality of the model's most likely or typical outputs.
Hard: the n-gram table above beats bz2 at compressing Shakespeare. Is that a fair fight? What would make it fair?
Not quite: the model's counts came from the other 90% of the same play collection, which is a learned prior the compressor lacks. A fair comparison counts the cost of transmitting the model (its parameters) plus the data, or gives the compressor the same training text as a preset dictionary. This "model size plus code length" view is the minimum description length principle, and it is why Delétang et al. report both a raw compression rate and an adjusted one that adds the model's size in bytes.
Go deeper¶
Papers
- Prediction and Entropy of Printed English — Shannon, 1951. The guessing game that defined the problem; read sections 1–3 and the figure of entropy against context length.
- A Neural Probabilistic Language Model — Bengio, Ducharme, Vincent, Jauvin, 2003 (JMLR). The first neural LM with learned word vectors; section 1 states the curse-of-dimensionality argument better than anyone since.
- Improving Language Understanding by Generative Pre-Training — Radford et al., 2018 (GPT-1). Causal LM pre-training plus fine-tuning; section 3.1 is the objective in one equation.
- Language Models are Unsupervised Multitask Learners — Radford et al., 2019 (GPT-2). The argument that next-token prediction on diverse text implies multitask learning.
- BERT — Devlin et al., 2018. The masked-LM alternative; read section 3.1 for the 15% masking recipe and why it uses [MASK]/random/unchanged.
- Efficient Training of Language Models to Fill in the Middle — Bavarian et al., 2022. How a pure reordering gives causal models infilling for free.
- Better & Faster Large Language Models via Multi-token Prediction — Gloeckle et al., 2024. The cleanest modern challenge to plain next-token loss.
- Language Modeling Is Compression — Delétang et al., 2023. Prediction-as-compression made concrete with arithmetic coding; the tables on image and audio are startling.
Videos and lectures
- The spelled-out intro to language modeling: building makemore — Andrej Karpathy. A bigram model built by counting, then as a neural net, with the loss explained from scratch. The best hour to spend after this page.
- Transformers, the tech behind LLMs — 3Blue1Brown, Deep Learning chapter 5. The visual version of "predict the next token, repeatedly".
Articles and books
- Speech and Language Processing, 3rd ed. draft — Jurafsky and Martin. The n-gram chapter is the definitive treatment of perplexity, smoothing and evaluation.
- The Illustrated GPT-2 — Jay Alammar. How the causal objective looks inside a decoder-only stack.
Courses and code
- Stanford CS336: Language Modeling from Scratch — Hashimoto and Liang. Builds the full pipeline, objective to training to data, with assignments.
- karpathy/nanoGPT —
model.pycomputes this loss in one line:F.cross_entropy(logits.view(-1, V), targets.view(-1)).
Where this leads¶
- Pre-training data — the objective is only as good as the text it is averaged over.
- Scaling laws — how this loss falls with parameters, data and compute, and the entropy floor \(E\).
- Build a GPT from scratch — minimise this objective with a real transformer and watch the loss go below the n-gram baselines.
- Decoding: greedy, beam, temperature, top-k, top-p — how to turn the learned distribution back into text.
- Information theory — entropy, cross-entropy and KL in full.