To train a model we need one number that says how wrong it is: the loss. Training then follows the gradient of the loss (section 1) to make it smaller. A language model is trained with exactly one loss, the cross-entropy of the next token. This page builds it step by step, makes it safe to compute, and adds the two details every LLM (large language model) training loop has: ignored positions and label smoothing.
The idea: minus the log of the right answer's probability
Most models do not give one answer: they give a probability to every possible answer. The natural way to score such a model is to look at the probability it gave to the answer that turned out to be right. High probability: good. Low probability: bad.
The loss of one example is minus the log of that probability, . The log turns probabilities into a scale that punishes confident mistakes hard:
| probability of the right answer | |
|---|---|
| 1 | 0 (perfect) |
| 0.9 | 0.105 |
| 0.5 | 0.693 |
| 0.1 | 2.303 |
| 0.01 | 4.605 |
For a whole dataset, average over the examples:
where:
- (theta) are the model's parameters;
- is the number of examples, and is example : an input with its right answer ;
- , read "the probability of given ", is the probability the model gives to the right answer.
Example. On two examples the model gives the right answer probability and . The losses are and , and their average is .
This is called the negative log-likelihood, and minimizing it is maximum likelihood: choosing the parameters under which the training data is most probable. Why a log and an average, rather than multiplying the probabilities directly? The probability of the whole dataset is the product of the probabilities of its examples, and the log turns a product into a sum, which is much easier to work with. The minus sign is there because optimizers minimize.
The familiar losses are all this one
Depending on what the model outputs, the same recipe gives the losses you may have seen under different names:
| Model output | Assumed distribution of | Negative log-likelihood |
|---|---|---|
| a real number | Gaussian, mean , fixed variance | + const: MSE (mean squared error) |
| one probability | Bernoulli () | : binary cross-entropy |
| a distribution over classes | categorical | : cross-entropy |
Here ("y hat") is the model's prediction. How to read the rows:
- Predicting a number (a price, a reward): if you assume the true value is the prediction plus bell-shaped (Gaussian) noise, minus the log-probability is the squared error, up to constants. So the MSE is not an arbitrary choice.
- Predicting yes or no: the model gives a probability of "yes", and the loss is when the answer is yes, when it is no. The formula in the table is just these two cases in one line.
- Choosing among classes: the model gives a probability to each class , and the loss is for the right class . For a language model the classes are the tokens of the vocabulary, so this is the row that matters.
Cross-entropy, KL divergence and perplexity
Sometimes the right answer is not a single class but a distribution, for example 70% "cat", 20% "dog", 10% "sun". Call the true distribution and the model's distribution , both over the same classes. The cross-entropy averages with the true probabilities as weights:
where and are the true and the model's probabilities of class . It splits into two parts:
where:
- is the entropy of the data: how unpredictable the answer is by itself. The model cannot change it;
- is the KL (Kullback–Leibler) divergence: how far the model's distribution is from the true one. It is 0 only when .
Example. True , model .
- Cross-entropy: .
- Entropy: .
- KL divergence: the difference, .
If the model predicted exactly, the cross-entropy would drop to and the KL divergence to 0.
So minimizing the cross-entropy is the same as minimizing the KL divergence: the model is pulled towards the true distribution. In ordinary training the target is one-hot: the right class has and all others 0. Then the sum has a single term, , which is the last row of the table above.
Two numbers help read a loss value:
- The uniform baseline. A model that knows nothing gives every class , so its loss is . For the 50,257-token vocabulary of GPT-2 (Generative Pre-trained Transformer 2) that is nats (the unit of a loss computed with the natural log). A freshly initialized language model should start near this value; if yours starts far above it, the initialization is too large.
- Perplexity is : the number of equally likely tokens the model is, on average, hesitating between. A loss of 2.3 nats is a perplexity of about 10: as uncertain as picking among 10 tokens.
Cross-entropy from logits
A network does not output probabilities directly: it outputs logits , one raw score per class, and softmax turns them into probabilities (see the NumPy section). Computing log(softmax(z)) is unsafe: softmax can round a tiny probability to exactly 0, and then the log is . Instead, use the LSE (log-sum-exp) function, which stays finite:
where:
- is the loss of one example;
- is the logit of the right class ;
- , computed with the stable trick of the NumPy section.
Example. Logits , right class .
- .
- .
Check: softmax gives , and .
The gradient: probabilities minus the target
The gradient of this loss with respect to the logits is remarkably simple:
where is the softmax probability of class , and is 1 when is the right class and 0 otherwise. It comes from two facts: the derivative of with respect to is , and the derivative of is 1 for and 0 for the others.
In words: the gradient is the probabilities minus the one-hot target.
Example. Same logits, .
- Right class : gradient .
- Right class instead: gradient .
Training moves against the gradient, so the right class's logit goes up (its gradient is negative) and every other logit goes down, each in proportion to its probability. The worse the right answer's probability, the bigger the push.
The gradient of each example adds up to zero, and every entry stays between and , whatever the logits. This is why frameworks fuse softmax and cross-entropy into one operation: done separately, the softmax backward multiplies by tiny numbers and the log backward divides by them.
For a batch, the loss is the mean over the examples, so every example's gradient is also divided by . Forgetting that factor makes the right learning rate silently depend on the batch size.
Binary cross-entropy from a logit
For a yes/no answer the network outputs one logit , and the probability of "yes" is the sigmoid, which squashes any number into :
Example. , , .
The binary cross-entropy, , breaks for large logits: rounds to exactly , and then . It can be rewritten without ever computing :
where is the target (1 for yes, 0 for no) and is the absolute value of .
Why this form is safe: the exponent is never positive, so is between 0 and 1 and nothing overflows; and is never .
Example.
- , : , the same as .
- , : the naive formula returns
inf; the stable one gives , the correct loss.
The gradient has the same shape as for cross-entropy, prediction minus target: . The target may also be a soft target, any number between 0 and 1, such as for "probably yes".
The loss of a language model in practice
A language model predicts the next token at every position of every text in the batch: logits of shape (batch size, sequence length, vocabulary size) and targets of shape . The loss is the mean cross-entropy over all positions, with two refinements.
Ignored positions
Some positions should not be learned: padding tokens, added only to make the texts of a batch the same length, and in fine-tuning the prompt tokens. Their target is set to a special value (PyTorch uses ignore_index=-100). These positions contribute nothing, and the mean is taken over the remaining positions only.
Example. A batch has 4 positions with losses , and , and one padding position. The loss is . Dividing by all 4 positions would give : the loss would look better just because the batch had more padding.
Label smoothing
Label smoothing replaces the one-hot target with a softer one: on the right class, plus spread evenly over all classes. The loss becomes
where (epsilon), for example , is the amount of smoothing. In words: mostly the usual loss, plus a small penalty for giving any class a very low probability.
Example. Same logits as above, , , , .
- for the three classes: , , .
- First part: .
- Second part: .
- Total: , compared with without smoothing.
Label smoothing stops the model from pushing logits towards infinity to reach a probability of exactly 1, and it tends to improve calibration (Müller et al., below). Whether it helps depends on the task, but every framework exposes it, so it is worth knowing exactly what it computes.
References
- C. E. Shannon, A Mathematical Theory of Communication, Bell System Technical Journal 27(3), 379–423, 1948. Entropy and the information-theoretic view of coding.
- S. Kullback, R. A. Leibler, On Information and Sufficiency, Annals of Mathematical Statistics 22(1), 79–86, 1951. The divergence that cross-entropy minimizes.
- I. Goodfellow, Y. Bengio, A. Courville, Deep Learning, MIT Press, 2016. Section 3.13, information theory; section 5.5, maximum likelihood estimation; section 6.2.1.1, maximum likelihood and the cost functions of neural networks.
- C. Szegedy, V. Vanhoucke, S. Ioffe, J. Shlens, Z. Wojna, Rethinking the Inception Architecture for Computer Vision, CVPR, 2818–2826, 2016. Introduces label smoothing.
- R. Müller, S. Kornblith, G. Hinton, When Does Label Smoothing Help?, NeurIPS, 2019. Effects on calibration and on the learned representations.
- PyTorch documentation,
torch.nn.CrossEntropyLoss: the exact semantics ofignore_index,label_smoothingandreductionthat the last exercise reproduces.