Skip to content
mlmentorship

Stable Softmax

Convert logits to probabilities without numeric overflow.

Published · 11 min read ·Role-specific ·Intermediate

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Stable Softmax

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. A floating-point NumPy array logits and a valid normalization axis, defaulting to the last axis. Output. Return softmax probabilities with the same shape, summing to one along each selected-axis slice. Rules. Probabilities are proportional to exponentiated scores within each slice. Require finite inputs, a nonempty selected axis, and representable score differences. Preserve the input. Large common score offsets must not cause exponential overflow. Example. Scores [1000, 1001, 999] return approximately [0.244728, 0.665241, 0.090031]. Scores [0, 0] return [0.5, 0.5], not raw exponentials [1, 1].

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Subtract the row maximum, exponentiate nonpositive shifts, and divide by their shared sum.

Problem trace

Subtracting a shared maximum changes exponentials without changing ideal probabilities

Worked example: subtracting the maximum preserves probabilities while preventing overflowLogits (1000,1001) shift to (-1,0). Their softmax probabilities are about 0.269 and 0.731 without exponentiating 1000.A common logit shift changesexponential scale, not probabilityshares1000-110010minus 1001Exponentiate the small shifted values0.2690.731Remove the common scale beforeexponentiation.
Read it this way: Logits (1000,1001) shift to (-1,0). Their softmax probabilities are about 0.269 and 0.731 without exponentiating 1000. Does adding another thousand to both original logits change their shifted difference or their probability shares?
Full interview answer 11 min read
Reading depth

Convert finite class scores into probabilities while avoiding overflow from large but valid score values.

Problem

Input. A floating-point NumPy array logits and a valid normalization axis, defaulting to the last axis.

Output. Return softmax probabilities with the same shape, summing to one along each selected-axis slice.

Rules. Probabilities are proportional to exponentiated scores within each slice. Require finite inputs, a nonempty selected axis, and representable score differences. Preserve the input. Large common score offsets must not cause exponential overflow.

Example. Scores [1000, 1001, 999] return approximately [0.244728, 0.665241, 0.090031]. Scores [0, 0] return [0.5, 0.5], not raw exponentials [1, 1].

Picture

Subtract the row maximum : . Exponentials are approximately , with sum . Divide by that shared sum to obtain .

Problem trace

Separate three-logit row: subtract its maximum, exponentiate, normalize

Input and goalConvert logits to probabilities without numeric overflow.
Find the maximum logitFor logits [1000,1001,999], the row maximum is 1001. Direct exp(1001) can overflow.
10000max = 1001100119992
max
1
index 0
1000
index 1
1001

Recognize it
Use it when exponentials normalize scores into probabilities and large positive logits may overflow even though only relative differences should affect the result.
Keep true
Subtracting one constant from every row element leaves every exponential ratio unchanged; after max shifting, the largest exponent is exp(0)=1 and none can overflow.
Reuse it
Before exponentiating normalized scores, exploit shift invariance to center at the maximum; preserve the reduced dimension so broadcasting back across the row is explicit.
For logits [1000,1001,999], the row maximum is 1001. Direct exp(1001) can overflow. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does subtracting 1001 change the exponentials but not the ideal softmax probabilities?
Reference drawing

Problem trace

Subtracting a shared maximum changes exponentials without changing ideal probabilities

Worked example: subtracting the maximum preserves probabilities while preventing overflowLogits (1000,1001) shift to (-1,0). Their softmax probabilities are about 0.269 and 0.731 without exponentiating 1000.A common logit shift changesexponential scale, not probabilityshares1000-110010minus 1001Exponentiate the small shifted values0.2690.731Remove the common scale beforeexponentiation.
Execution trace
Input and goalConvert logits to probabilities without numeric overflow.
Find the maximum logitFor logits [1000,1001,999], the row maximum is 1001. Direct exp(1001) can overflow.
10000max = 1001100119992
max
1
index 0
1000
index 1
1001

Recognize it
Use it when exponentials normalize scores into probabilities and large positive logits may overflow even though only relative differences should affect the result.
Keep true
Subtracting one constant from every row element leaves every exponential ratio unchanged; after max shifting, the largest exponent is exp(0)=1 and none can overflow.
Reuse it
Before exponentiating normalized scores, exploit shift invariance to center at the maximum; preserve the reduced dimension so broadcasting back across the row is explicit.
For logits [1000,1001,999], the row maximum is 1001. Direct exp(1001) can overflow. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does subtracting 1001 change the exponentials but not the ideal softmax probabilities?
Read it this way: Logits (1000,1001) shift to (-1,0). Their softmax probabilities are about 0.269 and 0.731 without exponentiating 1000. Does adding another thousand to both original logits change their shifted difference or their probability shares?

Code

A common shift cancels from normalized ratios:

Taking makes every exponent argument nonpositive, with at least one exponential equal to one. Retain dimensions for row-wise broadcasting.

import numpy as np

def stable_softmax(logits: np.ndarray, axis: int = -1) -> np.ndarray:
   shifted = logits - np.max(logits, axis=axis, keepdims=True)
   exponentials = np.exp(shifted)
   return exponentials / np.sum(exponentials, axis=axis, keepdims=True)

Work, output and temporaries require for entries.

Change the output

1. Forbid selected alternatives

New task: forbidden entries must receive zero probability. Every row must contain an allowed entry.

Picture and change: validate the mask and allowed values before replacing forbidden scores by negative infinity.

Code:

def masked_softmax(logits, allowed, axis=-1):
   logits = np.asarray(logits, dtype=float)
   allowed = np.asarray(allowed, dtype=bool)
   if logits.shape != allowed.shape or not np.all(allowed.any(axis=axis)):
      raise ValueError("invalid visibility")
   if not np.all(np.isfinite(logits[allowed])):
      raise ValueError("nonfinite visible score")
   return stable_softmax(np.where(allowed, logits, -np.inf), axis=axis)

Check: mask gives approximately . A completely masked row raises an error rather than inventing probabilities.

Use when: attention or classification explicitly forbids alternatives.

2. Return log probabilities

New task: preserve useful log values when tiny probabilities underflow.

Picture and change: subtract the log normalizer directly, rather than taking logs of computed probabilities.

Code:

def stable_log_softmax(logits, axis=-1):
   logits = np.asarray(logits, dtype=float)
   shifted = logits - logits.max(axis=axis, keepdims=True)
   normalizer = np.exp(shifted).sum(axis=axis, keepdims=True)
   return shifted - np.log(normalizer)

Check: gives log probabilities in float64, although underflows.

Use when: losses or sequence scores consume log probabilities.

Check the axis and dtype

The wrong axis normalizes the wrong groups. Integer subtraction can overflow before exponentiation. Max shifting does not repair NaNs or a completely masked row.

Try subtracting the mean

Why does mean subtraction preserve exact ratios but offer less overflow protection?

Check your answer

Any common shift cancels algebraically. After mean subtraction, the largest exponent argument can remain positive. Maximum subtraction guarantees nonpositive arguments for valid finite arithmetic.

Numerical limits

The four-decimal trace probabilities sum to because of rounding. Test the full-precision result with a tolerance, not exact equality to rounded values. For a batch, verify every intended row sums to one and compare a column-normalized case separately.

Very large input differences can overflow subtraction even when both original values are finite. Low precision can erase small differences before this function receives the logits. Underflow of very small exponentials can still produce zero probabilities. The log variant avoids first forming those probabilities, but does not remove finite-range arithmetic limits.

Production libraries may fuse softmax or log-softmax with downstream operations. The NumPy temporary arrays establish no fused-kernel memory or speed claim.