Tokenwerk · The LLM textbook

Chapter 14 · II · From numbers to language · 7 minutes

The learning goal: cross-entropy

How do you scold a language model? You check how many percent it gave the correct next word. Few percent, big trouble. That is cross-entropy, the learning goal of ChatGPT and friends.

What does “wrong” even mean here?

With the number model it was easy: prediction minus target. But a language model doesn't output a single number; it outputs a whole list of percentages, one for every possible next token. From the training data we know which token actually came next. So we ask: how many percent did the model give exactly this token?

Example: after “The cat sits” the data continues with “on”. If the model gives “on” only 10 percent, the error should be large. At 80 percent, small. Important: other plausible words aren't punished separately; the goal is simply to give the actually observed word as much of the cake as possible.

Why not just compare the IDs?

If “on” has ID 42 and “under” ID 43, the distance of 1 is completely meaningless. IDs are house numbers. “Under” isn't “almost right” just because its number is close. That is why the squared error is out of place here. We only look at the probability of the correct token, no matter what number it has.

One sentence becomes many tasks

Take the sequence [BOS, The, cat, sleeps, EOS]. BOS is the start marker, EOS the end marker. Four practice tasks come out of it at once:

Visible input so far Desired next token
BOS The
BOS, The cat
BOS, The, cat sleeps
BOS, The, cat, sleeps EOS

In the program these are two lists: input [BOS, The, cat, sleeps] and target [The, cat, sleeps, EOS]. The same sequence, just shifted by one. That is called the target shift. So a single sentence delivers as many exercises as it has tokens, which is why a language model learns from text so efficiently.

Who wrote down the answers? Nobody. The answer is simply the word that comes next in the real text. The training program holds it back like the answer sheet for a fill-in-the-blank test, lets the model guess, and only checks afterwards. That is why no human has to label any data: any text at all is automatically a stack of tasks with answers. That is why a language model can be trained on trillions of words.

And why do probabilities come out at the end instead of a single answer? Because often there is no single right one. One text says “The cat sits on the mat”, another “… on the sofa”, the next “… on the roof”. Sometimes the model is pushed toward “mat”, sometimes toward “sofa”. In the end its distribution roughly reflects how often what follows such a beginning. Later, when you chat, there is no answer sheet anymore: the model simply draws a word from this learned distribution.

So the model doesn't cheat by peeking at the next word, there will be a “mask” later. It comes in the chapter on causality.

The penalty curve

We need a rule that works like this: 100 percent for the correct token gives error zero. The fewer percent, the larger the error, and hard when the model was very sure and wrong. The negative logarithm does exactly that:

Probability of the correct token Error approximately
0.9 0.105
0.5 0.693
0.1 2.303
0.01 4.605

Look at the numbers: from 90 to 50 percent the error rises by 0.6. From 10 to 1 percent by another 2.3. Being confidently wrong costs you dearly.

What is a logarithm?

You know exp from the softmax chapter. The natural logarithm, ln or log for short, is its counterpart, the reverse gear so to speak: because exp(0)=1, ln(1)=0. Because exp(1)≈2.718, ln(2.718)≈1.

For numbers between 0 and 1 the logarithm is negative. The minus in front flips it so a positive error comes out. You don't need to calculate anything; the table above and the direction are enough: more percent, less error.

The short formula

L=−log⁡(pk).L=-\log(p_k).

Read it like this: take the probability of the correct token, apply the logarithm, flip the sign. k is the number of the correct token, pkp_k its probability. k isn't a learnable number; it comes from the data.

At probability 0.5 that gives about 0.693. The official name of this rule is negative log-likelihood loss. You may translate it as “error from the probability of the correct token”.

Why it is called cross-entropy

You will hear the name cross-entropy all the time. In general it compares two distributions. In our case, though, the target distribution is very simple: 100 percent for the correct token, 0 for all others (a one-hot target). Then cross-entropy shrinks down to exactly our formula. Two names, one calculation.

In PyTorch you only pass the ID of the correct token:

python
loss = F.cross_entropy(
    logits.reshape(-1, vocab_size),
    targets.reshape(-1),
    ignore_index=-100,
)

logits are the raw values before softmax, targets the correct token IDs. reshape puts all positions of all examples into one long list of tasks; -1 means “work out the length yourself”.

Important: pass in the raw values, not finished percentages. The function does softmax and logarithm internally in a particularly stable combination. Softmax twice would be a different, wrong calculation.

Adding up many positions fairly

We add up the errors of all target positions and divide by their number. A long text with 100 targets counts ten times as much as a short one with 10; every token is worth the same.

Padding means filler positions used to bring short examples up to the length of the others. Of course the model shouldn't learn anything from them. So they get the target −100, and ignore_index=-100 tells the function: skip these spots. −100 isn't a real token ID but an agreed “please ignore”.

Perplexity: the same number, packaged differently

Apply exp to the average error and you get the perplexity. Intuitively, it says among how many tokens the model is on average as unsure as if it were rolling dice.

Example: a model that always spreads 25 percent evenly over four possible tokens has perplexity 4; it “rolls a four-sided die”. A good model has a low perplexity. Careful when comparing models with different tokenizers: if a token is a letter in one and half a word in the other, you are comparing apples and oranges.

And how does that turn into learning?

Just like in part I! The error depends on the logits, the logits depend on the weights, and backpropagation passes the effect backwards. The gradient for a logit is even wonderfully simple: computed probability minus target (1 for the correct token, 0 otherwise). If the correct token has 50 percent, that gives 0.5−1=−0.5, so its score gets pushed up. All wrong candidates get pushed down a little.

The learning goal is new. The learning mechanism is the old one: measure the error, compute the gradient, turn the dials a bit downhill.

Build it yourself: in step 3 of part VII you program exactly this error with F.cross_entropy, and watch it go down.

Key points

  • Cross-entropy asks: how much probability did the model give the token that actually came next? The less, the larger the error.
  • Thanks to the target shift, every position in a text becomes a practice task.
  • Learning happens as always via backpropagation and gradient descent. Perplexity is the same number on a different scale.