TExcelTAD
Home › Math for Deep Learning & LLMs › Overflow, Underflow and a Stable Softmax

Overflow, Underflow and a Stable Softmax

The softmax softmax⁡(z)i=ezi/∑jezj\operatorname{softmax}(\mathbf{z})_i = e^{z_i}/\sum_j e^{z_j} looks harmless, but e1000e^{1000} overflows and e−1000e^{-1000} underflows in any float format. Large logits are normal in practice (attention scores, confident classifiers), so every framework computes the softmax, the log-softmax and the cross-entropy with a few algebraic tricks. They are short, and worth knowing by heart.

The max-subtraction trick

The softmax does not change if the same constant is subtracted from every logit:

ezi−c∑jezj−c=e−cezie−c∑jezj=ezi∑jezj\frac{e^{z_i - c}}{\sum_j e^{z_j - c}} = \frac{e^{-c}e^{z_i}}{e^{-c}\sum_j e^{z_j}} = \frac{e^{z_i}}{\sum_j e^{z_j}}

Choosing c=max⁡jzjc = \max_j z_j makes the largest exponent e0=1e^0 = 1: nothing overflows, and the denominator is at least 1, so nothing divides by zero.

python · try it yourself
import numpy as np

def softmax_naive(z): e = np.exp(z); return e / e.sum()
def softmax(z): e = np.exp(z - z.max()); return e / e.sum()
z = np.array([1000.0, 999.0, 990.0])
with np.errstate(over="ignore", invalid="ignore"):
    print("naive:", softmax_naive(z))
print("stable:", np.round(softmax(z), 6))
print("same as small logits:", np.allclose(softmax(z), softmax(z - 1000)))
naive: [nan nan nan]
stable: [7.31034e-01 2.68932e-01 3.30000e-05]
same as small logits: True

Log-sum-exp and log-softmax

Cross-entropy needs log⁡softmax⁡(z)y=zy−log⁡∑jezj\log\operatorname{softmax}(\mathbf{z})_y = z_y - \log\sum_j e^{z_j}. Computing the softmax first and then the log fails when a probability underflows to 0 (log⁡0=−∞\log 0 = -\infty). The log-sum-exp with the same shift is stable:

LSE⁡(z)=log⁡∑jezj=m+log⁡∑jezj−m,m=max⁡jzj\operatorname{LSE}(\mathbf{z}) = \log\sum_j e^{z_j} = m + \log\sum_j e^{z_j - m}, \qquad m = \max_j z_j
−log⁡softmax⁡(z)y=LSE⁡(z)−zy-\log\operatorname{softmax}(\mathbf{z})_y = \operatorname{LSE}(\mathbf{z}) - z_y
python · try it yourself
import numpy as np

def lse(z): m = z.max(); return m + np.log(np.sum(np.exp(z - m)))
z = np.array([50.0, -800.0, 10.0])          # the true class 1 has a hugely negative logit
y = 1
with np.errstate(divide="ignore", under="ignore"):
    p = np.exp(z - z.max()); p /= p.sum()
    print("probability of the true class:", p[y], " -> log:", np.log(p[y]))
print("stable cross-entropy:", lse(z) - z[y])
probability of the true class: 0.0  -> log: -inf
stable cross-entropy: 850.0

The stable version returns the exact, finite loss of 850 nats, and its gradient is still meaningful. This is why frameworks provide cross_entropy(logits, target) taking logits, not probabilities.

Sigmoid and binary cross-entropy

The same issue arises with one logit. log⁡σ(z)=−log⁡(1+e−z)\log\sigma(z) = -\log(1 + e^{-z}), and log⁡(1+eu)\log(1 + e^{u}) is the softplus, computed stably as max⁡(u,0)+log⁡(1+e−∣u∣)\max(u, 0) + \log(1 + e^{-\lvert u \rvert}). The binary cross-entropy with logits is then

ℓ(z,y)=softplus⁡(z)−yz\ell(z, y) = \operatorname{softplus}(z) - yz

Other places where numbers blow up

  • exp in attention scores: the same max trick inside the attention softmax; FlashAttention keeps a running maximum while processing blocks.
  • Products of many probabilities: work with sums of logs (Perplexity).
  • sqrt of a variance in normalization layers: add a small ϵ\epsilon (e.g. 10−510^{-5}) to avoid dividing by 0.
  • log of a probability that may be 0: clip with a tiny ϵ\epsilon, or better, avoid forming the probability.

In software

  • torch.logsumexp, torch.log_softmax, nn.CrossEntropyLoss (logits in), nn.BCEWithLogitsLoss (stable binary cross-entropy).
  • scipy.special.logsumexp, softmax and log_softmax do the same in NumPy land.
  • The online-softmax trick (updating the maximum and the sum as new scores arrive) makes memory-efficient attention possible.

Exercises

Exercise 1: Shift invariance

Compute softmax⁡(2,1,0)\operatorname{softmax}(2, 1, 0) and softmax⁡(102,101,100)\operatorname{softmax}(102, 101, 100) by hand (to 3 decimals).

Answer

Both are (0.665,0.245,0.090)(0.665, 0.245, 0.090).

Solution

e2,e1,e0=7.389,2.718,1e^2, e^1, e^0 = 7.389, 2.718, 1, sum 11.10711.107; dividing gives 0.665,0.245,0.0900.665, 0.245, 0.090. The second vector differs by the constant 100, which cancels.

Exercise 2: Log-sum-exp bounds

Show that max⁡jzj≤LSE⁡(z)≤max⁡jzj+log⁡K\max_j z_j \le \operatorname{LSE}(\mathbf{z}) \le \max_j z_j + \log K for KK logits.

Answer

The sum ∑jezj−m\sum_j e^{z_j - m} is between 1 and KK.

Solution

With m=max⁡jzjm = \max_j z_j, the term for the maximum is e0=1e^0 = 1 and every term is at most 1, so 1≤∑jezj−m≤K1 \le \sum_j e^{z_j - m} \le K. Taking logs and adding mm gives the bounds. LSE is a "smooth maximum".

Exercise 3: Stable binary cross-entropy (code)

Compute ℓ(z,y)=softplus⁡(z)−yz\ell(z, y) = \operatorname{softplus}(z) - yz for z=−40z = -40 and y=1y = 1, and compare with the naive −log⁡σ(z)-\log\sigma(z) in float32.

Answer

The stable loss is 40; the naive one is also about 40 here but becomes inf for z=−120z = -120 in float32.

Solution
python · try it yourself
import numpy as np
def softplus(u): return np.maximum(u, 0) + np.log1p(np.exp(-np.abs(u)))
for z in (np.float32(-40), np.float32(-120)):
    with np.errstate(over="ignore", divide="ignore"):
        naive = -np.log(np.float32(1) / (np.float32(1) + np.exp(-z)))
    print(float(z), "stable:", float(softplus(z) - 1 * z), " naive:", float(naive))
-40.0 stable: 40.0  naive: 40.0
-120.0 stable: 120.0  naive: inf

Test yourself

Why subtract max⁡jzj\max_j z_j before exponentiating in a softmax?

  1. It changes the probabilities to be more accurate
  2. It prevents overflow without changing the result
  3. It makes the logits positive
  4. It is required for the gradient

Why do frameworks' cross-entropy functions take logits instead of probabilities?

  1. Probabilities are not allowed in Python
  2. So they can use log-sum-exp and avoid log⁡0\log 0
  3. Logits are smaller
  4. It is faster to type

LSE⁡(z)\operatorname{LSE}(\mathbf{z}) is always between…

  1. 0 and 1
  2. max⁡jzj\max_j z_j and max⁡jzj+log⁡K\max_j z_j + \log K
  3. min⁡jzj\min_j z_j and max⁡jzj\max_j z_j
  4. −1-1 and 1