1.4Probability, softmax & cross-entropy
How a model turns raw scores into probabilities with softmax, how temperature sharpens or flattens them, and how cross-entropy grades a prediction. This is the exact loss every LLM is trained on.
Predictions as probabilities
When a language model reads “The cat sat on the”, it does not output a single word. It outputs a probability for every token in its vocabulary: maybe 40% “mat”, 15% “floor”, 8% “sofa”, and tiny amounts for tens of thousands of others. That list of probabilities is a probability distributionProbability distributionAn assignment of probabilities to possible outcomes, summing to 1.: every entry is between 0 and 1, and they add up to exactly 1.
Probabilities are much more useful than a single guess. They express uncertainty (“mat or floor, not sure which”), they let us generate varied text by sampling, and, as you will see, they give us a precise way to grade the model during training.
Probability in two minutes
You need only three ideas from probability for this whole guide.
Distributions. A distribution assigns a number between 0 and 1 to each possible outcome, and the numbers sum to 1. A fair die gives to each face. A language model’s output gives some probability to each of its tens of thousands of tokens.
Conditional probability. , read “the probability of A given B”, is the probability of A once you know B happened. might be 0.2 on an average day, but is much higher. A language model computes exactly this kind of quantity: .
The chain rule of probability. The probability of a whole sequence is the product of the probability of each piece given everything before it:
This identity is always true, and it is the reason “predict the next token” is enough. A model that can give good next-token probabilities can score any text, and generate new text by picking one token at a time, as you will see in next-token prediction. It also explains why we work with logarithms: multiplying thousands of small probabilities underflows to zero on a computer, while adding their logs is easy and stable. Since , the log-probability of a sequence is the sum of the per-token log-probabilities.
From scores to a distribution
A neural network’s last layer is just a matrix multiplication, and it produces arbitrary real numbers: 3.1, −0.4, 7.2. These raw scores are called logitsLogitsRaw, unnormalized scores a model outputs, one per class or token. Softmax turns them into probabilities.. They can be negative and they don’t sum to anything in particular. We need a way to turn them into a proper distribution.
Imagine judges giving each contestant a score, and a prize fund to be split among them. You could split it in proportion to the scores, but scores can be negative, and you want the leader to get a clearly bigger share. So you first turn each score into “points” with an exponential: every extra score point multiplies a contestant’s points by about 2.7. Then each contestant gets their points divided by everyone’s total.
The judges’ scores are the logits, the exponential points are , and each contestant’s share is the softmax probability. The temperature is how dramatic the exponential is: at low temperature the leader takes nearly everything; at high temperature the prize is spread almost evenly.
Softmax: from scores to probabilities
SoftmaxSoftmaxA function that turns a vector of scores into probabilities by exponentiating each score and dividing by the total. does exactly what the analogy describes:
Exponentiating makes every value positive and keeps the order (bigger logit, bigger probability). Dividing by the sum makes everything add to 1. And because it is exponential, differences matter, not absolute values: a logit that is 1 higher gets about times the probability; one that is 2 higher gets about 7.4 times.
One consequence surprises people: adding the same number to every logit changes nothing, because the common factor cancels in the fraction. Only the gaps between logits matter.
Temperature: sharpening and flattening
Divide every logit by a temperatureTemperatureA sampling knob that divides logits before softmax. Low values make output more deterministic; high values make it more random. before the softmax:
With the gaps get bigger, so the top choice grabs more probability: the distribution is sharper and more confident. With the gaps shrink and the distribution gets flatter. As , all probability goes to the single highest logit; as , every option becomes equally likely. When you set “temperature” in a chatbot’s settings, this is the dial you are turning.
Cross-entropy: grading a prediction
Now suppose we know the right answer: the actual next word was “mat”. How good was the model’s prediction? The answer used to train essentially every classifier and every LLM is the cross-entropy lossCross-entropy lossThe negative log-probability the model assigned to the correct answer. It is low when the model is confidently right.:
That’s it: the negative log of the probability the model gave to the correct answer. Look at how it behaves:
- (certain and right): . Perfect.
- : .
- : .
- (confident it’s not the right answer): . Ouch.
The log makes the penalty grow without limit as the probability of the truth approaches zero. A model that hedges a little is punished mildly; a model that is confidently wrong is punished severely. That pushes models toward probabilities that are calibrated, meaning they reflect how often they’re actually right.
Things to try:
- Raise one logit by 1. Its probability roughly multiplies by 2.7 (before renormalizing). The others all shrink, because the total must stay at 1.
- Add +1 to every logit. The bars don’t move. Only the differences between logits matter.
- Temperature 0.2, then 3. At low temperature “mat” takes almost everything. At high temperature even “banana” gets a real share.
- Make “sofa” the correct answer. The loss jumps, because the model gave it a small probability. Drag its logit up and watch the dot slide down the curve toward zero.
- Confident and wrong. The model bets on “banana” with about 94% probability while the truth is “mat” (about 1.7%). The loss is above 4, nearly eight times the default case.
Why this loss trains language models
A language model is trained on trillions of tokens of text. At every position, it predicts a distribution over the next token, and the loss is . The training loss you see reported for an LLM is the average of this number over many positions. Training pushes the probability of each real next token up, and because probabilities sum to 1, every other token gets pushed down a little.
The numbers have a useful scale. A model that knows nothing and spreads probability evenly over a 50,000-token vocabulary gives each token , a loss of . That is roughly where a freshly initialized model starts. Good LLMs get down to around 2 or below on typical text, though exact values depend heavily on the tokenizer and the data, so losses from different models are not directly comparable. You will sometimes see perplexity, which is just : a loss of 2 means perplexity , “as uncertain as choosing uniformly among about 7 tokens”.
Why not simply train on accuracy, the fraction of tokens predicted correctly? Because accuracy is a step function: nudge a logit slightly and the top choice usually doesn’t change, so accuracy doesn’t change either. Its gradient is zero almost everywhere, and gradient descent gets no signal about which way to move. Cross-entropy changes smoothly with every logit, so every tiny improvement in the probability of the right answer is rewarded. It also rewards partial credit: moving the correct token from 5% to 20% lowers the loss substantially even though it is still not the top guess. That steady, fine-grained signal over trillions of tokens is what lets LLMs learn so much.
MATH CORNER · optionalSoftmax, temperature and the cross-entropy gradient with small numbers
Softmax. Take logits for classes A, B, C.
| sum | ||||
|---|---|---|---|---|
| 0.5 | (4, 2, 0) | (54.60, 7.39, 1.00) | 62.99 | (0.867, 0.117, 0.016) |
| 1 | (2, 1, 0) | (7.39, 2.72, 1.00) | 11.11 | (0.665, 0.245, 0.090) |
| 2 | (1, 0.5, 0) | (2.72, 1.65, 1.00) | 5.37 | (0.506, 0.307, 0.186) |
Lower temperature, sharper distribution; higher temperature, flatter.
Loss. If A is correct (at ): . If C is correct: .
The gradient is beautifully simple. Writing for the one-hot target, the gradient of the cross-entropy loss with respect to the logits is
With A correct: . Gradient descent steps against the gradient, so it raises and lowers and , each in proportion to how much probability it wrongly took. The entries sum to zero, consistent with “adding a constant to every logit changes nothing”.
Derivation sketch. where is the correct class. Differentiating the log-sum gives , and the first term contributes only when .
Numerical stability. Computing for overflows. Since adding a constant changes nothing, implementations subtract the largest logit first: . The demo does this too.
In code
import numpy as np
def softmax(z, T=1.0):
z = np.asarray(z, dtype=float) / T
e = np.exp(z - z.max()) # subtract max for numerical stability
return e / e.sum()
z = [2.0, 1.0, 0.0]
p = softmax(z)
print(p.round(3)) # [0.665 0.245 0.09 ]
print(softmax(z, T=0.5).round(3)) # [0.867 0.117 0.016]
print(-np.log(p[0])) # cross-entropy if class 0 is correct: 0.408
# PyTorch fuses softmax + log + picking the correct class into one stable op:
import torch, torch.nn.functional as F
logits = torch.tensor([[2.0, 1.0, 0.0]])
print(F.cross_entropy(logits, torch.tensor([0]))) # tensor(0.4076)
Note that F.cross_entropy takes raw logits, not probabilities. Passing it the output of a softmax is a classic bug: it would apply softmax twice.
- “Logits are probabilities.” Logits are unnormalized scores that can be any real number. Only after softmax do they become probabilities.
- “Softmax picks the maximum.” It produces a soft version of the maximum: the largest logit gets the most probability, but every option gets some. The hard maximum is the limit as temperature goes to zero.
- “Doubling a logit doubles its probability.” Softmax is exponential in the differences. Raising a logit by 1 multiplies its unnormalized weight by about 2.7, and the final probability depends on all the other logits too.
- “A lower loss means the model is more often right.” Loss rewards putting high probability on the truth, which is related to but not the same as top-1 accuracy. A model can become more accurate while its loss gets worse if it grows overconfident on the cases it gets wrong.
Check your understanding
Q1.Logits are (1, 1, 1, 1). What does softmax output?
Q2.The model gives the correct token probability 0.01. Roughly what is the cross-entropy loss?
Q3.You lower the temperature from 1.0 to 0.3. What happens to the distribution?
Q4.With softmax and cross-entropy, the gradient of the loss with respect to logit i is p_i − y_i. For an incorrect class with p_i = 0.3, what does gradient descent do to its logit?
Q5.An untrained model spreads probability uniformly over a 32,000-token vocabulary. What is its cross-entropy loss per token?
Further reading
- bookDeep Learning (Goodfellow, Bengio, Courville), Section 6.2.2: Output units — Softmax outputs and why they pair naturally with the log-likelihood loss.
- blogVisual Information Theory (Chris Olah) — A beautiful visual explanation of entropy and cross-entropy as bits.
- docstorch.nn.functional.cross_entropy documentation — The standard implementation; takes logits, not probabilities.
- paperDistilling the Knowledge in a Neural Network (Hinton et al., 2015) — Uses softmax temperature to transfer a big model's 'soft' knowledge to a small one.