Keep a softmax stable when the logits are huge
Compute a two-token distribution at logits 1000 and 1001, and see why subtracting the maximum is part of the algorithm, not a tidy-up.
Softmax is usually written as exp(x) / sum(exp(x)). That formula is correct in
real arithmetic and unusable in floating point when the logits are large:
exp(1000) overflows before the division ever happens. The stable form subtracts
the maximum logit from every value first. The probabilities are unchanged,
because the same factor cancels from numerator and denominator.
This example runs the stable path on logits 1000 and 1001. It also shows the
selection rules that sit on top of the distribution: top-k keeps the highest
logits, and top-p keeps the smallest set whose cumulative probability reaches the
threshold. The example does not use a model, so it isolates the numerical
mechanism from the quality of any generated text.
Run it
From the canonical repository at commit
f958967d70992d7b09d9c75000bd8c543f1644d4:
python examples/ch03/probability.py --logits 1000,1001 --jsonPython 3.11 or later, standard library only. No model, network, GPU or credentials are required; the command finishes immediately.
Implementation
stable_log_softmax shifts by the maximum, then computes the log-sum-exp in the
shifted space. top_p_indices sorts by probability, adds tokens until the
cumulative mass reaches p, and returns that set. The tie-break is the smaller
token index, which makes the output deterministic.
def stable_log_softmax(logits: Sequence[float]) -> List[float]:
if not logits:
raise ValueError("logits must not be empty")
maximum = max(logits)
shifted = [value - maximum for value in logits]
log_sum_exp = maximum + math.log(sum(math.exp(value) for value in shifted))
return [value - log_sum_exp for value in logits]
def softmax(logits: Sequence[float]) -> List[float]:
logs = stable_log_softmax(logits)
return [math.exp(value) for value in logs]
def top_k_indices(logits: Sequence[float], k: int) -> List[int]:
if isinstance(k, bool) or not isinstance(k, int):
raise ValueError("k must be an integer")
if k < 1:
raise ValueError("k must be positive")
if k > len(logits):
raise ValueError("k must not exceed the number of logits")
order = sorted(range(len(logits)), key=lambda i: (-logits[i], i))
return order[:k]
def top_p_indices(logits: Sequence[float], p: float) -> List[int]:
if isinstance(p, bool) or not isinstance(p, (int, float)):
raise ValueError("p must be a number")
if p <= 0 or p > 1:
raise ValueError("p must be in (0, 1]")
probs = softmax(logits)
order = sorted(range(len(logits)), key=lambda i: (-probs[i], i))
selected: List[int] = []
cumulative = 0.0
for index in order:
selected.append(index)
cumulative += probs[index]
if cumulative >= p:
break
return selectedExpected outcome
Observed with the command above (exit 0):
{
"logits": [
1000.0,
1001.0
],
"log_probabilities": [
-1.3132616875182066,
-0.3132616875182066
],
"probabilities": [
0.2689414213699995,
0.7310585786300168
],
"top_k_indices": [
1,
0
],
"top_p_indices": [
1,
0
],
"sampled_index": 1,
"metadata": {
"vocab": [
"0",
"1"
],
"temperature": 1.0,
"top_k": 2,
"top_p": 0.9,
"seed": 0
}
}The two probabilities sum to 1. The gap between logits is still 1, so the ratio
is e, and token 1 receives e / (1 + e) = 0.731.... Adding 1000 to both logits
did not change the distribution. The sampled index is 1 for seed 0; that is a
deterministic reproduction, not a claim about model quality.
Mechanism and limitations
Documented: the module raises on empty logits, invalid k, invalid p,
non-numeric p, and non-positive temperature. The tests check that probabilities
sum to one, that logits [1000, 1001] remain finite, top-k ordering, top-p
selection, invalid inputs and same-seed determinism. The chapter separately
records a float32 naive-softmax experiment on real GPT-2 logits where the
denominator became subnormal and the maximum probability error reached 0.303;
that is a recorded model measurement, not this two-token run.
Observed: the command exited 0 with the distribution above. The targeted
test tests.test_ch03_probability ran in a 36-test batch with Chapters 02, 04 and
05 and reported OK.
Not shown: that this distribution is calibrated, useful or representative of a model; that Python floats behave like float32 on a GPU; that top-p improves text quality; or that the tokeniser maps these two ids to meaningful words. The example is arithmetic and selection logic, not a language-model experiment.
Challenge this result
Compute the naive form directly in Python:
import math
logits = [1000.0, 1001.0]
exps = [math.exp(x) for x in logits]
print([x / sum(exps) for x in exps])Predict the exception before running it. Then repeat with logits [88.0, 89.0]
in float32 using struct.pack("f", ...) and find the point where the exponential
overflows. Explain why the stable form can still lose precision when one logit
dominates, and what a log-softmax output preserves that a probability does not.
Source and verification
Canonical source:
examples/ch03/probability.py
at commit f958967d70992d7b09d9c75000bd8c543f1644d4. Tests:
tests/test_ch03_probability.py
.
Chapter: Tokens, Embeddings and Probability
.
The run above is a fresh local execution on Windows 11 with Python 3.13.15; it
does not load a model.
Understand this example
Copy this prompt into your AI tool. No code runs here.
Apply this example
Copy this prompt into your AI tool. No code runs here.