Skip to main content
Core Pattern · Interactive Simmedium•DECEMBER 2026•8 MIN

Stable Softmax & Top-p Nucleus Sampling: Avoiding Overflow Before Sampling

Why raw exp(logits) overflows float32/float64, how max-subtraction fixes it, and how top-p truncates the tail.

log-sum-expnumerical stabilitytop-p samplingmlllmnumpy

The problem

Given an unnormalized logit vector x of shape (V,), temperature T > 0, and nucleus cutoff top_p in (0, 1], normalize x into a valid probability distribution and keep only the smallest prefix of highest-probability tokens whose cumulative mass reaches top_p.

Calling np.exp(x) directly fails in float32 above ~88 (and float64 above ~709), producing inf and NaN during softmax normalization.

Watch it run

Adjust Temperature and Top-p to see how subtracting m = max(logits) keeps every exponent ≤ 0, and how top_p dynamically masks tail tokens after sorting.

LOADING STABLE SOFTMAX & TOP-P SIM...

Reference implementation

import numpy as np

def sample_top_p(logits: np.ndarray, T: float = 1.0, top_p: float = 0.9) -> np.ndarray:
    m = np.max(logits)
    z = (logits - m) / T
    exps = np.exp(z)
    probs = exps / np.sum(exps)

    order = np.argsort(-probs)
    sorted_p = probs[order]
    cum_before = np.cumsum(sorted_p) - sorted_p
    kept = np.where(cum_before < top_p, sorted_p, 0.0)

    out = np.zeros_like(probs)
    out[order] = kept / np.sum(kept)
    return out

Key details

StepInvariantCommon Bug
Max-shiftx - max(x) ≤ 0, so exp(z) is in (0, 1]Calling exp(x) before subtracting max(x)
Exclusive cumsumCheck cum_before < top_p so the crossing token staysChecking cum <= top_p, which can drop all tokens when p[0] > top_p
RenormalizeDivide surviving probabilities by sum(kept)Sampling directly from unnormalized truncated weights

Related Lab Entries