All courses

Softmax, logits and the log-sum-exp trick

Turn a logit vector into probabilities with softmax and explain why adding a constant to every logit changes nothing. Compute softmax stably by subtracting the max.

Builds on: What an LLM computes, end to end

▶ Watch this lesson Start the whole course

What the animation says

Scores to probabilities

At every position, the model outputs one raw score per token in its vocabulary. These scores are called logits. Logits can be negative, or huge. But we need probabilities: positive, and adding up to one. Softmax gets there in two moves. First, raise e to each score. Everything turns positive, and the order stays the same. Then divide each one by the total. Logits of two, one and minus one become about seventy, twenty-six and three and a half percent. Now add ten to every logit. What happens to the probabilities?

Only gaps matter

They don't change at all. Adding ten multiplies every exponential by e to the ten. The total gets the same factor, so it cancels. So the ratio between two tokens depends only on the gap between their logits. A gap of one means about two point seven times more likely. A gap of three means about twenty times. And equal logits always mean equal probabilities. Now try the logits one thousand, nine ninety-nine, nine ninety-seven. Same gaps. What does a direct computation give?

Overflow, underflow, the fix

Not a number. e to the one thousand is far beyond the largest float, so it becomes infinity. Infinity divided by infinity is NaN. Very negative logits fail the other way. Every exponential rounds down to zero, and zero over zero is NaN too. The fix uses what we just learned. Shifting all logits is free, so pick a shift that keeps the numbers safe. Which number should we subtract from every logit?

Worked: 1000, 999, 997

Subtract the max, one thousand. The logits become zero, minus one, minus three. Exponentiate: one, about zero point three seven, and about zero point zero five. The sum is about one point four two. The largest term is exactly one, so nothing overflows. And the sum is never below one, so there's no zero over zero. Divide: about seventy point five, twenty-five point nine, and three point five percent. That's exactly the answer for two, one, minus one. Same gaps, same probabilities.

In code, and in log space

In numpy, the naive line overflows and prints NaN. The stable version needs one extra subtraction. This line takes the max off before exponentiating. For log probabilities, use log-sum-exp: the max, plus the log of the shifted sum. Then each log probability is its logit minus that log-sum-exp. No exponential of a huge number anywhere. Remember: only the gaps between logits matter, and always subtract the max first.

From raw scores to probabilities

At each position the model outputs a logit vector $z_t \in \mathbb{R}^V$: one real score per vocabulary token. Scores can be negative, huge, or any size. A next-token distribution needs numbers that are positive and sum to 1. **What function makes that conversion, which properties of the scores actually matter, and how do you compute it without $e^{1000}$ blowing up?**

Exponentiate, then normalize

Softmax takes $e^{z_i}$ of each score, which makes everything positive and keeps the order. It then divides by the total so the results sum to 1. The key fact: $e^{a}/e^{b} = e^{a-b}$. So the probability ratio of two tokens depends only on their **score difference**. Adding the same constant $c$ to every logit multiplies every term, and the total, by $e^c$. That factor cancels.

Softmax, shift invariance, log-sum-exp

$$\mathrm{softmax}(z)_i = \frac{e^{z_i}}{\sum_{j=0}^{V-1} e^{z_j}}$$ Shift invariance: $\mathrm{softmax}(z + c\mathbf{1}) = \mathrm{softmax}(z)$ for any scalar $c$, where $\mathbf{1}$ is the all-ones vector (so $c$ is added to every logit). The naive form fails in two ways. Huge logits overflow to inf, giving inf/inf. Very negative logits underflow to 0, giving 0/0. Both produce NaN. Stable form: take $m = \max_j z_j$ and use $z - m$. The largest term becomes $e^0 = 1$, so nothing overflows and the sum is at least 1, never 0. Log-sum-exp: $\mathrm{LSE}(z) = \log\sum_j e^{z_j} = m + \log\sum_j e^{z_j - m}$, and $\log p_i = z_i - \mathrm{LSE}(z)$.

Worked example: z = (1000, 999, 997)

Computed directly, $e^{1000}$ overflows to inf, and inf/inf gives NaN. Stable route: 1. $m = 1000$, so $z - m = (0, -1, -3)$ 2. Exponentiate: $(1,\ 0.3679,\ 0.0498)$, with sum $1.4177$ 3. Divide: $p \approx (0.705,\ 0.259,\ 0.035)$. These are rounded, so they sum to 0.999. The logits $(2, 1, -1)$ give exactly the same $p$, because they are the same vector shifted by 998.

Stable softmax in numpy

The naive version returns NaN. The shifted version and the log-sum-exp version both agree with the hand calculation.
import numpy as np
def softmax(z):
    e = np.exp(z - z.max())
    return e / e.sum()
def log_softmax(z):
    m = z.max()
    return z - (m + np.log(np.exp(z - m).sum()))
z = np.array([1000., 999., 997.])
print(np.exp(z) / np.exp(z).sum())  # [nan nan nan] (plus an overflow warning)
print(softmax(z))                   # ≈ [0.705 0.259 0.035]
print(np.exp(log_softmax(z)))       # same

Remember

Softmax is $e^{z_i}/\sum_j e^{z_j}$. Only **differences** between logits matter: a gap of $\Delta$ means a probability ratio of $e^{\Delta}$, and adding a constant to every logit changes nothing. Always subtract the max before exponentiating. For log-probabilities use $z_i - \mathrm{LSE}(z)$.

On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.