All courses

The next-token cross-entropy objective

Write 𝓛 = −(1/T) Σ log p_θ(x_{t+1} | x_{≤t}) and explain it as maximum likelihood over a corpus. State the loss of a uniform guess, log V, as a reference point.

Builds on: Language modeling as next-token prediction, Maximum likelihood as cross-entropy minimization, Softmax, logits and the log-sum-exp trick, What training does

▶ Watch this lesson Start the whole course

What the animation says

Only the true token counts

At every position, the model spreads probability over its whole vocabulary. But the text gives us just one answer: the token that really came next. So we look up only that token's probability, and turn it into a penalty: minus its log. Confident and right costs almost nothing. Hedging costs a little. Confident and wrong costs without limit. Here are three predictions. Tap the one that pays the biggest penalty.

Many penalties, one average

Penalties from every position now need to become one number. A whole text's probability is the product of its per-token probabilities. The log of a product is a sum of logs. So the summed penalties are exactly minus the log of the whole text's probability. Divide by the number of positions. That average is the loss. Pushing the loss down pushes the corpus's probability up. That is maximum likelihood.

Worked: the cat sat .

Take a four-token vocabulary and one sentence: the cat sat, full stop. After 'the', the model gave 'cat' one half. Penalty: zero point six nine three. After 'the cat', it gave 'sat' a quarter. Penalty: one point three eight six. After 'the cat sat', the full stop got zero point eight. Penalty: zero point two two three. The penalties add up to two point three zero two nats. So what is the loss?

Compared with a blind guess

It's the average: two point three zero two divided by three, which is zero point seven six seven nats. Is that good? Compare a model that knows nothing and gives every token one quarter. Then each position costs the log of four, one point three eight six. Every term is the same. Averaging equal terms gives that same term, however long the text. A blind guess scores the log of the vocabulary size. Our model sits well below it. It has learned something.

From logits, computed stably

Real models hand us raw scores called logits: one row per position, one column per token. The true next tokens are marked: column one, then two, then three. This line subtracts each row's largest score before exponentiating, so big scores can't overflow. Out come log-probabilities. This last line picks each true token's log-probability and averages the negatives. That gives about zero point seven seven four, against one point three eight six for guessing. Which position costs the most? Tap its row.

What to remember

So the loss is the average surprise at the token that really came next. Minimizing it is maximum likelihood on the corpus. The line to beat is the log of the vocabulary size. For fifty thousand tokens, that's about ten point eight nats. The floor is the entropy of the text itself. Averaged over real text, no model's loss can go below it.

One number to score every prediction

At every position, the model outputs a full distribution over $V$ tokens. The corpus supplies only the single token that actually came next. Training needs **one number** to push down, summarizing trillions of such predictions. It must reward the model exactly when its probabilities match how real text behaves. What is that number, and how good or bad is a given value?

Average surprise at what actually came

At each position, look up the probability the model gave to the **actual** next token. Take its surprisal, $-\log p$, then average over all positions. - Confident and right: $p\approx1$, penalty $\approx 0$. - Hedging: a moderate penalty. - Confident and wrong: $p\to 0$, penalty $\to\infty$. The text's total probability is the product of these per-token probabilities. The log of a product is a sum of logs, so the summed surprisal is exactly $-\log$ of the whole text's probability. Lowering the average loss therefore raises the probability of the whole corpus.

The objective and why it is maximum likelihood

For tokens $x_1\ldots x_{T+1}$, positions $t=1\ldots T$ each have a next token: $$\mathcal L(\theta)=-\frac1T\sum_{t=1}^{T}\log p_\theta(x_{t+1}\mid x_{\le t})$$ Here $\theta$ is everything the model learns, and $p_\theta=\text{softmax}(z_t)$. By the chain rule, $-T\mathcal L=\log p_\theta(x_2\ldots x_{T+1}\mid x_1)$, so minimizing $\mathcal L$ is maximum likelihood. For a corpus of many documents, average over all their positions. The log-probabilities of the documents add, so the same argument holds. Each term is the cross-entropy from a one-hot target. A uniform guess ($p=1/V$) gives $\mathcal L=\log V$.

Four-token vocabulary, one sentence

$V=4$, text: *the cat sat .* Probabilities the model gave to each actual next token: - $p(\text{cat}\mid\text{the})=0.5$: $-\ln0.5=0.693$ - $p(\text{sat}\mid\text{the cat})=0.25$: $1.386$ - $p(.\mid\text{the cat sat})=0.8$: $0.223$ Sum $=2.302$. Then $\mathcal L=2.302/3=0.767$ nats. Uniform guess: $\ln4=1.386$. This model beats it.

Loss from logits, computed stably

Use logits `z` of shape [T, V] and the actual next tokens `y`. Take a log-softmax with the max subtracted, pick each true token's log-probability, and average the negatives. The three positions cost about 1.449, 0.622 and 0.250 nats. Compare their mean with $\log V$.
import numpy as np
V = 4
z = np.array([[2.0, 1.0, 0.1, -1.0],
              [0.5, 0.2, 1.5, 0.0],
              [0.0, 0.3, 0.1, 2.5]])  # logits z_t, [T, V]
y = np.array([1, 2, 3])                 # actual x_{t+1}
m = z.max(axis=1, keepdims=True)
logp = z - m - np.log(np.exp(z - m).sum(axis=1, keepdims=True))
loss = -logp[np.arange(len(y)), y].mean()
print(loss, np.log(V))  # ~0.774 vs ~1.386 (uniform guess)

What to remember

$\mathcal L$ is the average surprisal of the true next token. Minimizing it is maximum likelihood on the corpus. The reference point is $\log V$, the loss of a uniform guess (about 10.8 nats for $V=50{,}000$). A useful model must get below it. The floor is the entropy of the process that generates the text. Averaged over that process, no model's loss can go below it.

On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.