Softmax
Softmax
Turn scores into a categorical distribution, derive its gradient, and keep extreme logits numerically stable.
softmaxA score of 1000 is not a probability
A classifier gives three document categories scores of 1000, 1001, and 999. The second category ranks first, but the raw numbers do not describe uncertainty: they neither lie between zero and one nor sum to one. Softmax turns these scores, often called logits, into approximately 0.245, 0.665, and 0.090.
Only score differences matter. Subtracting 1000 from every score gives 0, 1, and -1 and leaves the distribution unchanged. This is useful both for understanding the model and for avoiding numerical overflow. A logit is an unconstrained real score; calling it a probability before normalization confuses two different quantities.
Ratios, derivatives, and cross-entropy
For a finite vector of real logits, define:
Each probability is positive in exact arithmetic, and the probabilities sum to one. Adding a common constant cancels between numerator and denominator. The ratio identity also gives a useful interpretation: increasing one logit by , with others fixed, doubles its odds against each other category. It does not necessarily double its probability. D2L, Section 4.1
Differentiate the quotient. For , the numerator and denominator both change; for , only the denominator changes. Using when the indices agree and zero otherwise gives:
Every row of sums to zero, matching invariance under a common score shift. For a target distribution whose entries sum to one, categorical cross-entropy and its gradient simplify to:
To see the last equality, differentiate the log of the exponential sum, obtaining , and then differentiate the target-weighted score sum, obtaining . One-hot targets are a special case. Feeding probabilities into a library loss that expects logits applies the wrong transformation. D2L, Section 4.1.2
Compute log-probabilities directly
Let be the largest logit. Exponentiating shifted values makes the largest exponential one, so the denominator cannot vanish. Some small probabilities can still underflow to zero. Therefore compute log-softmax directly rather than taking the logarithm of already rounded probabilities. Deep Learning, Section 4.1
This complete Python example checks normalization, shift invariance, extreme scores, and the cross-entropy gradient using central finite differences. Its input contract requires finite logits whose shifted differences remain representable as finite floats; it rejects values beyond that contract.
import math
def log_softmax(logits):
if not logits or any(not math.isfinite(z) for z in logits):
raise ValueError("nonempty finite logits required")
m = max(logits)
shifted = [z-m for z in logits]
if any(not math.isfinite(z) for z in shifted):
raise ValueError("logit differences exceed float range")
normalizer = math.log(math.fsum(math.exp(z) for z in shifted))
return [z-normalizer for z in shifted]
def probabilities(logits):
return [math.exp(lp) for lp in log_softmax(logits)]
z = [1000.0, 1001.0, 999.0]
p = probabilities(z)
assert math.isclose(sum(p), 1)
assert abs(p[1]-0.6652409557748218) < 1e-12
assert all(abs(a-b) < 1e-12 for a,b in zip(p, probabilities([v+7 for v in z])))
assert probabilities([5.0]*3) == [1/3]*3
assert log_softmax([1000.0, -1000.0])[1] == -2000
h, target = 1e-3, 1
for j in range(len(z)):
plus, minus = z.copy(), z.copy()
plus[j] += h
minus[j] -= h
numeric = (-log_softmax(plus)[target]+log_softmax(minus)[target])/(2*h)
assert abs(numeric-(p[j]-(j == target))) < 1e-7
for invalid in ([], [float('-inf')]*2, [1e308,-1e308]):
try:
log_softmax(invalid)
except ValueError:
pass
else:
raise AssertionError("invalid logits accepted")
The implementation takes time and space for the returned probabilities and intermediate arrays. A batched classifier usually normalizes along its class axis, separately for each example. Normalizing across examples instead makes one document’s prediction depend on the other documents in the batch.
Normalization is not calibration
Softmax guarantees a categorical distribution, not that a prediction of 0.8 will be correct 80% of the time. That property is calibration and requires evaluation. Multiplying all logits by ten preserves the winning category while usually making the distribution more concentrated; accuracy can stay unchanged while reported confidence changes substantially.
Temperature uses for . Increasing flattens the distribution toward uniformity; as approaches zero, mass concentrates on the maximum logits, splitting equally among exact ties. Temperature changes sampling behavior; it does not establish factual correctness.
A categorical output assumes one mutually exclusive outcome. A document that can carry several labels often needs separate Bernoulli outputs instead. Masked attention adds another engineering boundary: implementations commonly use negative infinity for forbidden positions, but a row with every position forbidden has no valid distribution. The finite-input teaching function deliberately rejects that input rather than inventing an answer.
Check what changes and what stays fixed
- What is softmax of three equal finite logits? Answer: each probability is , regardless of their common value.
- If all logits increase by 7, what happens to their probabilities? Answer: nothing in exact arithmetic; their differences are unchanged.
- For the opening example and true class index 1, what is the loss gradient? Answer: approximately , with components summing to zero.
- Why can
log(softmax(z)[i])fail even after subtracting the maximum? Answer: a very small numerator can underflow to zero; direct log-softmax retains its finite log-probability when the score difference is representable.
The same normalization appears in different models
Multinomial logistic regression applies softmax to linear scores. Neural classifiers apply it to learned representations. Attention applies it to compatibility scores over keys. The normalization is shared, while the meanings of the categories and scores differ. When comparing implementations, identify the normalized axis, mask, temperature, and expected loss inputs before interpreting a numerical discrepancy.
Make a prediction, then check
What happens to softmax probabilities in exact arithmetic when 100 is added to every logit?
Learning objectives
- Derive class probabilities, the Jacobian, and cross-entropy gradients from score differences.
- Implement stable log-softmax and distinguish normalization, calibration, temperature, and multilabel outputs.
Prerequisites & connections
Explore related knowledge →References
- Dive into Deep Learning — Softmax Regression
Aston Zhang; Zachary C. Lipton; Mu Li; Alexander J. Smola · 2023 - Deep Learning — Chapter 4: Numerical Computation
Ian Goodfellow; Yoshua Bengio; Aaron Courville · 2016
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check: cited-source comparison, re-derivation and recalculation, bilingual argument comparison, and executed Python assertions; no independent human peer review.
- Re-derived probability ratios, the Jacobian, and p−y gradients; complete Jacobians matched central finite differences on 20 random logit vectors.
- Executed extreme logits, shift invariance, equal scores, empty inputs, and nonfinite differences; distinguished normalization, calibration, and fully masked rows.
- Compared arguments, modeling assumptions, numbers, and exercise answers across languages; structural checks separately compare display formulas, code, references, and main sections. No independent human peer review.
Source locations checked:
- Dive into Deep Learning — Softmax Regression · §4.1.1–4.1.2: categorical normalization and cross-entropy derivatives
- Deep Learning — Chapter 4: Numerical Computation · §4.1: subtracting the maximum, remaining underflow, and direct log-softmax
Related topics