To learn, the network needs a number telling it how badly it’s doing. That’s the loss function.

For language models the task is: given the text so far, predict the next token. The network outputs a probability for every possible token. If the true next token was “cat” and the model gave “cat” a probability of 0.02, that’s bad. If it gave 0.9, that’s good.

The loss used is cross-entropy (also called negative log-likelihood):

Averaged over a whole text of tokens, this becomes:

Breaking down the averaged formula, piece by piece

PieceHow to read it
”For every position from 1 to , add up…”
The actual token at position
All the tokens before position (the context the model gets to see)
“The probability the model (with parameters ) assigned to the true token, given everything before it”
Natural log. Turns a probability into a negative number (or 0 if perfect)
(leading minus)Flips it so the loss is positive. Bigger = worse
Divide by the count, i.e. take the average

Plain English: “On average, how surprised was the model by the real next token?”

Model’s probability for the right tokenLoss Reaction
Perfect
Great
Meh
Bad
Very bad
Catastrophic

The log makes confident wrong answers get punished hard. Training means: adjust the parameters so this loss, averaged over a gigantic amount of text, goes down.

Perplexity

You’ll also see perplexity:

Roughly “how many tokens is the model effectively choosing between at each step.” A perplexity of 10 means it’s about as unsure as picking uniformly from 10 options.


← 2. Layers and why non-linearity matters · Contents · 4. Gradient descent and backpropagation →