Floating point, stability and log-sum-exp¶
Computers do not do real-number arithmetic; they do floating-point arithmetic, with a fixed budget of bits for range and precision. Most NaN losses, silent accuracy losses and "it diverged at step 40,000" bugs in AI come from a handful of predictable failure modes, and a handful of tricks (subtract the max, work in logs, accumulate in higher precision, scale the loss) prevent nearly all of them.
10,000 ft
Modern models are trained in 16-bit and increasingly 8-bit formats, and served in 8- and 4-bit ones, because fewer bits mean more FLOPs per second and less memory traffic (see mixed precision and quantisation). Fewer bits also mean every operation rounds more coarsely and overflows sooner. The mathematics on the rest of this track assumes exact real numbers; this page is about what changes when it runs on hardware. The central trick, log-sum-exp, is how softmax, cross-entropy, log-likelihoods and attention are computed without overflow, and its streaming form is the core of FlashAttention. The central idea, conditioning versus stability, tells you when a bad answer is the problem's fault and when it is the algorithm's.
2,000 ft
A float stores a sign, an exponent (which sets the range) and a mantissa (which sets the precision). Every operation rounds its result to the nearest representable number, with relative error at most the unit roundoff. Four things then go wrong, each with a standard fix:
Ground level¶
How a float is stored¶
An IEEE 754 binary float represents
a sign bit \(s\), an exponent field \(e\) and \(p\) mantissa bits (the leading 1 is implicit for normal numbers). It is scientific notation in base 2. The consequence that matters most: precision is relative, not absolute. Between each pair of consecutive powers of two there are the same number of representable values (\(2^p\)), so the gap between neighbouring floats grows in proportion to their size. Near 1.0 in FP32 the gap is \(2^{-23} \approx 1.2 \times 10^{-7}\) (machine epsilon); near \(10^6\) it is 0.0625; near \(10^{8}\) it is 8. Fabien Sanglard's "window and offset" picture (Go deeper) is the clearest way to see it.
Most decimal fractions are not representable. 0.1 in binary is
\(0.000110011001100\ldots\), recurring, so it is stored rounded: in FP64 as
0.10000000000000000555. That is why 0.1 + 0.2 == 0.3 is false in every language that uses
IEEE floats. It is not a bug; it is rounding, and you compare floats with a tolerance.
The formats that matter for AI, as of 2026:
| Format | Bits (sign / exponent / mantissa) | Largest value | Smallest normal | Machine epsilon | Typical use |
|---|---|---|---|---|---|
| FP64 | 1 / 11 / 52 | \(1.8 \times 10^{308}\) | \(2.2 \times 10^{-308}\) | \(2.2 \times 10^{-16}\) | Scientific computing; rarely in DL |
| FP32 | 1 / 8 / 23 | \(3.4 \times 10^{38}\) | \(1.2 \times 10^{-38}\) | \(1.2 \times 10^{-7}\) | Master weights, optimiser states, accumulators |
| BF16 | 1 / 8 / 7 | \(3.4 \times 10^{38}\) | \(1.2 \times 10^{-38}\) | \(7.8 \times 10^{-3}\) | Default training and inference format |
| FP16 | 1 / 5 / 10 | 65,504 | \(6.1 \times 10^{-5}\) | \(9.8 \times 10^{-4}\) | Older mixed precision (needs loss scaling) |
| FP8 E4M3 | 1 / 4 / 3 | 448 | \(2^{-6}\) | \(2^{-3}\) | Weights and activations in FP8 training |
| FP8 E5M2 | 1 / 5 / 2 | 57,344 | \(2^{-14}\) | \(2^{-2}\) | Gradients in FP8 training |
The FP64/FP32/FP16 numbers are NumPy's finfo (printed by the code below); BF16 follows from
its layout; the FP8 maxima are from Micikevicius et al. (2022).
BF16, the "brain floating-point" format from Google Brain, keeps FP32's eight exponent bits and
truncates the mantissa. It has FP32's range but only two to three significant decimal digits.
Kalamkar et al. (2019) showed it trains a wide range of
networks to FP32 accuracy without the loss-scaling machinery FP16 needs, which is why it became
the default.
The standard also defines subnormals (values below the smallest normal, with lost precision, which make underflow gradual), signed infinities for overflow, and NaN ("not a number") for undefined results like \(\infty - \infty\) or \(0/0\). NaN is contagious: any arithmetic with a NaN gives NaN, and a NaN compares unequal to everything, including itself. One NaN in one activation spreads to the loss, then to every gradient, then to every weight, in a single step.
Rounding, absorption and the accumulation problem¶
Every operation is rounded, with relative error at most the unit roundoff \(u\) (half of machine epsilon):
One rounding is harmless. The danger is when a small number is added to a large one. If \(|b|\) is below about \(u\,|a|\), then \(a + b\) rounds back to \(a\): the small number is absorbed. In FP16, \(1 + 10^{-4} = 1\). In BF16, \(1 + 10^{-3} = 1\), while \(1 + 5 \times 10^{-3}\) jumps to 1.0078125, the next representable value.
This is not academic. A weight of 1.0 in BF16 cannot be changed by an update of \(10^{-3}\), and typical updates are far smaller than that: learning rate \(3 \times 10^{-4}\) times a normalised gradient. Train with BF16 weights alone and most updates silently vanish. That is the reason mixed-precision training keeps an FP32 master copy of the weights and of the optimiser state, does the matrix multiplications in BF16, and applies updates to the FP32 copy (Micikevicius et al., 2017).
Accumulation is the same problem in a loop. Add 0.001 to an FP16 counter 10,000 times and the
answer is 4.0, not 10: once the counter reaches 4, the gap between FP16 numbers there is
\(4 \times 2^{-10} \approx 0.0039\), so an increment of 0.001 (less than half the gap) is rounded
away every time. Summing ten million copies of 0.1 left-to-right in FP32 gives 1,087,937 instead
of 1,000,000, a 9% error. NumPy's sum uses pairwise summation (add in a balanced tree, so
error grows like \(\log n\) rather than \(n\)) and gets 1,000,000.1. GPU matrix multiplication units
take BF16 or FP8 inputs but accumulate in FP32 for the same reason, and reductions such as
softmax denominators and LayerNorm statistics are computed in FP32 even inside "BF16" models.
Floating-point addition is not associative
\((a + b) + c\) and \(a + (b + c)\) can differ in the last bits. A parallel reduction on a GPU adds in an order that depends on the kernel, the batch size and the hardware, so the same model on the same input can give bitwise-different logits in different runs or batch configurations. Usually harmless; occasionally it flips a greedy decoding choice, and it is why "deterministic" training needs special flags and is slower.
Catastrophic cancellation¶
Subtracting two nearly equal numbers cancels their leading digits, leaving only the rounding errors behind. The textbook trap is the one-pass variance formula \(\operatorname{Var}(x) = \mathbb{E}[x^2] - (\mathbb{E}[x])^2\). For 100,000 FP32 values with mean \(10^4\) and standard deviation 1, both terms are about \(10^8\), where the FP32 spacing is 8, and their difference (the true answer, about 1) is pure noise: the code gets −8.0, a negative variance. Subtracting the mean first (two passes) gives 1.0003. Welford's algorithm does the same in a single streaming pass, and it or the two-pass form is what LayerNorm, BatchNorm and running-statistics code should use.
Related fixes are built into every maths library: log1p(x) computes \(\log(1 + x)\) accurately
for tiny \(x\) (where \(1 + x\) would round to 1), expm1(x) computes \(e^x - 1\), and losses are
computed from logits rather than from probabilities (below).
Overflow in softmax, and the log-sum-exp trick¶
\(e^{x}\) overflows FP32 for \(x > 88.7\), FP16 for \(x > 11.1\) and BF16 for \(x > 88.7\) (BF16 has FP32's range). Logits of a few hundred are not unusual. The naive softmax of \((1000, 1001, 1002)\) computes \(\infty / \infty\) = NaN. But softmax does not change if you subtract the same constant from every logit, so subtract the maximum \(m\):
Now the largest exponent is \(e^0 = 1\), nothing overflows, and at least one term of the denominator is 1, so it cannot underflow to zero either. The stable softmax of \((1000, 1001, 1002)\) is \((0.090, 0.245, 0.665)\), the same as the softmax of \((0, 1, 2)\).
The log of the denominator is the log-sum-exp function, and the same shift makes it stable:
It is everywhere, because every normalised log-probability needs it:
- Log-softmax is \(z_k - \operatorname{LSE}(\mathbf{z})\), computed without ever forming the probabilities.
- Cross-entropy from logits is \(\operatorname{LSE}(\mathbf{z}) - z_y\): 2.4076 nats for class 0
of the logits above. This is why
F.cross_entropytakes logits, not probabilities, and fuses the softmax inside. - Binary cross-entropy from logits is \(\operatorname{softplus}(z) - yz\) with \(\operatorname{softplus}(z) = \max(z, 0) + \log(1 + e^{-|z|})\). Computed from a sigmoid probability instead, a logit of 40 gives \(p = 1\) exactly in floating point, \(\log(1 - p) = -\infty\), and an infinite loss; from the logit, the loss is the correct 40.0.
- Mixture models, HMMs, CTC and beam search combine log-probabilities of alternative paths with LSE (the "log-space sum").
Underflow, and why everything lives in log space¶
A sequence of 1,000 tokens each predicted with probability 0.3 has joint probability \(0.3^{1000} \approx 10^{-523}\), which is zero in every float format. Its log is \(-1203.97\), an ordinary number. So sequence models never multiply probabilities: they add log-probabilities, and convert to probabilities only at the end, if at all. The same goes for likelihoods in estimation: you maximise the log-likelihood partly because it is the only version that survives contact with floating point.
Log-sum-exp as a smooth maximum¶
LSE has a second identity: it is a smooth, convex approximation of the max,
and its gradient is the softmax, \(\nabla \operatorname{LSE}(\mathbf{z}) = \operatorname{softmax}(\mathbf{z})\). With a temperature, \(\tau\,\operatorname{LSE}(\mathbf{z}/\tau) \to \max_j z_j\) as \(\tau \to 0\), and the softmax tends to the one-hot argmax. "Softmax" is really "soft argmax", and LSE is the soft max. This is why softmax attention is a differentiable lookup, why the logsumexp appears as the "free energy" in energy-based models, and why the convexity of cross-entropy in the logits (see optimisation) follows from the convexity of LSE.
Streaming softmax: the trick inside FlashAttention¶
Attention computes a softmax over a row of scores that may be hundreds of thousands long, and reading the whole row twice (once for the max, once for the sum) costs memory bandwidth. The online softmax of Milakov and Gimelshein (2018) does it in one pass: keep a running maximum \(m\) and a running sum \(\ell\) of \(e^{z - m}\); when a new block arrives with a larger maximum \(m'\), rescale the old sum by \(e^{m - m'}\) before adding the new terms. The result is exact. The code below processes 10,000 scores in 100 tiles and matches the two-pass LSE to all ten printed decimals. FlashAttention applies the same rescaling to the running weighted sum of value vectors, which lets it compute exact attention tile by tile in fast on-chip memory without ever materialising the full attention matrix.
Mixed precision in practice¶
Putting the pieces together, a modern training step looks like this:
- FP32 master weights are cast to BF16 (or FP8 with per-tensor scale factors) for the forward and backward matrix multiplications, which accumulate in FP32.
- Softmax, LayerNorm/RMSNorm statistics, the loss and its log-sum-exp run in FP32.
- With FP16 (not BF16), the loss is multiplied by a loss scale before the backward pass so that small gradients do not underflow below FP16's smallest subnormal (\(6 \times 10^{-8}\)), and the gradients are divided back before the update; the scale is lowered when an overflow (inf) is detected and the step is skipped.
- The optimiser updates the FP32 master weights with FP32 moment estimates.
FP8 training adds per-tensor (or finer-grained) scaling factors, chosen from recent maximum magnitudes, so that each tensor uses the narrow FP8 range well: E4M3 for weights and activations, E5M2 for gradients (Micikevicius et al., 2022). Large-magnitude outlier features in transformer activations are the main obstacle to low-precision formats, because one huge value forces a scale that crushes all the small ones (Dettmers et al., 2022).
Instabilities that only show up at scale¶
Some numerical problems are slow-motion: nothing overflows on step one, but a quantity drifts until something breaks. Two documented in large transformers:
- Output logit drift. The softmax is shift-invariant, so nothing in the loss stops all the logits from drifting upward together until the normaliser \(\log Z\) is large enough to lose precision. PaLM added an auxiliary z-loss, \(10^{-4} \cdot \log^2 Z\), to keep \(\log Z\) near zero (Chowdhery et al., 2022).
- Attention logit growth. Query–key dot products can grow during training until attention softmaxes saturate to one-hot and gradients vanish, followed by loss spikes or divergence. Normalising queries and keys (QK-LayerNorm) prevents it; Wortsman et al. (2023) reproduce both instabilities in small models and study the fixes.
Optimiser hyperparameters have numerical sides too. Adam divides by \(\sqrt{v} + \epsilon\) with a default \(\epsilon = 10^{-8}\); Wortsman et al. found that gradient magnitudes shrink with model scale until they approach \(\epsilon\), at which point \(\epsilon\) dominates the denominator and silently shrinks the updates. Lowering it to \(10^{-15}\) improved the loss of their 4.8B-parameter model. See optimisers and the training recipe.
Conditioning versus stability¶
When a computed answer is wrong, there are two possible culprits.
- The problem may be ill-conditioned: tiny changes in the input produce large changes in the exact answer. Solving \(A\mathbf{x} = \mathbf{b}\) has condition number \(\kappa(A) = \sigma_\text{max}/\sigma_\text{min}\); expect to lose about \(\log_{10}\kappa\) decimal digits of the \(\approx 7\) that FP32 gives you. No algorithm can do better.
- The algorithm may be unstable: it adds more error than the problem's conditioning forces. The one-pass variance and the naive softmax are unstable algorithms for well-conditioned problems.
The working rule is forward error ≲ condition number × backward error. A backward stable
algorithm gives the exact answer to a slightly perturbed problem (perturbation of order \(u\)), and
then the error you see is entirely the problem's fault. Classic consequences: never form an
explicit inverse to solve a linear system; never solve least squares through the normal
equations \(X^\top X\mathbf{w} = X^\top\mathbf{y}\) when \(X\) is ill-conditioned, because
\(\kappa(X^\top X) = \kappa(X)^2\) squares the damage (use QR or SVD, which np.linalg.lstsq does);
and when gradients explode or vanish in a deep network, ask first whether the function is
ill-conditioned (a product of many Jacobians) before blaming the arithmetic.
First principles¶
Why floating point at all? Quantities in a network span many orders of magnitude: gradients of \(10^{-8}\), activations of \(10^{2}\), logits of \(10^{3}\). Fixed-point numbers have constant absolute precision and would need very many bits to cover that span. Floating point gives constant relative precision over an enormous range with few bits, which matches how errors matter in most computations (a 0.1% error is equally acceptable at every scale). Integer formats come back for inference (quantisation) once the range of each tensor is known and can be handled with an explicit scale factor.
Why the standard is designed as it is. IEEE 754's choices each fix a failure mode. Round-to-nearest-even makes rounding errors unbiased on average, so they tend to cancel in long sums rather than drift. Subnormals make underflow gradual, so \(x - y = 0\) only when \(x = y\). Infinities and NaN let a computation continue and report a problem at the end instead of trapping. And the guarantee \(\operatorname{fl}(a \circ b) = (a \circ b)(1 + \delta)\) for the basic operations makes floating-point programs analysable: every error bound in numerical analysis is built from that one axiom.
Why the shift trick is exact. The softmax is invariant to adding a constant because exponentiation turns addition into multiplication, and the common factor cancels in the ratio. Choosing the constant to be \(-\max_j z_j\) is the unique choice that guarantees both no overflow (largest exponent is 0) and no total underflow (one term equals 1). It costs one extra pass, or none with the online form. Blanchard, Higham and Higham (2019) prove that the shifted formulas are accurate, not just overflow-free.
Why bits are a design variable. On current accelerators, halving the bits of each operand roughly doubles matrix-multiply throughput and halves memory traffic. Precision is therefore spent where it buys accuracy (accumulators, reductions, optimiser state, master weights) and saved where it does not (the bulk of the matrix multiplications). This trade, made per tensor, is what mixed precision and quantisation engineer in detail.
History¶
From the Z3 to FP8
Konrad Zuse's Z3 (1941) already computed in binary floating point. Through the 1970s every manufacturer had its own format and rounding rules, and numerical programs gave different answers on different machines. William Kahan led the effort that produced IEEE 754 in 1985 (he received the 1989 Turing Award for it); revisions followed in 2008 and 2019. David Goldberg's 1991 survey What Every Computer Scientist Should Know About Floating-Point Arithmetic became the standard introduction. For deep learning, NVIDIA's Volta GPUs (2017) introduced tensor cores for FP16 matrix multiplication with FP32 accumulation, the same year mixed-precision training with loss scaling was published; Google's TPUs popularised bfloat16; and Hopper GPUs (2022) added FP8 tensor cores.
The maths¶
Floating-point model
A binary format with \(p\) stored mantissa bits has machine epsilon \(\epsilon = 2^{-p}\) (the gap between 1 and the next float) and unit roundoff \(u = \epsilon/2\) under round-to-nearest. For any real \(x\) in the normal range, \(\operatorname{fl}(x) = x(1 + \delta)\) with \(|\delta| \le u\), and for \(\circ \in \{+, -, \times, \div\}\), \(\operatorname{fl}(a \circ b) = (a \circ b)(1 + \delta)\). The gap between consecutive floats near \(x\) is about \(\epsilon\,|x|\).
Error growth in summation
Summing \(n\) numbers left to right, the computed result \(\hat S\) satisfies
while pairwise (tree) summation replaces \(n - 1\) by \(\lceil\log_2 n\rceil\). Kahan's compensated summation carries the lost low-order bits in a second variable and achieves a bound of about \(2u\sum_i|x_i|\), independent of \(n\). For \(n = 10^7\) in FP32 the naive worst case is \(10^7 \times 6 \times 10^{-8} \approx 60\%\); the observed 9% is typical of systematic absorption once the running sum is large.
Cancellation
If \(\hat a = a(1 + \delta_a)\) and \(\hat b = b(1 + \delta_b)\) carry relative errors of size \(u\), then
which is huge when \(a \approx b\). The subtraction itself is exact (Sterbenz's lemma, when \(b/2 \le a \le 2b\)); it merely exposes errors already present. For the one-pass variance, \(|a| + |b| \approx 2 \times 10^8\) and \(|a - b| \approx 1\), so the relative error bound is about \(2 \times 10^8 \times 6 \times 10^{-8} = 12\): no correct digits.
Log-sum-exp and softmax identities
For \(\mathbf{z} \in \mathbb{R}^n\) and any constant \(c\):
- \(\operatorname{LSE}(\mathbf{z}) = c + \operatorname{LSE}(\mathbf{z} - c)\) and \(\operatorname{softmax}(\mathbf{z}) = \operatorname{softmax}(\mathbf{z} - c)\).
- \(\max_j z_j \le \operatorname{LSE}(\mathbf{z}) \le \max_j z_j + \log n\).
- \(\nabla\operatorname{LSE}(\mathbf{z}) = \operatorname{softmax}(\mathbf{z})\) and \(\nabla^2\operatorname{LSE}(\mathbf{z}) = \operatorname{diag}(\mathbf{p}) - \mathbf{p}\mathbf{p}^\top \succeq 0\) with \(\mathbf{p} = \operatorname{softmax}(\mathbf{z})\): LSE is convex, and that Hessian is the softmax Jacobian.
- \(\log\operatorname{softmax}(\mathbf{z})_k = z_k - \operatorname{LSE}(\mathbf{z})\); cross-entropy with label \(y\) is \(\operatorname{LSE}(\mathbf{z}) - z_y\).
- Binary case: \(\log\sigma(z) = -\operatorname{softplus}(-z)\) and \(\log(1 - \sigma(z)) = -\operatorname{softplus}(z)\), with \(\operatorname{softplus}(z) = \max(z, 0) + \log(1 + e^{-|z|})\).
Derivation: the online softmax recurrence
Process scores in blocks \(B_1, B_2, \dots\). After block \(t\) keep \(m_t = \max(\text{all scores so far})\) and \(\ell_t = \sum_{\text{scores so far}} e^{z - m_t}\). When block \(B_{t+1}\) arrives, set \(m_{t+1} = \max(m_t, \max B_{t+1})\). Every old term must be re-expressed relative to the new maximum: \(e^{z - m_{t+1}} = e^{z - m_t}\,e^{m_t - m_{t+1}}\), so
At the end \(\operatorname{LSE} = m_T + \log\ell_T\). Every exponent is \(\le 0\), so nothing overflows. For attention, also keep the unnormalised output \(\mathbf{o}_t = \sum e^{z - m_t}\mathbf{v}\) and rescale it by the same factor: \(\mathbf{o}_{t+1} = \mathbf{o}_t e^{m_t - m_{t+1}} + \sum_{B_{t+1}} e^{z - m_{t+1}}\mathbf{v}\). The final output is \(\mathbf{o}_T/\ell_T\). Because the rescaling factors compose multiplicatively, blocks can also be merged in any tree order, which is what lets the computation be split across thread blocks and devices.
Build it¶
Floats, absorption, accumulation and cancellation, measured:
import numpy as np
def bf16(x):
"""Round float32 values to bfloat16 (round-to-nearest-even) and back to float32."""
u = np.asarray(x, dtype=np.float32).view(np.uint32)
u = (u + 0x7FFF + ((u >> 16) & 1)) & 0xFFFF0000
return u.view(np.float32)
print("0.1 + 0.2 == 0.3 ?", 0.1 + 0.2 == 0.3, f" (0.1 is stored as {0.1:.20f})")
for name, t in [("float64", np.float64), ("float32", np.float32), ("float16", np.float16)]:
fi = np.finfo(t)
print(f"{name}: eps {fi.eps:.3e} max {fi.max:.3e} smallest normal {fi.smallest_normal:.3e}")
print(f"bfloat16: eps {2**-7:.3e} max {(2 - 2**-7) * 2.0**127:.3e} smallest normal {2.0**-126:.3e}")
# Updates smaller than half the spacing vanish
print("float16: 1 + 1e-4 =", np.float16(1) + np.float16(1e-4))
print("bf16 : 1 + 1e-3 =", bf16(np.float32(1) + np.float32(1e-3)), " 1 + 5e-3 =", bf16(np.float32(1) + np.float32(5e-3)))
# Accumulating many small numbers: low precision stalls, high-precision accumulators don't
acc16 = np.float16(0)
for _ in range(10_000):
acc16 = np.float16(acc16 + np.float16(0.001))
x32 = np.full(10_000_000, 0.1, dtype=np.float32)
print(f"sum of 10,000 x 0.001 in float16 running sum: {float(acc16)} (true 10)")
print(f"sum of 1e7 x 0.1: float32 sequential {np.add.accumulate(x32, dtype=np.float32)[-1]:.1f}, "
f"numpy pairwise {x32.sum(dtype=np.float32):.1f}, float64 {x32.sum(dtype=np.float64):.1f}")
# Catastrophic cancellation: variance via E[x^2] - E[x]^2 in float32
rng = np.random.default_rng(0)
x = (1e4 + rng.normal(size=100_000)).astype(np.float32)
one_pass = np.mean(x * x) - np.mean(x)**2
two_pass = np.mean((x - x.mean())**2)
print(f"variance (true ~1.0): one-pass {one_pass:.4f} two-pass {two_pass:.4f}")
0.1 + 0.2 == 0.3 ? False (0.1 is stored as 0.10000000000000000555)
float64: eps 2.220e-16 max 1.798e+308 smallest normal 2.225e-308
float32: eps 1.192e-07 max 3.403e+38 smallest normal 1.175e-38
float16: eps 9.766e-04 max 6.550e+04 smallest normal 6.104e-05
bfloat16: eps 7.812e-03 max 3.390e+38 smallest normal 1.175e-38
float16: 1 + 1e-4 = 1.0
bf16 : 1 + 1e-3 = 1.0 1 + 5e-3 = 1.0078125
sum of 10,000 x 0.001 in float16 running sum: 4.0 (true 10)
sum of 1e7 x 0.1: float32 sequential 1087937.0, numpy pairwise 1000000.1, float64 1000000.0
variance (true ~1.0): one-pass -8.0000 two-pass 1.0003
Stable softmax, log-sum-exp, losses from logits, and the online LSE:
import numpy as np
def softmax_naive(z):
e = np.exp(z)
return e / e.sum()
def logsumexp(z):
m = np.max(z)
return m + np.log(np.sum(np.exp(z - m)))
def softmax(z):
return np.exp(z - logsumexp(z))
z = np.array([1000.0, 1001.0, 1002.0])
with np.errstate(over="ignore", invalid="ignore"):
print("naive softmax :", softmax_naive(z))
print("stable softmax:", softmax(z).round(4), " log-sum-exp:", round(logsumexp(z), 4))
print("cross-entropy for class 0 from logits:", round(logsumexp(z) - z[0], 4))
# Binary cross-entropy: from probabilities vs from logits
def bce_from_prob(z, y):
p = 1 / (1 + np.exp(-z))
return -(y * np.log(p) + (1 - y) * np.log(1 - p))
def bce_from_logits(z, y): # = softplus(z) - y*z, computed stably
return np.maximum(z, 0) - y * z + np.log1p(np.exp(-np.abs(z)))
with np.errstate(divide="ignore"):
for zz in [5.0, 40.0]:
print(f"z={zz}, y=0: BCE from probability {bce_from_prob(zz, 0.0):.6f} from logits {bce_from_logits(zz, 0.0):.6f}")
# A product of many probabilities underflows; a sum of logs does not
p = np.full(1000, 0.3)
print("prod of 1000 x 0.3:", np.prod(p), " sum of logs:", round(np.log(p).sum(), 2))
# Online (streaming) log-sum-exp: one pass, running max, rescale -- the core of FlashAttention
rng = np.random.default_rng(0)
s = rng.normal(scale=30, size=10_000)
m, acc = -np.inf, 0.0
for block in np.split(s, 100): # process 100 tiles of 100 scores
m_new = max(m, block.max())
acc = acc * np.exp(m - m_new) + np.exp(block - m_new).sum()
m = m_new
print(f"online LSE {m + np.log(acc):.10f} two-pass LSE {logsumexp(s):.10f}")
naive softmax : [nan nan nan]
stable softmax: [0.09 0.2447 0.6652] log-sum-exp: 1002.4076
cross-entropy for class 0 from logits: 2.4076
z=5.0, y=0: BCE from probability 5.006715 from logits 5.006715
z=40.0, y=0: BCE from probability inf from logits 40.000000
prod of 1000 x 0.3: 0.0 sum of logs: -1203.97
online LSE 104.4564235432 two-pass LSE 104.4564235432
Things to try
- Implement Kahan summation and sum ten million FP32 copies of 0.1 with it. How close do you get, and how does it compare with NumPy's pairwise sum?
- Simulate a BF16-only optimiser: keep weights in
bf16(...), apply updates of size \(10^{-4}\) for 1,000 steps to a weight of 1.0, and compare with an FP32 master copy. Then try stochastic rounding (round up with probability proportional to the remainder): does the BF16-only weight now drift correctly on average? - Compute the condition number of the design matrix for the degree-7 polynomial on
the estimation page with
np.linalg.cond, then of \(X^\top X\). Solve both ways in FP32 and compare the error. - Write a one-pass Welford variance and check it against the two-pass result on the mean-\(10^4\) data.
Common misconceptions¶
- "FP32 is exact enough that I can ignore this." Absorption and cancellation happen at any precision; FP32 only moves the threshold. The ten-million-term sum above was FP32.
- "BF16 is just a worse FP16." It trades precision for range. For training, range is the scarcer resource (gradients and activations span many orders of magnitude), which is why BF16 usually wins and needs no loss scaling.
- "NaN means a bug in the model." Often it means an overflow: a softmax or exp without a shift, a log of zero, a division by a variance that cancelled to zero, or a loss scale that is too high. Check those before rewriting the architecture.
- "
log(softmax(z))is fine." It can return \(-\infty\) when a probability underflows to 0. Uselog_softmax, which computes \(z - \operatorname{LSE}(z)\) directly.
Check yourself¶
What is the largest x for which exp(x) is finite in FP16, and why does that matter for attention?
\(\ln 65504 \approx 11.09\). Attention scores \(\mathbf{q}^\top\mathbf{k}/\sqrt{d}\) easily exceed 11, so an FP16 softmax without the max-subtraction overflows. Attention kernels always subtract the row maximum (and usually compute the softmax in FP32).
In BF16, what is the smallest positive δ such that 1 + δ ≠ 1? What about 1024 + δ?
Machine epsilon is \(2^{-7} = 0.0078125\); with round-to-nearest, any \(\delta\) larger than half of that, \(2^{-8} \approx 0.0039\), rounds up to \(1 + 2^{-7}\) (exactly half rounds to even, i.e. down). Near 1024 the gap is \(1024 \times 2^{-7} = 8\), so \(\delta\) must exceed 4.
Show that the stable softmax cannot produce a zero denominator.
After subtracting \(m = \max_j z_j\), the term with \(z_j = m\) is \(e^0 = 1\) and all others are non-negative, so the denominator is at least 1.
Why does mixed-precision training keep FP32 master weights even though all matrix multiplications are in BF16?
Updates are typically much smaller than the BF16 spacing around the weight (about \(0.4\%\) of the weight's magnitude), so applying them in BF16 would round most of them away. Accumulating updates in FP32 preserves them; the BF16 copy used for compute is re-derived from the master copy each step.
A 70-billion-parameter model's loss spikes and then goes to NaN late in training. List three numerical suspects and how you would check each.
(1) Attention logit growth: log the maximum pre-softmax attention score per layer; fix with QK-normalisation. (2) Output logit drift: log \(\log Z\) of the output softmax; fix with z-loss. (3) Optimiser state: tiny second-moment estimates making Adam steps huge (check the update norm per layer; raise \(\epsilon\) or clip). Also check for inf/NaN in gradients before the optimiser step, and whether the spike follows particular data batches.
Hard: why is the error of computing LSE by shifting with the max essentially independent of the logits' magnitudes, while the naive formula is not?
After the shift, all exponents are in \((-\infty, 0]\), the sum is in \([1, n]\), and its log is in \([0, \log n]\): every intermediate is an ordinary-sized number, rounded with relative error \(u\). The final addition of \(m\) is a single rounding. The naive formula's intermediates \(e^{z_j}\) scale with the logits and leave the representable range entirely (overflow to \(\infty\) or underflow to 0), which no amount of relative accuracy can repair. Blanchard, Higham and Higham give the formal bound.
Go deeper¶
Papers
- What Every Computer Scientist Should Know About Floating-Point Arithmetic — Goldberg, 1991. The classic; read the sections on rounding error and the IEEE standard.
- Mixed Precision Training — Micikevicius et al., 2017. FP32 master weights, FP32 accumulation and loss scaling.
- A Study of BFLOAT16 for Deep Learning Training — Kalamkar et al., 2019. Why BF16's range makes loss scaling unnecessary.
- FP8 Formats for Deep Learning — Micikevicius et al., 2022. E4M3 and E5M2, defined and tested.
- Online normalizer calculation for softmax — Milakov and Gimelshein, 2018. The one-pass softmax that FlashAttention builds on.
- FlashAttention — Dao et al., 2022. Online softmax plus tiling: exact attention without the N² matrix in memory.
- Accurate Computation of the Log-Sum-Exp and Softmax Functions — Blanchard, Higham and Higham, 2019. Error analysis proving the shifted formulas are accurate.
- Small-scale proxies for large-scale Transformer training instabilities — Wortsman et al., 2023. Attention-logit growth and output-logit divergence, reproduced and fixed.
Videos
- Floating Point Numbers — Computerphile. A gentle introduction to why 0.1 + 0.2 is not 0.3.
Articles and tools
- Floating Point Visually Explained — Fabien Sanglard, 2017. Exponent as window, mantissa as offset.
- What Is the Log-Sum-Exp Function? — Nick Higham, 2021. A short, authoritative note on LSE and its stable evaluation.
- The Log-Sum-Exp Trick — Gregory Gundersen, 2020. The derivation with a worked example.
- Float Toy — Evan Wallace. Flip the bits of FP16/FP32/FP64 numbers and watch the value change.
- Numerical accuracy — PyTorch documentation. TF32, reduced-precision reductions and non-determinism in practice.
Books
- Accuracy and Stability of Numerical Algorithms — Nicholas Higham, 2nd edition, SIAM, 2002. The reference for error analysis: summation, cancellation, backward stability.
- Deep Learning, chapter 4 — Goodfellow, Bengio and Courville. Numerical computation for ML, including overflow, underflow and conditioning.
Where this leads¶
- Mixed precision: FP32, BF16, FP8 — the engineering of reduced-precision training.
- Quantisation: INT8, INT4, GPTQ, AWQ — integer formats with explicit scales, for inference.
- KV cache, FlashAttention, MQA/GQA/MLA — the online softmax at the heart of fast attention.
- A recipe for training (and debugging) networks — where NaNs and loss spikes are diagnosed in practice.
- Statistics for experiments and evals — the other kind of noise: not rounding, but sampling.