Numerical computing for ML: floating point, precision formats, stable softmax

Reading: 40 min, plus 9 in closed details. How a computer stores a number, bit by bit, and what that does to training: IEEE 754, epsilon and rounding, the formats ML uses (float64 to FP8), cancellation and conditioning, summation error and non-deterministic reductions, the stable softmax and its relatives, mixed precision and loss scaling, and hunting NaNs. Measured on a laptop and on a real model (SmolLM2-135M). A child page of Topic: math. Data as of October 2026.

The idea in one screen

A computer stores a real number as a sign, a power of two and a fixed number of binary digits. So it can only hold numbers from a finite grid: the grid is dense near zero and sparse far away, every result is snapped to the nearest grid point, and the grid ends (past it lies infinity). Exponent bits buy range; mantissa bits buy precision. Everything on this page follows from that picture: why 0.1+0.2≠0.30.1 + 0.2 \ne 0.3, why softmax needs the max subtracted, why fp16 training needs loss scaling and bf16 does not, why adding a million numbers in 16 bits returns garbage, and why the same model gives different answers on different runs.

The one idea to keep
Every floating-point result is the true result times (1+δ)(1 + \delta) with |δ||\delta| at most half the format's epsilon, as long as nothing overflows or underflows. Trouble comes from three places only: leaving the range (overflow to infinity, underflow to zero), subtracting nearly equal numbers (cancellation), and piling up many small errors (long sums). Stable algorithms are rearrangements that avoid all three.

Exponent bits set the range, mantissa bits set the gap

Top: every format's bits to scale (sign, exponent, mantissa). Bottom: the magnitudes it can hold on one log axis, pale where numbers are subnormal, solid where normal, ending at the largest value; ε\varepsilon is the relative gap. bfloat16 keeps float32's range with only 7 mantissa bits; float16 has 3 more mantissa bits but stops at 65,504, while SmolLM2-135M's median gradient (dashed line, measured in section 9) already sits in its subnormal zone. Derived from the bit layouts.

You need: nothing beyond calculus. The running example is the root page's tiny model (Topic: math): logits z=(2,1,0)z = (2, 1, 0) for the words cat, dog and sat, target sat, loss 2.4082.408; and the same three words with logits (1000,999,0)(1000, 999, 0), the case the root's Gradient lab uses for overflow. The condition number of a matrix is Linear algebra's; 8- and 4-bit formats for serving, block scaling and FP8 training recipes are Quantization and precision's; this page owns the arithmetic underneath them.

ulp
the gap between a float and its neighbour: the value of the last stored bit.
ε\varepsilon, uu
machine epsilon (the gap above 1) and unit roundoff u=ε/2u = \varepsilon/2, the worst relative error of one rounding.
Subnormal
a number below the smallest normal one, kept with fewer significant bits (gradual underflow).
Cancellation
subtracting nearly equal numbers, which leaves only their earlier rounding errors.
Condition number κ\kappa
how much a problem amplifies a relative error in its input, whatever the algorithm.
Log-sum-exp
ln⁡∑jezj\ln\sum_j e^{z_j}, computed after subtracting the largest zz.
Kahan summation
a running sum plus a second number that carries what each addition lost.
Loss scaling
multiplying the loss by SS so float16 gradients stay above underflow, dividing by SS before the update.
Batch invariance
a kernel whose result for one row does not depend on what else is in the batch.
IdeaIn one lineOne number to rememberWhere ML meets it
Floating pointsign, exponent (range), mantissa (precision)loss 2.4082.408 in fp32 is 0 10000000 0011010...every tensor
Machine epsilon, roundingrelative gap between neighbours; results round to the nearest, ties to evenfp32 2−23≈1.19×10−72^{-23} \approx 1.19 \times 10^{-7}; bf16 2−7=0.00782^{-7} = 0.0078what "precision" means
ML formatstrade mantissa bits for speed and memory; exponent bits decide the rangefp16 max 65,50465{,}504; bf16 max 3.4×10383.4 \times 10^{38}training and serving dtypes
Cancellationsubtracting nearly equal numbers leaves only the rounding errorone-pass fp32 variance of three numbers: −8-8variance, log near 1, norms
Summationadding in a different order gives a different answer; long sums driftfp16 running sum of ones stops at 20482048reductions, accumulators
Determinismparallel hardware changes the order, so results changeMPS index_add_: 20 different results in 20 runsreproducibility, batch invariance
Stable softmaxsubtract the max logit first; work in logsln⁡∑ez=1000.313\ln\sum e^{z} = 1000.313 for (1000,999,0)(1000, 999, 0)every classifier and LLM
Stable toolboxlog1p, expm1, logsigmoid, BCE with logits, Welford, epsilonnaive log⁡(1−σ(30))\log(1 - \sigma(30)) in fp32: −∞-\inftylosses, norms
Mixed precision16-bit compute, fp32 master weights; scale the loss in fp16SmolLM2 in pure fp16: 8.2% of gradients become 0training recipes
NaN huntingfind the first operation that made inf or NaN∞/∞=\infty / \infty = NaNdebugging divergence

The Float explorer tab shows any number's bits, neighbours and rounding error in seven formats, with bits you can flip; use it alongside sections 1 to 3.

How numbers are labelled, and how they were checked

Measured: run on an Apple M1 Pro (PyTorch 2.14.1, NumPy 2.5.3) or on one real training step of SmolLM2-135M by the scripts in src/inputs/. Derived: computed from a formula shown next to it. Published: quoted from a specification, paper or library source, linked. Bit patterns are computed, never typed by hand: NumPy, Python's struct and ml_dtypes 0.6.0, and this page's own emulator, which matches ml_dtypes on 17,610 test values.

1. A float, bit by bit

In binary each place is worth twice the place to its right, and places after the point are worth 12,14,18,…\tfrac12, \tfrac14, \tfrac18, \dots. A fraction has a finite binary expansion only if its denominator is a power of two, so 0.1=0.0001120.1 = 0.0\overline{0011}_2 repeats forever and any fixed number of bits must cut it off: that is why 0.1+0.20.1 + 0.2 prints as 0.30000000000000004 in Python (measured). ML needs 3×10−83 \times 10^{-8} (a small gradient) and 5×1045 \times 10^{4} (a large activation) in the same tensor; an evenly spaced grid fine enough for the first needs about 101210^{12} steps, about 41 bits, to reach the second. So numbers are stored in base-2 scientific notation, x=(−1)s×m×2Ex = (-1)^{s} \times m \times 2^{E} with 1≤m<21 \le m \lt 2: 13=11012=1.1012×23=1.625×813 = 1101_2 = 1.101_2 \times 2^{3} = 1.625 \times 8. The point "floats" to just after the first 1, and every number carries the same number of significant bits whatever its size: the gaps between neighbours grow in proportion to the number.

Integers and two's complement (for quantised codes and index overflow)

An unsigned 8-bit integer holds 00 to 28−1=2552^8 - 1 = 255. For negative numbers every modern machine uses two's complement: the top bit is worth −27=−128-2^{7} = -128 instead of +128+128, so int8 holds −128-128 to 127127 and −13=111100112=−128+64+32+16+2+1-13 = 11110011_2 = -128 + 64 + 32 + 16 + 2 + 1. Adding uses the same circuit as unsigned addition, and negating is "flip every bit, add 1" (13=00001101213 = 00001101_2, flipped 11110010211110010_2, plus one 11110011211110011_2). The price is that integers wrap around: in int8, 127+1=−128127 + 1 = -128 (derived; NumPy does the same and warns). Integers are exact inside their range and evenly spaced, which is why quantised weights are stored as int8 or int4 codes with a separate scale (Quantization and precision). Token ids, counts and quantised codes are integers; wraparound appears in practice when an int32 index overflows past 231−1≈2.1×1092^{31} - 1 \approx 2.1 \times 10^{9} elements, the size of a single large embedding or attention tensor.

IEEE 754 float32: three fields

The standard that fixes every bit is IEEE 754 (1985, revised 2008 and 2019: IEEE 754-2019; William Kahan, its main architect, received the 1989 Turing Award). Before it, every computer maker rounded differently. A 32-bit float (float32, fp32) is:

sign: 1 bitexponent field: 8 bitsfraction (mantissa) field: 23 bits
x=(−1)s×(1+f223)×2e−127(1≤e≤254)x = (-1)^{s} \times \Bigl(1 + \frac{f}{2^{23}}\Bigr) \times 2^{\,e - 127} \qquad (1 \le e \le 254)
ss
the sign bit: 0 for positive, 1 for negative.
ee
the 8-bit biased exponent, read as an unsigned integer 0 to 255; the true exponent is E=e−127E = e - 127, and 127 is the bias (28−1−12^{8-1} - 1). Storing E+127E + 127 makes positive floats sort like their bit patterns, so hardware compares floats with integer comparisons.
ff
the 23-bit fraction, an integer 0 to 223−12^{23} - 1. The leading 1 is not stored (the hidden bit), so float32 carries p=24p = 24 significant bits, its precision.

The loss, by hand. The exact loss ln⁡(e2+e1+e0)=2.40760596444438…\ln(e^2 + e^1 + e^0) = 2.40760596444438\ldots lies between 2 and 4, so E=1E = 1 and e=128=100000002e = 128 = 10000000_2. The significand is 1.2038…1.2038\ldots; its fractional part times 2232^{23} is 1,709,622.6…1{,}709{,}622.6\ldots, which rounds to f=1,709,623f = 1{,}709{,}623. Read back, 1.2038029432296753×2=2.40760588645935061.2038029432296753 \times 2 = 2.4076058864593506: off by 7.8×10−87.8 \times 10^{-8}, a relative error of 3.2×10−83.2 \times 10^{-8}. struct.pack('>f', loss).hex() gives 401a1637, the same 32 bits (measured). The card does the same for other values and formats:

Decode a number: the bits, then the formula read back

Four kinds of bit pattern

The two extreme exponent fields are reserved. Every ML bug involving NaN starts in this table:

Exponent field eeFraction ffMeaningValue (float32)
1 to 254anythingnormal±(1+f/223)×2e−127\pm(1 + f/2^{23}) \times 2^{e-127}: from 2−126≈1.18×10−382^{-126} \approx 1.18 \times 10^{-38} to (2−2−23)×2127≈3.40×1038(2 - 2^{-23}) \times 2^{127} \approx 3.40 \times 10^{38}
00zero+0+0 or −0-0: two zeros, equal when compared; 1/(−0)=−∞1/(-0) = -\infty
0not 0subnormal (denormal)±(f/223)×2−126\pm (f/2^{23}) \times 2^{-126}: no hidden 1, so fewer significant bits; down to 2−149≈1.4×10−452^{-149} \approx 1.4 \times 10^{-45}
2550infinity±∞\pm\infty: the result of overflow, or of 1/01/0
255not 0NaN ("not a number")the result of 0/00/0, ∞−∞\infty - \infty, 0×∞0 \times \infty, −1\sqrt{-1}, ln⁡(−1)\ln(-1); any operation on a NaN gives NaN, and NaN is not equal even to itself

Subnormals make numbers fade to zero in equal steps of 2−1492^{-149} (gradual underflow), so x−y=0x - y = 0 only when x=yx = y (Goldberg 1991, "Denormalized Numbers"); without them the gap between 0 and 2−1262^{-126} would be 2232^{23} times wider than the gap just above it. The price: 10−4010^{-40} in float32 keeps only 17 significant bits. NaN spreads (one NaN in a matrix multiply's input makes every output that touches it NaN) and compares false with everything, so loss > 10 is false for a NaN loss and a divergence check written that way never fires: use not torch.isfinite(loss). In a tensor dump, 7fc00000 is a NaN and 7f800000 is +∞+\infty; torch.finfo(torch.float32) prints the constants (eps, max, smallest_normal, tiny).

Hardware that flushes subnormals to zero

Some hardware drops subnormals for speed (flush to zero): Google's TPU blog says "bfloat16 handles denormals differently from FP32: it flushes them to zero" (Wang and Kanwar 2019), and PyTorch's notes say AMD MI200's FP16 and BF16 matrix instructions "flush input and output denormal values to zero" (numerical accuracy notes, v2.14.1). On such hardware the bottom of the range is 2−1262^{-126}, not 2−1332^{-133} (bfloat16's smallest subnormal).

2. Gaps between floats, machine epsilon and rounding

Between two consecutive powers of two, 2E2^E and 2E+12^{E+1} (one binade), a format with pp significant bits has exactly 2p−12^{p-1} evenly spaced values, so the gap there, one ulp ("unit in the last place"), is the value of the last stored bit. For float32 it is 2−232^{-23} between 1 and 2 and 2−13≈1.2×10−42^{-13} \approx 1.2 \times 10^{-4} between 1024 and 2048: float32 can tell 1000.0 from 1000.0001 but not from 1000.00001. Below the smallest normal number the spacing stops shrinking (subnormals are evenly spaced). FP8 E4M3 (p=4p = 4: 8 values per binade) is small enough to draw every value:

ulp⁡(x)=2E−(p−1)for 2E≤|x|<2E+1.\operatorname{ulp}(x) = 2^{\,E - (p - 1)} \quad \text{for } 2^E \le |x| \lt 2^{E+1} .

Machine epsilon ε=2−(p−1)\varepsilon = 2^{-(p-1)} is the gap between 1 and the next float. The unit roundoff u=ε/2=2−pu = \varepsilon / 2 = 2^{-p} is the largest relative error of one rounding: libraries report ε\varepsilon (torch.finfo(...).eps, C's FLT_EPSILON), numerical analysis texts write uu (Higham 2002, chapter 2), and mixing them up is a factor of two. pp bits are about 0.301p0.301\,p decimal digits: float64 about 16, float32 about 7.2, float16 about 3.3 and bfloat16 about 2.4 (derived). bfloat16 cannot tell 256 from 257: both round to 256. An update, a residual or a loss difference smaller than ε\varepsilon times the value it is added to is invisible, which is also why test tolerances (torch.testing.assert_close) are set from the dtype's ε\varepsilon.

The grid doubles its spacing every power of two

Every non-negative FP8 E4M3 value up to 16 (ticks), with the gap under each binade. Left of 2−6=0.01562^{-6} = 0.0156 the subnormals are evenly spaced (2−92^{-9} apart); each binade after that has 8 values and twice the previous spacing. The formats you train with have the same shape with many more points. Drawn from the format's definition by this page's emulator.
Why one rounding costs at most uu relative error, checked on the loss

Take xx with 2E≤|x|<2E+12^E \le |x| \lt 2^{E+1}. Neighbouring floats there are 2E−p+12^{E-p+1} apart, so the nearest one is at most half that away: |fl⁡(x)−x|≤2E−p|\operatorname{fl}(x) - x| \le 2^{E-p}. Divide by |x|≥2E|x| \ge 2^E:

|fl⁡(x)−x||x|≤2E−p2E=2−p=u.\frac{|\operatorname{fl}(x) - x|}{|x|} \le \frac{2^{E-p}}{2^{E}} = 2^{-p} = u .

Here fl⁡(x)\operatorname{fl}(x) means "xx rounded to the format". Check on the loss: float32 3.2×10−8≤u=5.96×10−83.2 \times 10^{-8} \le u = 5.96 \times 10^{-8}; float16 2.4082031252.408203125, error 2.5×10−4≤2−11=4.9×10−42.5 \times 10^{-4} \le 2^{-11} = 4.9 \times 10^{-4}; bfloat16 2.406252.40625, error 5.6×10−4≤2−8=3.9×10−35.6 \times 10^{-4} \le 2^{-8} = 3.9 \times 10^{-3} (all derived from the bits). In the subnormal range the bound fails: the absolute error is at most half the smallest subnormal, and the relative error can reach 100%.

Round to nearest, ties to even

IEEE 754 requires every basic operation (+,−,×,÷, +, -, \times, \div, \sqrt{\ } and the fused multiply-add) to be exactly rounded: computed as if with infinite precision, then rounded once. The default mode is round to nearest, ties to even: on an exact tie, pick the neighbour whose last bit is 0, which avoids the upward drift of ties away from zero. Measured:

SumNeighboursResultWhy
float16 1+2−111 + 2^{-11}11 and 1+2−101 + 2^{-10}11exactly halfway; 1 has last bit 0 (even)
float16 1+3⋅2−111 + 3 \cdot 2^{-11}1+2−101 + 2^{-10} and 1+2−91 + 2^{-9}1.0019531251.001953125halfway; 1+2−91 + 2^{-9} is the even one, so the tie goes up
bfloat16 1+2−81 + 2^{-8}11 and 1+2−71 + 2^{-7}11halfway, ties to even: the addition is lost entirely

The last row is why bf16 weights need help: any update smaller than half an ulp of the weight disappears, every time (section 9 measures how often on a real model). Stochastic rounding is the alternative: if xx sits a fraction tt of the way from aa to the next float bb, return bb with probability tt, so 𝔼[SR⁡(x)]=(1−t)a+tb=x\mathbb{E}[\operatorname{SR}(x)] = (1 - t)a + tb = x. Example (derived): a bfloat16 weight 0.1070.107 sits where the gap is 2−11≈0.0004882^{-11} \approx 0.000488; an update of 10−410^{-4} is 0.2050.205 of a gap, so nearest rounding never moves the weight, while stochastic rounding moves it one gap up about one step in five, and after 1,000 updates it has moved about 0.10.1 in expectation, as it should. The same property moves a block-scaled tensor between block layouts without bias: when a 4-bit forward value must be regrouped under a new block scale for the backward pass, a stored 4.54.5 that becomes 2.252.25 units of the new scale is rounded by nearest to 22 (so 44) every time, but stochastically to 22 three times in four and 33 once, 4.54.5 on average (Thinking Machines' end-to-end 4-bit recipe; the mechanism is on Quantization and Precision, section 6, and the evidence judged on End-to-End 4-Bit Training).

Where stochastic rounding is used

Gupta et al. trained networks with 16-bit fixed point "when using stochastic rounding" (Gupta et al. 2015); Zamirai et al. used it, and Kahan summation (section 5), to train in bf16 alone (Zamirai et al. 2020); NVIDIA's 4-bit pretraining recipe uses it on gradients "for unbiased gradient estimation" (NVIDIA 2025).

3. The formats ML uses

Every format is the same recipe with different field widths (the hero draws them; the stage below builds each from float32, bit by bit). Fewer bits per number means less memory, less traffic and more arithmetic per second on the same chip, which is why each GPU generation added a narrower format. All limits below are computed from the bit layouts by recompute.py and agree with NumPy, ml_dtypes and the specifications cited.

Formatsign / exp / mantissabiasε\varepsilonlargestsmallest normalsmallest subnormaleze^{z} overflows atFirst defined
float641 / 11 / 5210232.2×10−162.2 \times 10^{-16}1.8×103081.8 \times 10^{308}2.2×10−3082.2 \times 10^{-308}4.9×10−3244.9 \times 10^{-324}709.78IEEE 754-1985 (2019 edition)
float321 / 8 / 231271.19×10−71.19 \times 10^{-7}3.40×10383.40 \times 10^{38}1.18×10−381.18 \times 10^{-38}1.4×10−451.4 \times 10^{-45}88.72IEEE 754-1985
TF321 / 8 / 101279.8×10−49.8 \times 10^{-4}3.40×10383.40 \times 10^{38}1.18×10−381.18 \times 10^{-38}n/a88.72NVIDIA A100, 14 May 2020 (Ampere in depth)
float161 / 5 / 10159.8×10−49.8 \times 10^{-4}65,50465{,}5046.1×10−56.1 \times 10^{-5}6.0×10−86.0 \times 10^{-8}11.09IEEE 754-2008 (binary16)
bfloat161 / 8 / 71277.8×10−37.8 \times 10^{-3}3.39×10383.39 \times 10^{38}1.18×10−381.18 \times 10^{-38}9.2×10−419.2 \times 10^{-41}88.72Google Brain for TPUs (blog, Aug 2019)
FP8 E4M31 / 4 / 370.1250.1254484480.01560.01560.001950.001956.10Micikevicius et al., Sep 2022; OCP OFP8 rev. 1.0, approved 20 Jun 2023
FP8 E5M21 / 5 / 2150.250.2557,34457{,}3446.1×10−56.1 \times 10^{-5}1.5×10−51.5 \times 10^{-5}10.96same two documents

ε=2−m\varepsilon = 2^{-m} for mm mantissa bits. "Largest" is (2−2−m)×2Emax⁡(2 - 2^{-m}) \times 2^{E_{\max}} for the IEEE-style formats and (2−2−(m−1))×28=448(2 - 2^{-(m-1)}) \times 2^{8} = 448 for E4M3, whose top exponent holds numbers (only S.1111.111 is NaN, and there is no infinity: OFP8 spec, table 2). "eze^z overflows at" is ln⁡\ln of the largest value: the logit above which a naive softmax returns infinity (709.78, 88.72, 11.09). TF32 is a compute mode, not a storage type: tensors stay float32 in memory, and the tensor core reads "the first 10 bits of the input mantissa" (PyTorch notes, v2.14.1).

Each format's gap grows one step per binade, then the line stops at its largest value

Gap against the size of the number, both on log scales. Each line is flat at the left in the subnormal range (absolute precision constant), then climbs one step per binade (relative precision constant). bfloat16 and float32 cover the same range; bfloat16 sits 2162^{16} higher, its gaps 65,536 times wider. float16 is as precise as TF32 but stops at 65,504. Derived from the bit layouts.
  • float64 is NumPy's default and this page's reference; GPUs built for ML run it slowly or not at all on tensor cores, so training never uses it.
  • float32 is PyTorch's default dtype and the format of master weights, optimiser state and accumulators in mixed-precision training (section 9).
  • TF32: "an 8-bit exponent (same as FP32), 10-bit mantissa (same precision as FP16), and 1 sign-bit" for matrix multiplies on NVIDIA Ampere and later (NVIDIA, May 2020). In PyTorch 2.14.1 it is off by default for matrix multiplies (details below).
  • float16 has 3 more mantissa bits than bfloat16 but only 5 exponent bits: it overflows at 65,504 and turns anything below 6×10−86 \times 10^{-8} into 0, hence loss scaling (section 9).
  • bfloat16 is float32 with the last 16 bits cut off, so conversion is a shift (Kalamkar et al. 2019). Google's reasoning: "neural networks are far more sensitive to the size of the exponent than that of the mantissa", and the multipliers are "about half the size in silicon of a typical FP16 multiplier" (Wang and Kanwar 2019). It is the default training dtype in 2026.
  • FP8 comes in two flavours because the passes need different things: "E4M3 for weight and activation tensors, and E5M2 for gradient tensors" (Micikevicius et al. 2022). With 8 values per binade every tensor needs its own scale;
  • 4-bit block formats (MXFP4 with an E8M0 scale per 32 elements, NVFP4 with an E4M3 scale per 16 plus a per-tensor FP32 scale), how scales are chosen per tensor, row or tile, and FP8 training as DeepSeek-V3 ran it are Quantization and precision's subject (its sections 1 and 2 for formats and shared scales, section 6 for FP8 training). Reading a recipe: "bf16 mixed precision" means bf16 matrix multiplies with float32 master weights and accumulators; "FP8 training" means FP8 matrix-multiply inputs with per-tensor or per-block scales and higher-precision accumulation.

The stage stores the running example's loss, 2.40760596…2.40760596\ldots, in six formats, one row of bits each, aligned at the sign bit: sign, exponent, mantissa; a 1 stands up, a 0 lies flat. Every bit is computed by this page's emulator and matches NumPy and ml_dtypes.

  1. float32: the loss in 32 bits. Sign 0, exponent field 10000000 (128, so 212^{1}), then 23 fraction bits: 0 10000000 00110100001011000110111, which reads back as 2.40760588645935062.4076058864593506.
  2. bfloat16: keep the first 16 bits. The same sign and 8-bit exponent, so the same range; the mantissa goes from 23 bits to 7. It rounds to nearest (the first dropped bit is 0, so here rounding equals cutting): 2.406252.40625, a relative error of 5.6×10−45.6 \times 10^{-4}.
  3. TF32: float32's exponent, 10 mantissa bits. 19 bits, rounded to nearest here: 2.4082031252.408203125. A tensor core reads TF32 from a float32 in memory, and one that keeps only "the first 10 bits of the input mantissa" (PyTorch notes) truncates instead, giving 2.406252.40625.
  4. float16: a shorter exponent. 5 exponent bits with bias 15 (field 10000 = 16, still 212^{1}) and TF32's 10 mantissa bits: the same 2.4082031252.408203125, relative error 2.5×10−42.5 \times 10^{-4}, but the range now ends at 65,504.
  5. FP8: E5M2 and E4M3. E5M2 keeps float16's exponent and bias, so it is float16's top byte, rounded; E4M3 gives an exponent bit to the mantissa. With 2 or 3 mantissa bits both store 2.52.5, a relative error of 3.8%3.8\%.
  6. Exponent bits buy range, mantissa bits buy precision. All six together: the exponent widths (8, 8, 8, 5, 5, 4) set the largest number, the mantissa widths (23, 10, 7, 10, 2, 3) set the gap ε=2−m\varepsilon = 2^{-m} and so the error of the stored loss.
TF32 in PyTorch, and the fnuz FP8 variants

In PyTorch 2.14.1 TF32 is off by default for matrix multiplies and on for convolutions; torch.backends.cuda.matmul.fp32_precision = "tf32" turns it on "if your network does not need full float32 precision" (notes). PyTorch also has float8_e4m3fnuz and float8_e5m2fnuz variants with no negative zero.

Two libraries, two answers for the same FP8 cast (measured)
Converting 10001000 to E4M3 (largest 448): PyTorch 2.14.1's tensor.to(torch.float8_e4m3fn) returns 448 (it saturates), while ml_dtypes 0.6.0 returns NaN. Both are allowed: the OFP8 spec "requires implementation of saturating and non-saturating modes", and in non-saturating mode an overflowing E4M3 result is NaN (spec, section 5.2 and table 3). E5M2 has infinities, so 10001000 rounds to 1024 in both. Know which one your kernel does before you trust an FP8 tensor's max.

4. The error of one operation, conditioning and cancellation

Because IEEE 754 rounds each basic operation once, correctly, every operation obeys the standard model (Higham 2002, chapter 2): the computed result is the exact result of the exact inputs, nudged by a relative error of at most uu (5.96×10−85.96 \times 10^{-8} in float32), as long as it neither overflows nor underflows.

fl⁡(x∘y)=(x∘y)(1+δ),|δ|≤u,∘∈{+,−,×,÷}\operatorname{fl}(x \circ y) = (x \circ y)(1 + \delta), \qquad |\delta| \le u, \qquad \circ \in \{+, -, \times, \div\}

One operation is almost perfect; problems come from errors already in the inputs and from many operations in a row. The fused multiply-add (FMA, required since IEEE 754-2008) computes a×b+ca \times b + c with one rounding instead of two; matrix-multiply units are built from it. Two ways to measure a wrong answer: the forward error is the distance from the true answer; the backward error asks how much the input would have to change for the computed answer to be exact. An algorithm whose answers are exact for inputs perturbed by a few uu is backward stable, and

forward error≲κ×backward error.\text{forward error} \lesssim \kappa \times \text{backward error} .

So there are two separate ways to get a bad answer: a badly conditioned problem (large κ\kappa: any algorithm loses digits) or an unstable algorithm (large backward error on a well-conditioned problem: a better algorithm fixes it). The naive softmax of section 7 is the second kind.

Catastrophic cancellation

Subtracting two nearly equal floats is exact (the Sterbenz lemma: if y/2≤x≤2yy/2 \le x \le 2y, then x−yx - y is a float), but it exposes the rounding errors the two numbers already carried, now measured against a tiny result:

The rule: when a≈ba \approx b, the relative error of a−ba - b is the inputs' relative error times |a|/|a−b||a| / |a - b|, and the fix is always to rewrite the formula so the subtraction of nearly equal quantities never happens.

Subtracting 1 keeps the rounding noise and throws away the digits that agreed

1.00011.0001 stored in float32 is 1.0001000165939331.000100016593933 (bits 3f800347), relative error 1.7×10−81.7 \times 10^{-8}, within uu. Subtracting 1 is exact, but the four leading digits that agreed are gone and the result 0.000100016593933105470.00010001659393310547 has a relative error of 1.66×10−41.66 \times 10^{-4}: the input's own error times κ=10,001\kappa = 10{,}001, within the bound κu=10,001×2−24=6.0×10−4\kappa u = 10{,}001 \times 2^{-24} = 6.0 \times 10^{-4}. Green: correct digits; orange: digits that are rounding noise. Derived, src/derive_new_visuals.py.
The same cancellation measured with x=10−8x = 10^{-8}, in float32 and float64

Measured with x=10−8x = 10^{-8}: in float32, 1+10−81 + 10^{-8} rounds to 1 (the gap above 1 is 1.2×10−71.2 \times 10^{-7}), so (1+x)−1=0(1 + x) - 1 = 0, 100% error; in float64, (1+x)−1=9.99999993922529×10−9(1 + x) - 1 = 9.99999993922529 \times 10^{-9}, a relative error of 6.1×10−96.1 \times 10^{-9}, which is 5×1075 \times 10^{7} times float64's u=1.1×10−16u = 1.1 \times 10^{-16}: eight of sixteen digits gone because 1+x1 + x was rounded first.

The condition number of a function

How much does a small relative change in xx change f(x)f(x)? Divide the two relative changes and let the input change shrink to zero:

κf(x)=|Δf/fΔx/x|→|xf′(x)f(x)|.\kappa_f(x) = \left|\frac{\Delta f / f}{\Delta x / x}\right| \to \left| \frac{x\, f'(x)}{f(x)} \right| .

An input known to relative accuracy uu gives an output known to about κf(x)u\kappa_f(x)\, u, whatever algorithm you use. Worked values (derived):

ffκf(x)\kappa_f(x)Atκ\kappaMeaning
x−1x - 1|x/(x−1)||x / (x - 1)|x=1.0001x = 1.000110,0014 of float32's 7 digits are lost (the figure above)
ln⁡x\ln x1/|ln⁡x|1 / |\ln x|x=1.0001x = 1.000110,000ln⁡\ln near 1 is ill-conditioned in xx: pass x−1x - 1 instead (log1p)
exe^{x}|x||x|x=1000x = 10001,000large logits amplify their own errors
x\sqrt{x}1/21/2any0.5harmless
ln⁡∑jezj\ln \sum_j e^{z_j}∑j|zj|pj/|ln⁡∑jezj|\sum_j |z_j|\, p_j / |\ln \sum_j e^{z_j}|z=(1000,999,0)z = (1000, 999, 0)0.9994perfectly well-conditioned: overflow there is the algorithm's fault

The last row uses ∂ln⁡∑jezj/∂zi=pi\partial \ln\sum_j e^{z_j} / \partial z_i = p_i, the softmax; for several inputs the condition number sums |zi||∂f/∂zi||z_i|\,|\partial f/\partial z_i| and divides by |f||f|. Matrices have their own condition number, σmax⁡/σmin⁡\sigma_{\max}/\sigma_{\min}: Linear algebra, section 11, where the float32 normal equations lose 77% of the answer and QR keeps it.

log1p and expm1 compute ln⁡(1+x)\ln(1 + x) and ex−1e^{x} - 1 directly from xx, with no rounded 1+x1 + x to cancel: at x=10−10x = 10^{-10} in float64, log(1 + x) keeps about 8 correct digits and log1p(x) all 16 (measured). Section 8 uses both inside softplus and BCE.

log1p and expm1, the measured values

Measured in float64 at x=10−10x = 10^{-10}: log(1 + x) gives 1.000000082690371×10−101.000000082690371 \times 10^{-10} (relative error 8.3×10−88.3 \times 10^{-8}), log1p(x) gives 9.9999999995×10−119.9999999995 \times 10^{-11}; exp(x) - 1 is off by the same 8.3×10−88.3 \times 10^{-8} and expm1(x) is exact.

Variance: one pass, two passes, Welford

The variance 1n∑i(xi−x‾)2\frac1n \sum_i (x_i - \bar x)^2 expanded into the one-pass "computational formula" 1n∑ixi2−x‾2\frac1n \sum_i x_i^2 - \bar{x}^2 subtracts two huge, nearly equal numbers. Measured in float32 on three numbers near 10,000 (stored as 10000.099610000.0996, 10000.200210000.2002, 10000.299810000.2998; exact variance of the stored values 0.00667970.0066797):

Methodfloat32 resultWhat happened
one pass, x2−x‾2\overline{x^2} - \bar x^2−8.0-8.0∑xi2≈3.0×108\sum x_i^2 \approx 3.0 \times 10^{8}, where float32's gap is 32; the true difference, 0.02, is far below one gap. A variance cannot be negative: ⋅\sqrt{\cdot} of it is NaN.
two passes: mean first, then ∑(xi−x‾)2\sum (x_i - \bar x)^20.00667990.0066799the subtraction happens before squaring, on numbers of size 0.1
Welford, one pass0.00663090.0066309updates the mean and the sum of squared deviations together; 0.7% off here, never negative

Welford's algorithm (Welford 1962) keeps a running mean mkm_k and sum of squared deviations MkM_k, so nothing large is ever subtracted from something large:

mk=mk−1+xk−mk−1k,Mk=Mk−1+(xk−mk−1)(xk−mk),var⁡=Mn/n.m_k = m_{k-1} + \frac{x_k - m_{k-1}}{k}, \qquad M_k = M_{k-1} + (x_k - m_{k-1})(x_k - m_k), \qquad \operatorname{var} = M_n / n .

It also merges partial results from two halves of the data exactly (Chan et al. 1979), which parallel hardware needs: PyTorch's reductions for variance and normalisation statistics use a WelfordOps accumulator (SharedReduceOps.h, v2.14.1). A hand-written (x**2).mean() - x.mean()**2 inside a LayerNorm, BatchNorm or RMSNorm can go negative on large activations and turn 1/var⁡+ϵ1/\sqrt{\operatorname{var} + \epsilon} into NaN.

Welford on the three numbers, step by step

m=10000.0996,10000.1504,10000.2002m = 10000.0996, 10000.1504, 10000.2002 and M=0,0.00501,0.01989M = 0, 0.00501, 0.01989, so var⁡=0.01989/3=0.00663\operatorname{var} = 0.01989 / 3 = 0.00663 (measured, float32).

5. Summation: order matters, and long sums drift

A loss is a mean over a batch, a matrix multiply is millions of sums, a gradient is a sum over tokens. Each ++ rounds, and the rounding depends on the operands' sizes, so floating-point addition is not associative. Measured in float64: (0.1+0.2)+0.3=0.6000000000000001(0.1 + 0.2) + 0.3 = 0.6000000000000001 but 0.1+(0.2+0.3)=0.60.1 + (0.2 + 0.3) = 0.6; (1016+1)−1016=0(10^{16} + 1) - 10^{16} = 0 but (1016−1016)+1=1(10^{16} - 10^{16}) + 1 = 1, because near 101610^{16} the gap is 2, so 1016+110^{16} + 1 is a tie that rounds back and the 1 is absorbed. Addition is still commutative (a+b=b+aa + b = b + a exactly); it is chains of additions in different orders that differ.

Adding x1,…,xnx_1, \dots, x_n left to right (recursive summation), x1x_1 and x2x_2 pass through n−1n - 1 roundings, x3x_3 through n−2n - 2, and so on, so to first order in uu

|sˆn−sn|≤(n−1)u∑i=1n|xi|.|\hat s_n - s_n| \le (n - 1)\, u \sum_{i=1}^{n} |x_i| .
Where that bound comes from, in three lines

sˆ2=(x1+x2)(1+δ2)\hat s_2 = (x_1 + x_2)(1 + \delta_2), sˆ3=((x1+x2)(1+δ2)+x3)(1+δ3)\hat s_3 = \bigl((x_1 + x_2)(1 + \delta_2) + x_3\bigr)(1 + \delta_3), and so on. Multiplying out, sˆn=∑ixi∏k=max⁡(i,2)n(1+δk)\hat s_n = \sum_i x_i \prod_{k = \max(i, 2)}^{n} (1 + \delta_k). Each product of at most n−1n - 1 factors (1+δk)(1 + \delta_k) lies within (1±u)n−1=1±(n−1)u+O(u2)(1 \pm u)^{n-1} = 1 \pm (n-1)u + O(u^2). Subtract the exact sum and bound each term by |xi|(n−1)u|x_i|\,(n-1)u. The full statement with the O(u2)O(u^2) term is in Higham 2002, chapter 4.

The bound grows with nn and is relative to ∑|xi|\sum|x_i|, not to the answer: with mixed signs the answer can be tiny and the relative error huge. Worse is stagnation: once the running sum is large, each small term is below half a gap and lost entirely. Adding 1 over and over (measured), float16 stops at 2,048, bfloat16 at 256, float32 at 16,777,216: these are 2p2^{p}, where the gap becomes 2 and adding 1 is a tie that rounds back (to even). Three fixes:

  • Pairwise summation: add neighbours in pairs, then pairs of pairs. Each term passes through ⌈log2⁡n⌉\lceil \log_2 n \rceil roundings, so the bound becomes ⌈log2⁡n⌉u∑|xi|\lceil \log_2 n \rceil\, u \sum|x_i|: 20 instead of a million for n=106n = 10^6. GPUs do this naturally (a tree reduction); NumPy uses "partial pairwise summation" (its sum docstring).
  • Kahan (compensated) summation (Kahan 1965) carries a second number cc holding what the last addition lost and feeds it into the next one. Its bound is (2u+O(nu2))∑|xi|\bigl(2u + O(n u^2)\bigr)\sum|x_i|: independent of nn while nu≪1n u \ll 1.
  • Accumulate in higher precision: 16-bit inputs added in a float32 accumulator. Tensor cores do this for fp16 and bf16 matrix multiplies (PyTorch notes: "intermediate accumulations (reduction) in single-precision"); FP8 recipes promote partial sums periodically: DeepSeek-V3 every 128 elements (Quantization and precision).

Before and after: the same eleven float16 numbers, 2048 then ten copies of 0.4

0.4 is stored as 0.399902340.39990234. Exact sum 2051.9992051.999; the nearest float16 is 2052.
y=xk−c,t=s+y,c=(t−s)−y,s=ty = x_k - c, \qquad t = s + y, \qquad c = (t - s) - y, \qquad s = t

Read Kahan's four lines as: yy is the new term corrected by last step's loss; tt is the rounded new sum; (t−s)(t - s) is what actually got added, so (t−s)−y(t - s) - y is minus what was lost. In exact arithmetic cc would always be 0, which is why a compiler allowed to reassociate (-ffast-math, some JIT settings) can silently delete it. Step through both on the same input; the steps play by themselves once the card is in view:

Predict the naive sum before it plays; the mode buttons on the card swap the steps below.

  1. Start. s=0s = 0. Eleven float16 numbers will be added: 2048, then ten copies of 0.4, stored as 0.399902340.39990234. At 2048 float16's gap is 2.
  2. Add 2048. It is exactly representable: s=2048s = 2048.
  3. Add the first 0.4: absorbed. The exact sum 2048.39992048.3999 is less than half a gap (1) above 2048, so it rounds back to 2048. Lost this step: 0.399902340.39990234.
  4. Add the other nine: all absorbed. Each is lost the same way, so the naive sum never moves: it ends at 2048, against an exact 2051.9992051.999 whose nearest float16 is 2052.

The same error growth on many numbers: add NN numbers with the four algorithms, every addition rounded to the chosen format exactly as the hardware would, against the exact sum (Shewchuk's algorithm, as Python's math.fsum). Predict what the naive float16 sum of 10,000 uniform numbers returns, then look.

Measured on a million numbers (NumPy and PyTorch on this laptop, uniform on [0,1)[0, 1)): the naive 16-bit running sum is useless past a few thousand terms (float16 59% low at N=104N = 10^4, bfloat16 50% low at N=103N = 10^3); pairwise and Kahan stay within one rounding; Kahan in bfloat16 fails at N=106N = 10^6 (87% error) exactly as its bound warns, since nu2=106×2−16≈15n u^2 = 10^6 \times 2^{-16} \approx 15 is no longer small; the float32 accumulator is the best by orders of magnitude. At N=106N = 10^6 the true sum, about 500,000, is beyond float16's 65,504, so pairwise, NumPy and torch.sum overflow to infinity and Kahan to NaN (its correction becomes ∞−∞\infty - \infty); only the naive sum stays finite, because it stalled at 2,048 long before. Rules: accumulate in float32 (float64 for metrics), prefer the library's reduction to a Python loop, never keep a running total in bf16.

Error against NN: naive drifts, pairwise and Kahan stay near one rounding, a float32 accumulator wins

Float16, uniform, N=10,000N = 10{,}000: the naive sum stalls at 2,048 (59% low) while pairwise and Kahan are within one rounding. Try big first value (naive loses almost all the small numbers), mixed signs (every bound is relative to ∑|xi|\sum|x_i|, not to the small answer) and Shuffle. "Best possible" is the exact sum rounded once to the format. A relative error of exactly 0 is drawn at the bottom edge, an infinite one (overflow) at the top. Data from a seeded generator (mulberry32), rounded to the format first so only the summation rounds; recompute.py reproduces the uniform cases at N=100N = 100, 1,000 and 10,000 in NumPy.
The measured table: three formats, five methods, NN from 100 to 10610^6

Sum the first NN of a million numbers drawn uniformly from [0,1)[0, 1), each first rounded to the format so that only the summation rounds. Relative error against math.fsum; "fp32 accumulator" adds the 16-bit inputs in a float32 running sum; torch.sum is PyTorch 2.14.1 on the CPU.

Python's built-in sum of floats switched to a compensated algorithm in 3.12: measured, Python 3.13 gives sum([1e16, 1.0, -1e16]) = 1.0 where Python 3.9 gives 0.0; math.fsum is exactly rounded.

6. Determinism: why the same code gives different numbers

Fix every seed, run the same step twice, and the losses can still differ in the sixth digit. The cause is the order of additions. A parallel reduction splits a sum into chunks, adds each chunk, then adds the chunk totals; the chunking depends on the thread count, the block sizes a kernel picks for this shape, and whether a matrix multiply splits its inner dimension (split-K). A kernel that lets many threads add into one location uses atomic adds, and then the order is whichever thread finishes first.

Same eight numbers, three reduction trees, three answers to a sum that is exactly 0

Thinking Machines' eight numbers ±10−10,±10−5,±10−2,±1\pm10^{-10}, \pm10^{-5}, \pm10^{-2}, \pm1 in one fixed order, float64, exact sum 0. Each numbered circle is one rounded addition (the list under the tree gives its operands and result, shortest exact decimal); orange marks the additions that lost digits. Results: 8.7×10−188.7 \times 10^{-18}, 4.5×10−174.5 \times 10^{-17} and 3.6×10−173.6 \times 10^{-17}. Derived, src/derive_new_visuals.py.

Measured on this laptop:

ExperimentDistinct resultsNote
8 numbers ±10−10,±10−5,±10−2,±1\pm10^{-10}, \pm10^{-5}, \pm10^{-2}, \pm1 (exact sum 0), 10,000 shuffles, plain left-to-right loop258results from −2.2×10−16-2.2 \times 10^{-16} to 2.2×10−162.2 \times 10^{-16}
same, Python 3.13 built-in sum102reproduces the 102 printed by Thinking Machines, 10 Sep 2025
10510^5 normal float32 values, sequential fp32 sum, 20 random orders20 of 20spread 0.0043 around the exact 29.3288
torch.sum of 10710^7 float32 on the CPU, 5 runs each at 1, 2, 4, 8 threads1 per thread count, 3 overall1 or 2 threads −4320.4326-4320.4326, 4 threads −4320.4336-4320.4336, 8 threads −4320.4331-4320.4331 (exact −4320.4332-4320.4332)
index_add_ of 10610^6 float32 into 10 slots, 20 runs, Apple GPU (MPS)20 of 20the same call on the CPU: 1 of 20; torch.sum on MPS: 1 of 20

So "nondeterminism" has two meanings. Run-to-run: the same call on the same input differs between runs (atomics, the MPS index_add_ row). Configuration-dependent: repeatable, but changes with thread count, batch size or hardware (the torch.sum row). Thinking Machines showed that LLM inference is mostly the second kind: the forward pass "involves no operations that require atomic adds" and is run-to-run deterministic, but kernels are not batch invariant, so a request's numbers depend on how many other requests share its batch. Sampling Qwen3-235B-A22B-Instruct-2507 1,000 times at temperature 0, they got 80 unique completions, all identical for the first 102 tokens; with batch-invariant kernels all 1,000 matched (same post; the serving side is on ML system design). In training, the backward pass is where atomics live: gradients of embeddings, gathers and scatters add many contributions into the same row. Bit-identical reruns matter for bisecting a divergence, for on-policy RL (sampler and trainer must compute the same log-probabilities, Thinking Machines' motivation) and for regression tests, which should compare with a tolerance, not ==; expect small differences between runs and providers at temperature 0.

What PyTorch lets you control (v2.14.1)
  • torch.manual_seed(0) seeds "the RNG for all devices"; DataLoader workers need their own seeding function and generator (the notes give a seed_worker recipe).
  • torch.use_deterministic_algorithms(True) picks deterministic implementations where they exist and raises a RuntimeError for operations that have none. The docstring lists both: made deterministic, for example index_add, scatter_add_ and the backward of nn.Embedding on CUDA; raising, for example NLLLoss and histc on CUDA. Deterministic kernels "tend to have worse performance".
  • torch.backends.cudnn.benchmark = False stops cuDNN choosing among algorithms by timing (which "may select different algorithms on subsequent runs"); torch.backends.cudnn.deterministic = True controls only cuDNN's convolution choice.
  • Up to v2.9.1 the docstring also required CUBLAS_WORKSPACE_CONFIG=:4096:8 (or :16:8) for some CUDA operations; that paragraph is absent from v2.10.0 onward (checked in both sources).
  • Even then: "Completely reproducible results are not guaranteed across PyTorch releases, individual commits, or different platforms" (reproducibility notes), and A.sum(-1)[0] "is not guaranteed to be bitwise equal" to the sum of the slice (numerical accuracy notes).

7. The stable softmax, log-sum-exp and log-softmax

The softmax turns logits z1,…,znz_1, \dots, z_n into probabilities, and the loss is the negative log of the target's:

pi=ezi∑j=1nezj,loss=−ln⁡py  for the target y.p_i = \frac{e^{z_i}}{\sum_{j=1}^{n} e^{z_j}}, \qquad \text{loss} = -\ln p_y \ \text{ for the target } y .

For z=(2,1,0)z = (2, 1, 0): e2=7.389e^2 = 7.389, e1=2.718e^1 = 2.718, e0=1e^0 = 1, sum 11.10711.107, so p=(0.665,0.245,0.090)p = (0.665, 0.245, 0.090) and the loss for the target sat is −ln⁡0.090=2.408-\ln 0.090 = 2.408. Now take z=(1000,999,0)z = (1000, 999, 0). e1000e^{1000} is about 1043410^{434}, past float32's largest value (e88.72e^{88.72}) and even float64's (e709.78e^{709.78}), so it rounds to ∞\infty; the sum is ∞\infty, pcat=∞/∞=p_{\text{cat}} = \infty/\infty = NaN, and one NaN makes the loss and every gradient NaN. The problem itself is easy (condition number 0.9994, section 4): the answer is p=(0.731,0.269,e−1000.3)p = (0.731, 0.269, e^{-1000.3}). Only the algorithm fails.

The fix: subtract the largest logit

Multiply the top and bottom by the same e−me^{-m}; the value is unchanged for any mm:

ezi∑jezj=ezi−m∑jezj−m,m=maxj⁡zj.\frac{e^{z_i}}{\sum_j e^{z_j}} = \frac{e^{z_i - m}}{\sum_j e^{z_j - m}}, \qquad m = \max_j z_j .

Then every exponent is at most 0, every ezj−me^{z_j - m} lies in (0,1](0, 1], nothing can overflow, and the denominator lies between 1 (the largest term is exactly e0e^0) and nn. Terms that underflow to 0 are far below uu relative to that 1, so dropping them changes nothing visible. The same move gives the log-sum-exp, the log of the denominator, and the log-softmax:

LSE⁡(z)=m+ln⁡∑jezj−m,ln⁡pi=zi−LSE⁡(z)=(zi−m)−ln⁡∑jezj−m.\operatorname{LSE}(z) = m + \ln \sum_j e^{z_j - m}, \qquad \ln p_i = z_i - \operatorname{LSE}(z) = (z_i - m) - \ln \sum_j e^{z_j - m} .

The stage computes both versions on the running example, logits cat 1000, dog 999, sat 0 (target sat), with every operation rounded to the chosen format by this page's emulator (the numbers match NumPy and ml_dtypes, recompute.py). The back row is the naive softmax, the front row the stable one. Predict which naive step first goes wrong.

  1. The same logits, twice. Bar heights are the logits as stored: cat 1000, dog 999, sat 0. In bfloat16, 999 is not a number (between 512 and 1024 the gap is 4), so it is stored as 1000 and the difference between cat and dog is gone before anything is computed.
  2. Naive: exponentiate, and two bars break through the ceiling. On a log scale the bar for eze^{z} has height zz, and the glass ceiling is the format's largest number: e88.72e^{88.72} in float32 and bfloat16, e11.09e^{11.09} in float16. e1000e^{1000} and e999e^{999} pass it and round to infinity (exponent all ones, fraction 0); e0=1e^{0} = 1 is fine.
  3. Naive: sum, divide, loss. ∞+∞+1=∞\infty + \infty + 1 = \infty; then ∞/∞\infty / \infty is NaN for cat and dog and 1/∞=01 / \infty = 0 for sat. The loss −ln⁡0-\ln 0 is infinite and the gradient p−onehotp - \text{onehot} is NaN, NaN, −1-1: one optimiser step with it makes every weight NaN. PyTorch measured the same: loss inf, gradient [nan, nan, nan].
  4. Stable: subtract the largest logit. m=1000m = 1000 flows to every logit; the shifted logits are 0, −1-1 and −1000-1000, every one at most 0, so no exponential can pass the ceiling. The subtraction is exact here.
  5. Stable: exponentiate. e0=1e^{0} = 1, e−1=0.368e^{-1} = 0.368, and e−1000e^{-1000} underflows to 0, far too small to change the sum: harmless. Every bar lies in (0,1](0, 1], far below the ceiling.
  6. Stable: sum, then divide. The denominator is 1.3681.368, between 1 and 3 because the largest term is exactly 1; p=(0.731,0.269,0)p = (0.731, 0.269, 0), finite and summing to 1. In bfloat16 it is (0.5,0.5,0)(0.5, 0.5, 0): stable, but the logits had already lost their difference.
  7. Log-softmax, loss and gradient. ln⁡p=(z−m)−ln⁡1.368\ln p = (z - m) - \ln 1.368: −0.313-0.313, −1.313-1.313 and −1000.313-1000.313, even though psatp_{\text{sat}} itself underflowed to 0, because the log never sees the 0. The loss is 1000.3131000.313, huge but honest, and the gradient (0.731,0.269,−1)(0.731, 0.269, -1) is finite; PyTorch's fused cross_entropy measured the same: 1000.31321000.3132, [0.7311,0.2689,−1][0.7311, 0.2689, -1].

The values at this step, as stored bits

For (1000,999,0)(1000, 999, 0): LSE⁡=1000+ln⁡(1+e−1+e−1000)\operatorname{LSE} = 1000 + \ln(1 + e^{-1} + e^{-1000}), that is 1000+ln⁡1.3679=1000.31331000 + \ln 1.3679 = 1000.3133 (derived; the old Topic: math child page's example, logits (1000,1001)(1000, 1001), gives 1001.3131001.313 the same way, rechecked). Never take the log of a softmax: psat=e−1000.31p_{\text{sat}} = e^{-1000.31} underflows to 0 even in float64 (smallest about e−744e^{-744}), and −ln⁡0=∞-\ln 0 = \infty, while the log-softmax gives ln⁡psat=(0−1000)−0.3133=−1000.3133\ln p_{\text{sat}} = (0 - 1000) - 0.3133 = -1000.3133: a huge, honest, finite loss, with gradient p−onehot(y)=(0.731,0.269,−1)p - \text{onehot}(y) = (0.731, 0.269, -1). For the same reason every likelihood is a sum of logs: 1,000 tokens each with probability 0.1 have likelihood 10−100010^{-1000}, which underflows even float64, while its log, −1000ln⁡10=−2302.6-1000 \ln 10 = -2302.6, is ordinary (derived). This is why CrossEntropyLoss takes "unnormalized logits" and runs log-softmax and the negative log-likelihood fused. (The probability side, why losses and likelihoods live in log space, is Probability's section 12.)

Keep logits and softmax in float32: PyTorch's autocast lists softmax, log_softmax, cross_entropy, exp, log and sum among the "CUDA Ops that can autocast to float32" (amp docs, v2.14.1).

One pass instead of two: the online softmax

The stable softmax reads the logits twice (max, then sum). Milakov and Gimelshein update both in one pass (2018): keep the running max mkm_k and the running sum dk=∑j≤kezj−mkd_k = \sum_{j \le k} e^{z_j - m_k}, and rescale the old sum when the max changes:

mk=max⁡(mk−1,zk),dk=dk−1emk−1−mk+ezk−mk.m_k = \max(m_{k-1}, z_k), \qquad d_k = d_{k-1}\, e^{m_{k-1} - m_k} + e^{z_k - m_k} .

On (1000,999,0)(1000, 999, 0): m=1000,d=1m = 1000, d = 1; then d=1+e−1=1.368d = 1 + e^{-1} = 1.368; then d=1.368+e−1000=1.368d = 1.368 + e^{-1000} = 1.368, the same denominator. This rescaling is the heart of FlashAttention (Dao et al. 2022; the FlashAttention paper page runs the kernel in its Run the kernel tab), which computes attention's softmax tile by tile without holding a full row of scores; the mask's −∞-\infty entries go through the same formulas. The error analysis of the shifted formulas is Blanchard, Higham and Higham 2021.

What PyTorch actually runs (v2.14.1 source)

torch.logsumexp is exactly the formula above, with one extra guard: if the max is infinite (a row of all −∞-\infty, as in a fully masked attention row), it shifts by 0 instead, so the result is −∞-\infty rather than NaN from −∞−(−∞)-\infty - (-\infty):

// aten/src/ATen/native/ReduceOps.cpp, lines 1543-1558 (v2.14.1)
static Tensor& logsumexp_out_impl(Tensor& result, const Tensor& self, IntArrayRef dims, bool keepdim) {
  // can't take max of empty tensor
  if (self.numel() != 0) {
    ...
    auto maxes = at::amax(at::real(self), dims, true);
    auto maxes_squeezed = (keepdim ? maxes : at::squeeze(maxes, dims));
    maxes_squeezed.masked_fill_(maxes_squeezed.abs() == INFINITY, 0);
    at::sum_out(result, (self - maxes).exp_(), dims, keepdim);
    result.log_().add_(maxes_squeezed);
  } else { ... }

The CPU softmax kernel does the same three steps per row: reduce to the max, map x↦ex−max⁡x \mapsto e^{x - \max}, sum and multiply by the reciprocal (SoftMaxKernel.cpp, lines 60 to 91). Excerpts are saved in src/inputs/pytorch_v2.14.1/excerpts.txt.

8. The stable toolbox: logsigmoid, BCE with logits, softplus, epsilons

One pattern covers almost every other everyday formula that overflows, underflows or cancels: split on the sign, so the exponential only ever sees a non-positive number, and use log1p for the log of one plus something small. The identity behind it is e−|x|≤1e^{-|x|} \le 1 for every xx. Predict where the naive binary cross-entropy breaks in float16, then switch the format:

logsigmoid. The sigmoid σ(x)=1/(1+e−x)\sigma(x) = 1/(1 + e^{-x}) gives a probability from one logit, and its log appears in every binary loss. Naively, ln⁡σ(−100)\ln\sigma(-100) in float32: e100e^{100} overflows (past e88.72e^{88.72}), σ=1/∞=0\sigma = 1/\infty = 0, ln⁡0=−∞\ln 0 = -\infty (measured); the true value is −100-100. Splitting on the sign gives one formula:

ln⁡σ(x)=min⁡(x,0)−log1p⁡(e−|x|).\ln \sigma(x) = \min(x, 0) - \operatorname{log1p}\bigl(e^{-|x|}\bigr) .

Binary cross-entropy with logits. For a logit xx and a label y∈{0,1}y \in \{0, 1\} (or a soft label in [0,1][0, 1]), ℓ=−[yln⁡σ(x)+(1−y)ln⁡(1−σ(x))]\ell = -[\,y \ln\sigma(x) + (1 - y)\ln(1 - \sigma(x))\,], and with 1−σ(x)=σ(−x)1 - \sigma(x) = \sigma(-x):

ℓ=(1−y)x−ln⁡σ(x)=max⁡(x,0)−xy+log1p⁡(e−|x|).\ell = (1 - y)\,x - \ln\sigma(x) = \max(x, 0) - x y + \operatorname{log1p}\bigl(e^{-|x|}\bigr) .

Worked: x=2x = 2, y=1y = 1 gives 0−2+2+log1p⁡(e−2)=0.12690 - 2 + 2 + \operatorname{log1p}(e^{-2}) = 0.1269; y=0y = 0 gives 2+0.1269=2.12692 + 0.1269 = 2.1269 (derived). Naively in float32 with x=30x = 30, y=0y = 0: σ(30)=1−9.4×10−14\sigma(30) = 1 - 9.4 \times 10^{-14} rounds to exactly 1, ln⁡(1−1)=−∞\ln(1 - 1) = -\infty, loss ∞\infty (measured); the stable form gives 30+log1p⁡(e−30)=30.030 + \operatorname{log1p}(e^{-30}) = 30.0. PyTorch v2.14.1 computes (1 - target).mul_(input).sub_(log_sigmoid_input), the middle form (Loss.cpp, lines 349 to 364). softplus, ln⁡(1+ex)\ln(1 + e^{x}), is the same shape: naively softplus⁡(100)=ln⁡(1+∞)=∞\operatorname{softplus}(100) = \ln(1 + \infty) = \infty in float32 (measured); stably max⁡(x,0)+log1p⁡(e−|x|)\max(x, 0) + \operatorname{log1p}(e^{-|x|}).

Naive formulas go infinite at a logit set by the format; the stable forms never do

Both curves computed with every operation rounded to the format by this page's emulator (log1p in float64, then rounded); the naive curve is cut where it first becomes infinite (the red marker). In float32 the naive BCE fails from x=16.64=24ln⁡2x = 16.64 = 24 \ln 2, where 1+e−x1 + e^{-x} already rounds to 1, a little before σ(x)\sigma(x) itself would round to 1 (17.3, below the table). Derived.
Why not Sigmoid then BCELoss?
Because the probability has already rounded to 0 or 1 before the loss sees it. PyTorch patches the symptom: "BCELoss clamps its log function outputs to be greater than or equal to -100", so the x=30x = 30 example returns 100 instead of 30, a finite but wrong loss with a wrong gradient. Under autocast it refuses outright: "binary_cross_entropy and BCELoss raise an error in autocast-enabled regions", and the docs say to use binary_cross_entropy_with_logits (loss.py, amp docs, v2.14.1). Reward models trained with −ln⁡σ(rw−rl)-\ln\sigma(r_w - r_l) and DPO's loss are exactly a logsigmoid.
The derivations, and the kernels PyTorch runs

logsigmoid. For x≥0x \ge 0, ln⁡σ(x)=−ln⁡(1+e−x)\ln\sigma(x) = -\ln(1 + e^{-x}). For x<0x \lt 0, multiply top and bottom by exe^{x}: σ(x)=ex/(1+ex)\sigma(x) = e^{x}/(1 + e^{x}), so ln⁡σ(x)=x−ln⁡(1+ex)\ln\sigma(x) = x - \ln(1 + e^{x}). Both are the one formula above. PyTorch's CPU kernel is that line, computed in float32 even for 16-bit inputs: min_vec - buffer_vec0.log1p() with buffer_vec0 = data_vec0.abs().neg().exp() (Activation.cpp, lines 33 to 48).

BCE. Two facts: 1−σ(x)=σ(−x)1 - \sigma(x) = \sigma(-x), and ln⁡σ(−x)=ln⁡σ(x)−x\ln\sigma(-x) = \ln\sigma(x) - x (from σ(−x)=e−xσ(x)\sigma(-x) = e^{-x}\sigma(x)). Substitute: ℓ=−yln⁡σ(x)−(1−y)(ln⁡σ(x)−x)\ell = -y \ln\sigma(x) - (1 - y)\bigl(\ln\sigma(x) - x\bigr), which collects to (1−y)x−ln⁡σ(x)(1 - y)\,x - \ln\sigma(x), and the logsigmoid line gives the last form.

softplus is a smooth ReLU and the negative of ln⁡σ(−x)\ln\sigma(-x). PyTorch's nn.Softplus(beta=1.0, threshold=20.0) takes a shortcut: when βx>20\beta x \gt 20 it returns xx unchanged. What it drops, log1p⁡(e−20)=2.1×10−9\operatorname{log1p}(e^{-20}) = 2.1 \times 10^{-9}, is a thousand times smaller than float32's gap at 20 (1.9×10−61.9 \times 10^{-6}), so the shortcut is exact in float32 (derived).

Epsilons. Formulas that divide by something that can be 0 (a standard deviation, a norm, the root of a second moment) add a small constant ϵ\epsilon, not machine epsilon: LayerNorm's default 10−510^{-5} turns a constant row's 0/00/0 into 0; Adam's 10−810^{-8} is itself 0 in float16, one reason optimiser state stays in float32.

Epsilons in LayerNorm, RMSNorm and Adam, and why autocast keeps norms in float32
  • LayerNorm, y=x−mean⁡(x)var⁡(x)+ϵγ+βy = \dfrac{x - \operatorname{mean}(x)}{\sqrt{\operatorname{var}(x) + \epsilon}}\,\gamma + \beta, default ϵ=10−5\epsilon = 10^{-5} (nn.LayerNorm, v2.14.1). For a constant row, without ϵ\epsilon the result is 0/0=0/0 = NaN; with it, 0×1/10−5=0×316.2=00 \times 1/\sqrt{10^{-5}} = 0 \times 316.2 = 0. It also caps the gain for nearly constant rows at 316.
  • RMSNorm, y=x/ϵ+1n∑ixi2y = x / \sqrt{\epsilon + \tfrac1n\sum_i x_i^2}: PyTorch's default ϵ\epsilon is now the machine epsilon of the compute type, 1.19×10−71.19 \times 10^{-7} for float16, bfloat16 and float32 inputs (docstring, v2.14.1); model configs set their own (SmolLM2-135M: rms_norm_eps 10−510^{-5}).
  • Adam divides by vˆ+ϵ\sqrt{\hat v} + \epsilon with default ϵ=10−8\epsilon = 10^{-8} (torch.optim.Adam, v2.14.1). In float16, 10−810^{-8} is below the smallest subnormal (6×10−86 \times 10^{-8}) and becomes 0: one reason optimiser state stays in float32.
  • Even 10−510^{-5} is not a normal float16 number: it is a subnormal (stored as 1.0014×10−51.0014 \times 10^{-5}; smallest normal 6.1×10−56.1 \times 10^{-5}). Autocast runs layer_norm, group_norm and norm in float32 for this kind of reason (amp docs).
FunctionFails whenStable formPyTorch
ln⁡∑ez\ln\sum e^{z}any z>88.7z \gt 88.7 (fp32)m+ln⁡∑ez−mm + \ln\sum e^{z - m}logsumexp
ln⁡softmax⁡\ln \operatorname{softmax}a probability underflowsz−LSE⁡(z)z - \operatorname{LSE}(z)log_softmax, cross_entropy
ln⁡σ(x)\ln\sigma(x)x<−88.7x \lt -88.7min⁡(x,0)−log1p⁡(e−|x|)\min(x,0) - \operatorname{log1p}(e^{-|x|})logsigmoid
BCE of σ(x)\sigma(x)σ(x)\sigma(x) rounds to 0 or 1 (|x|≳17|x| \gtrsim 17 in fp32)max⁡(x,0)−xy+log1p⁡(e−|x|)\max(x,0) - xy + \operatorname{log1p}(e^{-|x|})binary_cross_entropy_with_logits
ln⁡(1+ex)\ln(1 + e^{x})x>88.7x \gt 88.7max⁡(x,0)+log1p⁡(e−|x|)\max(x,0) + \operatorname{log1p}(e^{-|x|})softplus
ln⁡(1+x)\ln(1 + x), ex−1e^{x} - 1|x|≪1|x| \ll 1direct serieslog1p, expm1
variancelarge mean, small spreadtwo-pass or Welfordvar, norms (Welford)
x/‖x‖x / \lVert x \rVertx=0x = 0x/max⁡(‖x‖,ϵ)x / \max(\lVert x \rVert, \epsilon)F.normalize (ϵ=10−12\epsilon = 10^{-12})

"|x|≳17|x| \gtrsim 17": float32 σ(x)\sigma(x) equals 1 once e−xe^{-x} is below half of float32's gap under 1 (2−252^{-25}), that is for x>25ln⁡2=17.3x \gt 25 \ln 2 = 17.3 (derived). The chart above shows it.

9. Mixed-precision training: master weights, loss scaling, and why bf16 skips it

The recipe that made 16-bit training work is Micikevicius et al. 2017: "maintaining a master copy of weights in FP32, loss-scaling that minimizes gradient values becoming zeros, and FP16 arithmetic with accumulation in FP32". Each of the three fixes one failure of model.half(). To see the failures on a real model, this page ran one training step of SmolLM2-135M (134,515,008 parameters, 30 layers) on 4 sequences of 128 tokens of Tiny Shakespeare: in float32 on the CPU as the reference (loss 3.5607), then in pure float16 and pure bfloat16 on the laptop's GPU (MPS), keeping every one of the 134.5 million gradients (measured; src/inputs/measure_b.py).

Failure 1: small updates vanish (fix: float32 master weights)

A weight update is the learning rate times something of order one (Adam's normalised step). Added to a 16-bit weight, it disappears whenever it is below half the weight's gap (section 2). On SmolLM2's real weights (median |w|=0.107|w| = 0.107), the fraction an update of size η\eta would not change at all:

Update size η\etafloat32 weightsfloat16 weightsbfloat16 weights
10−310^{-3}0%0.00005%1.3%
10−410^{-4}0%15.2%83.8%
10−510^{-5}0%83.8%97.9%

Measured: (w.to(dtype) - eta * sign(g).to(dtype)) == w.to(dtype) over all 134.5M weights. The two 83.8% cells are the same weights: both conditions reduce to |w|≥2−5|w| \ge 2^{-5}. Typical LLM learning rates are 10−410^{-4} to 10−310^{-3}, decayed lower at the end of training.

At a median weight of 0.107, bfloat16's gap is 2−11=0.000492^{-11} = 0.00049, so any step below 0.000240.00024 is lost: most of a run at learning rate 10−410^{-4} would not train. The fix is a float32 master copy: the optimiser adds the update in float32 and a 16-bit copy is made for the next forward pass. The bytes this costs (2 + 2 + 4 + 4 + 4 = 16 per parameter with Adam) are counted on Quantization and precision.

Failure 2: small gradients underflow (fix: loss scaling, float16 only)

In the float32 reference step the median |g||g| is 3.2×10−53.2 \times 10^{-5}, below float16's smallest normal number (2−14=6.1×10−52^{-14} = 6.1 \times 10^{-5}): 68% of SmolLM2's gradients live in float16's subnormal range, 7.2% are below its smallest subnormal 2−242^{-24}, and 5.0% are below 2−252^{-25} and round to exactly 0 when cast (measured). The 2017 paper found the same order on a speech model: "approximately 5% of weight gradient values have exponents smaller than −24-24". Loss scaling multiplies the loss by SS before the backward pass; by the chain rule every gradient is multiplied by SS, shifting the histogram right by log2⁡S\log_2 S binades; the gradients are divided by SS in float32 before the update, so the step is unchanged. Too small an SS leaves gradients in the underflow zone; too large pushes the largest past 65,504 into infinity. Predict the largest safe kk, then drag:

SmolLM2-135M's real gradients slide into float16's range, until the top falls off the end

Bars: how many of the 134.5M gradients fall in each binade [2e,2e+1)[2^{e}, 2^{e+1}) (float32 reference step, measured), shifted by the loss scale. Shading: float16 rounds to 0 (left of 2−252^{-25}), subnormal (2−252^{-25} to 2−142^{-14}), normal, overflow (right of 2162^{16}).

The slider reads the float32 histogram; the real float16 runs are the ground truth (pure float16 forward and backward on MPS, every gradient compared with the float32 one):

So on this model a static scale between 282^{8} and 2162^{16} works and 2202^{20} is fatal: one overflow in the backward pass becomes infinity, then NaN, and spreads to 96.5 million gradients. Because the right scale changes during training, frameworks adjust it. PyTorch's GradScaler starts at init_scale=2.0**16; when a step produces inf or NaN gradients it skips the step and multiplies the scale by backoff_factor=0.5, and after growth_interval=2000 clean steps it multiplies by growth_factor=2.0 (grad_scaler.py, lines 123 to 131, v2.14.1). The loop: scaler.scale(loss).backward(), scaler.step(opt), scaler.update(), and scaler.unscale_(opt) before gradient clipping, so the threshold applies to the true gradients.

What the 2017 paper itself reported

An update becomes zero "when the magnitude of a normalized weight value is at least 2048 times larger that of the weight update" (float16 has 10 mantissa bits, 211=20482^{11} = 2048); on their Mandarin speech model, dropping the float32 master copy cost "80% relative accuracy loss" (§3.1). An SSD detector "diverges when gradients are not scaled, but scaling them by a factor of 8 (increasing the exponents by 3) is sufficient", and the factors used across its models ranged "from 8 to 32K"; it proposed, without running it, a dynamic scale that is lowered and the step skipped on overflow.

Why bfloat16 mostly does not need loss scaling

bfloat16 has float32's 8 exponent bits, so its smallest normal number is 1.2×10−381.2 \times 10^{-38}; SmolLM2's smallest gradient is 2−51≈4×10−162^{-51} \approx 4 \times 10^{-16}, 22 orders of magnitude inside the range. In the pure bfloat16 run only 0.00005% of gradients became 0, with no scaling. bfloat16's problem is the other axis: with 8 significant bits its gradients had a median relative error of 4.8%, against 0.55% for float16 at a good scale (measured). Range is fixed by the format; precision by float32 master weights and float32 accumulation. Google: "Unlike FP16, which typically requires special handling via techniques such as loss scaling, BF16 comes close to being a drop-in replacement for FP32" (Wang and Kanwar 2019). "Mostly": hardware that flushes bfloat16 subnormals (section 1) has a smaller range at the bottom, and FP8 and 4-bit training are back to needing scales, per tensor or per block. The standard loop is with torch.autocast("cuda", dtype=torch.bfloat16) around the forward pass, with float32 parameters and optimiser.

Failure 3: large activations overflow (fix: bf16, or keep the risky ops in float32)

float16's 65,504 is reachable inside a network: attention scores before the softmax, the sum of squares inside a norm, a residual stream with outlier features, the logits of a large vocabulary. One overflow gives ∞\infty, the next softmax gives NaN. That is why autocast keeps exactly those operations in float32 (softmax, layer_norm, norm, sum, exp, the losses; section 7) and runs matrix multiplies in 16 bits with float32 accumulation.

10. NaN hunting: where non-finite numbers come from and how to find the first one

Step 41,200 logs loss: nan and every weight is now NaN. NaN never appears from nowhere: some operation received an input outside its domain or produced a result outside the format's range, and from there it spreads through every operation that touches it. The stage follows one NaN through a linear layer Y=XWY = XW with a mean loss, one training step and the next forward pass; every cell is a real IEEE 754 result of the stated operation, on illustrative sizes (3 tokens, 4 features, 3 outputs) and illustrative values.

  1. Forward: one NaN in the input. Token 2, feature 3 of XX is NaN (say an overflowed activation upstream). Each output in row 2 of YY is a sum that includes NaN times a weight, so the NaN flows along its row into every output of token 2; rows 1 and 3 are fine.
  2. The loss is NaN. The mean loss adds every entry of YY, row 2 included. A check written as loss > 10 is false for NaN and never fires.
  3. Backward: one row of weight gradients. ∂L/∂Y\partial L / \partial Y of a mean is 1/91/9 everywhere, finite. But ∂L/∂W=X⊤∂L/∂Y\partial L / \partial W = X^{\top} \partial L / \partial Y: row 3 of it sums column 3 of XX, which holds the NaN, so that whole row of the gradient is NaN.
  4. Update, then the next forward pass: everything. The optimiser writes NaN into row 3 of WW. Every output of the next forward pass uses that row (feature 3 times row 3), so every entry is NaN, for every token, and the run is over.
OperationResultTypical ML cause
exe^{x}, x>88.72x \gt 88.72 (fp32) or >11.09\gt 11.09 (fp16)∞\inftynaive softmax or sigmoid, an exponentiated log-variance
any result above 65,504 in fp16∞\inftyattention scores, sums of squares, large activations, too large a loss scale
∞/∞\infty / \infty, ∞−∞\infty - \infty, 0×∞0 \times \inftyNaNnormalising by an overflowed sum; Adam's m/vm / \sqrt{v} once both overflow
0/00 / 0NaNa norm or standard deviation of a zero or constant vector without ϵ\epsilon
ln⁡0\ln 0, x/0x / 0−∞-\infty, ±∞\pm\inftylog of an underflowed probability; division by an underflowed count
ln⁡x\ln x, x\sqrt{x} for x<0x \lt 0NaNa variance that cancelled to a negative number (section 4)
arccos⁡x\arccos x, |x|>1|x| \gt 1NaNa cosine similarity that rounds to 1.00000011.0000001 (measured: torch.acos(torch.tensor(1.0000001)) is NaN; clamp first)
gradient of x\sqrt{x} at 0∞\inftyan L2 norm of a zero vector inside the loss (measured: the gradient is inf)

A real hunt, on the running example (PyTorch 2.14.1, measured, src/inputs/nan_demo.py): the naive softmax cross-entropy on (1000,999,0)(1000, 999, 0), target sat, returns loss = inf, not NaN (psat=1/∞=0p_{\text{sat}} = 1/\infty = 0, −ln⁡0=∞-\ln 0 = \infty), and the backward pass returns gradients [nan, nan, nan]. Wrapped in torch.autograd.detect_anomaly(), it stops at the culprit: Function 'DivBackward0' returned nan values in its 0th output, the division by the overflowed sum. The fused F.cross_entropy on the same logits returns 1000.3132 with gradient [0.7311, 0.2689, -1.0].

  1. Check where it first appears. Log the loss and the global gradient norm every step; a norm that jumps by orders of magnitude a few steps before the NaN points to an instability (learning rate, a layer's logits growing), not a single bad operation. With GradScaler, a few skipped steps are normal; skipped steps every iteration are not.
  2. Find the first non-finite activation with a forward hook on every module that checks torch.isfinite(output).all() and records the module name; the first to fail is the culprit, everything after it collateral.
  3. Find the first non-finite gradient. torch.autograd.detect_anomaly() (or set_detect_anomaly(True)) records forward tracebacks so the backward error can name "the forward operation that created the failing backward function", and with check_nan=True "any backward computation that generates 'nan' value will raise an error"; "This mode should be enabled only for debugging" (anomaly_mode.py, v2.14.1).
  4. Replay the batch with the saved weights in float32, then float64. If float64 is finite, it is a precision or range problem (section 3); if not, it is the data or the maths (a log of 0, a division by a zero norm).
  5. Fix the cause, not the symptom: the stable form (sections 7 and 8), the risky operation in float32, a lower learning rate or clipping for an instability. torch.nan_to_num on a loss hides the evidence; skipping a step on a non-finite loss is acceptable only as a guard while you look.
Two published instabilities with this shape

Two published instabilities had this shape, and the fixes are architectural (owned by Normalisation, residuals and stability): PaLM's auxiliary z-loss, 10−4⋅log2⁡Z10^{-4} \cdot \log^2 Z, keeps the softmax normaliser near 1; ViT-22B saw attention logits "grow to over 50000 in magnitude" without normalisation, near float16's 65,504, and fixed it by applying LayerNorm to queries and keys (Dehghani et al. 2023, appendix B).

Depth: research directions and a mistakes checklist

Where research is now (2026)
  • Fewer bits for training. FP8 training at 671B parameters with fine-grained scaling (DeepSeek-V3, December 2024; the DeepSeek-V3 paper page animates it in its FP8 training section) and NVFP4 pretraining of a 12B model on 10 trillion tokens, "the longest publicly documented training run in 4-bit precision to date", using random Hadamard transforms, two-dimensional block scaling, stochastic rounding of gradients and a few layers kept in higher precision (NVIDIA, Sep 2025). Every ingredient is this page's: range (scales), precision (rounding), and accumulation. Depth: Quantization and precision.
  • 16-bit-only training. Can the float32 master copy go? Zamirai et al. show nearest rounding "cancels small updates" in bf16 and that stochastic rounding and Kahan summation on the weight update recover "0.1% lower to 0.2% higher validation accuracy compared to 32-bit training" across seven applications (2020).
  • Determinism as a feature. Batch-invariant kernels make inference reproducible at a speed cost (Thinking Machines 2025); on-policy reinforcement learning needs the sampler's and the trainer's log-probabilities to match bit for bit.
  • Accurate kernels, one pass. Online softmax (Milakov and Gimelshein 2018) inside FlashAttention, with error analysis of shifted log-sum-exp and softmax (Blanchard, Higham and Higham 2021).
  • Stability by architecture. QK normalisation, z-loss and softmax capping keep logits in range so that low precision survives (section 10).
Mistakes checklist (each with the section that explains it)
  • Comparing floats with ==: 0.1+0.2≠0.30.1 + 0.2 \ne 0.3 in every binary format; compare with torch.testing.assert_close or math.isclose(a, b, rel_tol=...), a few times the dtype's ε\varepsilon (section 2).
  • torch.log(torch.softmax(z)) or Sigmoid then BCELoss: use log_softmax, cross_entropy on logits, binary_cross_entropy_with_logits (sections 7 and 8).
  • A running sum, metric or optimiser state in bf16: a bf16 running sum of ones stops at 256; a bf16 sum of a thousand numbers in [0,1)[0, 1) is 50% low (section 5). Keep master weights and Adam's moments in float32.
  • Believing machine epsilon is the smallest positive number: ε\varepsilon is the gap above 1; the smallest positive float32 is 1.4×10−451.4 \times 10^{-45} and the smallest normal 1.18×10−381.18 \times 10^{-38}; libraries' eps is 2u2u.
  • fp16 without a loss scaler, or bf16 with one "to be safe": fp16 without scaling silently zeroes gradients (8.2% on SmolLM2); bf16 does not need one, and a misconfigured scaler only adds skipped steps (section 9).
  • Clipping gradients before unscaling them: with GradScaler they are SS times too large until scaler.unscale_(optimizer).
  • Expecting bit-identical results across GPUs, batch sizes or thread counts: compare with tolerances; for exact reproducibility fix hardware, versions, batch shapes and use deterministic algorithms (section 6).
  • A variance as x2−x‾2\overline{x^2} - \bar x^2: −8-8 on three float32 numbers near 10,000; use two passes or Welford (section 4).
  • Logits or targets in bf16: 999 and 1000 are the same bfloat16 number, so are 256 and 257; keep logits, losses and anything compared by small differences in float32.
  • Trusting an FP8 cast's overflow behaviour: PyTorch saturates 1000→4481000 \to 448 in E4M3, ml_dtypes returns NaN (section 3).
  • Letting the compiler reassociate: fast-math flags can delete Kahan's correction term as algebraically zero (section 5).

Practice: the root's Gradient lab, panel 5, pushes a logit past each format's overflow point.