BACKPROP LAB
01TITLE

Softmax

DIFFICULTY 1/38 MIN02 · Probability & Entropy
UNSEEN
02EQUATION
CRISP KATEX // NO DISTORTION

softmax(z)i=ezi∑j=1Kezj=ezi−m∑j=1Kezj−m,m=max⁡jzj\text{softmax}(z)_i = \frac{e^{z_i}}{\sum_{j=1}^{K} e^{z_j}} = \frac{e^{z_i - m}}{\sum_{j=1}^{K} e^{z_j - m}}, \qquad m = \max_j z_j

Subtracting m=max⁡jzjm = \max_j z_j before exponentiating matters because naive ezie^{z_i} overflows floating-point precision (inf / inf = NaN) even for modest logits (around zi>709z_i > 709 in float64 or zi>88z_i > 88 in float32), whereas shifting ensures every exponent satisfies zi−m≤0z_i - m \le 0 so ezi−m∈(0,1]e^{z_i - m} \in (0, 1] while leaving the exact mathematical ratios unchanged.

03WHAT IT MEANS

Softmax converts a vector of arbitrary real scores (logits) into positive probabilities that sum to 11, amplifying larger entries exponentially relative to smaller ones. Subtracting the maximum score from every entry before taking exponentials keeps each exponential bounded at 11 or less, preventing floating-point overflow without changing the final probabilities.

04WHERE A MODEL USES IT

Transformers and classifiers apply softmax both to transform final vocabulary logits into next-token probabilities and to normalize query-key scores into attention weights inside every attention head.

05WORKED EXAMPLE

Take raw logits z=[2.0,1.0,0.0]z = [2.0, 1.0, 0.0]:

  1. Subtract max for stability: m=max⁡(2.0,1.0,0.0)=2.0m = \max(2.0, 1.0, 0.0) = 2.0, giving shifted logits z−m=[0.0,−1.0,−2.0]z - m = [0.0, -1.0, -2.0].
  2. Exponentiate: e0.0=1.0000e^{0.0} = 1.0000, e−1.0≈0.3679e^{-1.0} \approx 0.3679, and e−2.0≈0.1353e^{-2.0} \approx 0.1353.
  3. Sum exponentials: S=1.0000+0.3679+0.1353=1.5032S = 1.0000 + 0.3679 + 0.1353 = 1.5032.
  4. Divide by the sum:

softmax([2.0,1.0,0.0])=[1.00001.5032,  0.36791.5032,  0.13531.5032]≈[0.6652,  0.2447,  0.0900]\text{softmax}([2.0, 1.0, 0.0]) = \left[\frac{1.0000}{1.5032},\; \frac{0.3679}{1.5032},\; \frac{0.1353}{1.5032}\right] \approx [0.6652,\; 0.2447,\; 0.0900]

06RUN IT
PYTHON 3 + NUMPY // LAZY WEBASSEMBLY WORKER

CODE RUNS ONLY IN YOUR BROWSER VIA PYODIDE WEBASSEMBLY — NOTHING IS SENT TO ANY SERVER.

07SOURCES
08CHECK YOURSELF

QUESTION 1 / 3

0 / 3 ANSWERED

Q1 · MCQ

Why does a numerically stable softmax implementation subtract max(z) from every logit before exponentiating?

09NEXT UP

NO DOWNSTREAM FORMULAS YET

Nothing downstream lists Softmax as a prerequisite yet. Open all 20 curriculum sections to pick what to prove next.

BROWSE ALL 20 SECTIONS →