The training objective

A language model is trained on one task: predict the next token. Shift the text one place to get the answers, and score every position at once by the negative log of the probability the model gave the right token. Average, and that is the loss.

Key idea
targets = inputs shifted by one; loss = average of −log p(correct next token) over every position; perplexity = e^loss
Real world
A guessing game with a book: cover everything after a word, guess the next word, uncover it, score yourself, and move on one word. A good reader rarely gets a nasty surprise.
In an LLM
On “The cat sat on the mat because it was tired.”, GPT-2 small gives the real next token an average loss of 3.88: it is about as unsure as if it were choosing between 48 equally likely tokens at each step.

Free labels

Most machine learning needs labelled examples: photos tagged “cat”, emails tagged “spam”. Language models don’t. Any text already contains its own answers, because the label for each position is simply the token that comes next.

Take a sentence of TT tokens. The inputs are tokens 1 to T−1T-1; the targets are tokens 2 to TT, the same text shifted one place left. At position tt the model sees tokens 1…t1 \ldots t and must predict token t+1t+1.

Score every position at once

At each position the model outputs a probability for every token in the vocabulary (the unembedding). The loss at that position is

ℓt=−log⁡pθ(xt+1∣x1,…,xt)\ell_t = -\log p_\theta(x_{t+1} \mid x_1, \ldots, x_t)

the negative log of the probability it gave the token that actually came next. The loss for the sequence is the average over positions:

L=1T−1∑t=1T−1−log⁡pθ(xt+1∣x≤t)\mathcal{L} = \frac{1}{T-1} \sum_{t=1}^{T-1} -\log p_\theta(x_{t+1} \mid x_{\le t})

This is the cross-entropy between the real next token and the model’s prediction. Here it is on real sentences, with GPT-2 small’s real probabilities:

Loading GPT-2 data…
Next-token loss on a real sentence.

Thanks to the causal mask, position tt can only see tokens up to tt, so one forward pass produces a prediction at every position, each one honest about the future. A training batch of 1,024 tokens is 1,023 prediction problems solved in one go. That is a big reason transformers train so efficiently.

Teacher forcing

Look at the “GPT-2 guess” row. After “The cat sat on the”, GPT-2’s top guess is “ floor”, not “ mat”. During training that doesn’t matter: the next input is still the real “ mat”. Every position gets the true history, never the model’s own guesses. This is .

It is what makes parallel training possible (no position has to wait for an earlier guess), and it keeps one early mistake from derailing the rest of the sequence. The price is a mismatch: at generation time the model does read its own guesses, which it never practised. In practice large models cope well.

example · the book guessing game

Cover a page of a novel with a card. Uncover one word at a time and, before each, write down your guess for the next word along with how confident you are. Score yourself −log(the confidence you gave the real word). “Once upon a” → “time”: you said 95%, cost 0.05. A character’s name you had never seen: you said 0.1%, cost 6.9. Whatever you guessed, you always uncover the real word and carry on from there: that is teacher forcing.

example · one GPT-2 sentence

In “The cat sat on the mat because it was tired.”, GPT-2 small gives “ on” after “The cat sat” a 22% chance (loss 1.50) and “ the” after “sat on” 45% (loss 0.79). The first prediction, “ cat” after just “The”, gets 0.01% (loss 9.20): nobody could guess that. The average over all ten positions is 3.88.

Why −log p

The loss must reward putting probability on the right answer, and it must be something we can add up over positions. The negative log does both:

  • Certain and right costs nothing: −log⁡1=0-\log 1 = 0.
  • Confident and wrong is ruinous: as p→0p \to 0, −log⁡p→∞-\log p \to \infty.
  • It adds up: the probability of a whole sequence is a product of next-token probabilities (the chain rule of probability), and the log of a product is a sum. So minimising the summed loss is the same as maximising the probability of the whole training text.
loss = −ln p1.386
perplexity = 1/p4.0
random guess over 50,25710.82
reading a loss
10.82guessing uniformly over GPT-2’s 50,257 tokens (a fresh, untrained model starts near here)
1.39your slider: like choosing between 4.0 equally likely tokens
0.00always certain and always right (impossible for real text)
loss = −ln p
p = 0.25 costs 1.39. Halving the probability always adds the same ln 2 ≈ 0.69 to the loss, wherever you start.
Drag the slider (or the chart) to set the probability the model gave the correct next token. The loss is −ln p; perplexity is e to the loss.

Perplexity

Losses are hard to picture, so people often report perplexity, eLe^{\mathcal{L}}. A perplexity of 48 means the model is, on average, as unsure as if it were choosing uniformly between 48 tokens. Lower is better. A model that guesses uniformly over GPT-2’s 50,257 tokens has loss ln⁡50,257=10.82\ln 50{,}257 = 10.82 and perplexity 50,257. More in perplexity.

What a loss curve looks like

Plot the loss against training steps and almost every language model draws the same shape:

  • Step 0: random weights give close to uniform predictions, a loss near 10.8 for a 50,257-token vocabulary.
  • The first few hundred steps: a steep drop as the model learns which tokens are common (“ the”, “,”, “.”). Just predicting token frequencies takes the loss a long way down.
  • Then a long, slow slope: grammar, then facts, then longer-range patterns, each worth a little less loss. Bigger models and more data keep pushing it down, following smooth scaling laws.

For scale: the released GPT-2 small reaches a loss of about 3.1 on web text (perplexity about 22), and GPT-2 XL about 2.5. Watch a real curve being drawn in train a tiny transformer live.

The loss can never reach zero on real text. Language is genuinely uncertain: after “I had a cup of”, both “ tea” and “ coffee” are right, and the best a model can do is split its bets. The irreducible part of the loss is the entropy of language itself.

going deeper

In code

logits = model(tokens[:, :-1])                 # (B, T-1, vocab): predictions at every position
targets = tokens[:, 1:]                        # the same text shifted one place left
loss = F.cross_entropy(logits.reshape(-1, logits.size(-1)), targets.reshape(-1))

F.cross_entropy applies log-softmax and picks out the target’s log-probability in one numerically stable step.

Loss masks

In chat fine-tuning, only the assistant’s tokens count: the prompt’s positions get a so the model is not trained to predict the user’s words.

Numbers

GPT-2 small, our three sentences: cat 3.88, France 4.50, Mary and John 3.58. Loss of the released GPT-2 checkpoints on OpenWebText (from nanoGPT): small 3.12, medium 2.84, large 2.67, XL 2.54.

In papers

Related

  • backprop - To train, the model needs to know how each of its weights affected the loss. Backpropagation gets all of those gradients in one backward sweep using the chain rule. The residual stream gives the gradient a straight road down through the stack, and an optimiser such as Adam, with a warm-up and decay schedule, turns gradients into updates.
  • train-live - A real transformer, one layer and one attention head, learns to reverse and to sort five digits while you watch. Within a few hundred steps its attention goes from noise to a clean pattern you can read, and that pattern is exactly the algorithm that solves the task.
  • unembedding - At the top of the stack, the last token’s vector is normalised and multiplied by one big matrix that gives a score to every token in the vocabulary. Softmax turns the scores into probabilities. Applying the same read-out to the middle layers, the logit lens, shows the prediction taking shape.
  • what-an-llm-does - A language model does one thing. It reads a list of tokens and gives a probability for every possible next token. Generation is that one step in a loop. Pick a token, append it, run again.