Skip to content
LearnAI
PART 1 · FOUNDATIONS/ Math toolkit

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.

⏱ 13 minBeginner

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 1/61/6 to each face. A language model’s output gives some probability to each of its tens of thousands of tokens.

Conditional probability. P(A∣B)P(A \mid B), read “the probability of A given B”, is the probability of A once you know B happened. P(umbrella)P(\text{umbrella}) might be 0.2 on an average day, but P(umbrella∣rain)P(\text{umbrella} \mid \text{rain}) is much higher. A language model computes exactly this kind of quantity: P(next token∣all the tokens so far)P(\text{next token} \mid \text{all the tokens so far}).

The chain rule of probability. The probability of a whole sequence is the product of the probability of each piece given everything before it:

P(the, cat, sat)=P(the)⋅P(cat∣the)⋅P(sat∣the, cat).P(\text{the, cat, sat}) = P(\text{the}) \cdot P(\text{cat} \mid \text{the}) \cdot P(\text{sat} \mid \text{the, cat}) .

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 log⁡(ab)=log⁡a+log⁡b\log(ab) = \log a + \log b, 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.

ANALOGY· Splitting a prize by votes, with a twist

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 eze^{z}, 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:

pi=ezi∑jezj.p_i = \frac{e^{z_i}}{\sum_j e^{z_j}} .

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 e≈2.72e \approx 2.72 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. TT before the softmax:

pi=ezi/T∑jezj/T.p_i = \frac{e^{z_i/T}}{\sum_j e^{z_j/T}} .

With T<1T < 1 the gaps get bigger, so the top choice grabs more probability: the distribution is sharper and more confident. With T>1T > 1 the gaps shrink and the distribution gets flatter. As T→0T \to 0, all probability goes to the single highest logit; as T→∞T \to \infty, 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.:

L=−ln⁡pcorrect.L = -\ln p_{\text{correct}} .

That’s it: the negative log of the probability the model gave to the correct answer. Look at how it behaves:

  • p=1p = 1 (certain and right): L=0L = 0. Perfect.
  • p=0.5p = 0.5: L≈0.69L \approx 0.69.
  • p=0.1p = 0.1: L≈2.30L \approx 2.30.
  • p=0.001p = 0.001 (confident it’s not the right answer): L≈6.91L \approx 6.91. 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.

INTERACTIVESoftmax and cross-entropy playground
Context: The cat sat on the ___The model outputs one logit (raw score) per candidate token. Click a token’s name to mark it as the correct next word.
59.5%
21.9%
13.3%
4.9%
0.4%
p(mat) = ez/T / Σ ez/T = 1.000 / 1.680 = 0.595
loss = −ln p(mat) = 0.519 nats
top guess: mat (correct) · probabilities sum to 1.000
(exponentials shown after subtracting the largest z/T, which cancels out)
01234500.250.50.751probability given to the correct tokenloss = −ln p
Move the logit sliders and watch the probabilities change. Click a token's name to make it the correct answer. Turn the temperature dial, try 'Add +1 to every logit' (nothing changes!), and press 'Confident and wrong' to see the loss explode.

Things to try:

  1. 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.
  2. Add +1 to every logit. The bars don’t move. Only the differences between logits matter.
  3. Temperature 0.2, then 3. At low temperature “mat” takes almost everything. At high temperature even “banana” gets a real share.
  4. 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 −ln⁡p-\ln p curve toward zero.
  5. 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 −ln⁡p(actual next token)-\ln p(\text{actual next token}). 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 1/50,0001/50{,}000, a loss of ln⁡50,000≈10.8\ln 50{,}000 \approx 10.8. 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 eLe^{L}: a loss of 2 means perplexity ≈7.4\approx 7.4, “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 z=(2,1,0)\mathbf{z} = (2, 1, 0) for classes A, B, C.

TTz/Tz/Tez/Te^{z/T}sumpA,pB,pCp_A, p_B, p_C
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 T=1T = 1): L=−ln⁡0.665≈0.408L = -\ln 0.665 \approx 0.408. If C is correct: L=−ln⁡0.090≈2.41L = -\ln 0.090 \approx 2.41.

The gradient is beautifully simple. Writing y\mathbf{y} for the one-hot target, the gradient of the cross-entropy loss with respect to the logits is

∂L∂zi=pi−yi.\frac{\partial L}{\partial z_i} = p_i - y_i .

With A correct: ∇zL=(0.665−1,  0.245,  0.090)=(−0.335,  0.245,  0.090)\nabla_{\mathbf{z}} L = (0.665 - 1,\; 0.245,\; 0.090) = (-0.335,\; 0.245,\; 0.090). Gradient descent steps against the gradient, so it raises zAz_A and lowers zBz_B and zCz_C, 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. L=−zc+ln⁡∑jezjL = -z_c + \ln\sum_j e^{z_j} where cc is the correct class. Differentiating the log-sum gives ezi/∑jezj=pie^{z_i}/\sum_j e^{z_j} = p_i, and the first term contributes −1-1 only when i=ci = c.

Numerical stability. Computing eze^{z} for z=1000z = 1000 overflows. Since adding a constant changes nothing, implementations subtract the largest logit first: softmax⁡(z)=softmax⁡(z−max⁡jzj)\operatorname{softmax}(\mathbf{z}) = \operatorname{softmax}(\mathbf{z} - \max_j z_j). 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.

COMMON MISCONCEPTIONS
  • “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

0/5 answered
  1. Q1.Logits are (1, 1, 1, 1). What does softmax output?

  2. Q2.The model gives the correct token probability 0.01. Roughly what is the cross-entropy loss?

  3. Q3.You lower the temperature from 1.0 to 0.3. What happens to the distribution?

  4. 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?

  5. Q5.An untrained model spreads probability uniformly over a 32,000-token vocabulary. What is its cross-entropy loss per token?

Further reading

Progress is saved in this browser only.
Type to search across all lessons and glossary terms.