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 , 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.
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; 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 for the words cat, dog and sat, target sat, loss ; and the same three words with logits , 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.
| Idea | In one line | One number to remember | Where ML meets it |
|---|---|---|---|
| Floating point | sign, exponent (range), mantissa (precision) | loss in fp32 is 0 10000000 0011010... | every tensor |
| Machine epsilon, rounding | relative gap between neighbours; results round to the nearest, ties to even | fp32 ; bf16 | what "precision" means |
| ML formats | trade mantissa bits for speed and memory; exponent bits decide the range | fp16 max ; bf16 max | training and serving dtypes |
| Cancellation | subtracting nearly equal numbers leaves only the rounding error | one-pass fp32 variance of three numbers: | variance, log near 1, norms |
| Summation | adding in a different order gives a different answer; long sums drift | fp16 running sum of ones stops at | reductions, accumulators |
| Determinism | parallel hardware changes the order, so results change | MPS index_add_: 20 different results in 20 runs | reproducibility, batch invariance |
| Stable softmax | subtract the max logit first; work in logs | for | every classifier and LLM |
| Stable toolbox | log1p, expm1, logsigmoid, BCE with logits, Welford, epsilon | naive in fp32: | losses, norms |
| Mixed precision | 16-bit compute, fp32 master weights; scale the loss in fp16 | SmolLM2 in pure fp16: 8.2% of gradients become 0 | training recipes |
| NaN hunting | find the first operation that made inf or NaN | NaN | debugging 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.
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.
In binary each place is worth twice the place to its right, and places after the point are worth . A fraction has a finite binary expansion only if its denominator is a power of two, so repeats forever and any fixed number of bits must cut it off: that is why prints as 0.30000000000000004 in Python (measured). ML needs (a small gradient) and (a large activation) in the same tensor; an evenly spaced grid fine enough for the first needs about steps, about 41 bits, to reach the second. So numbers are stored in base-2 scientific notation, with : . 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.
An unsigned 8-bit integer holds to . For negative numbers every modern machine uses two's complement: the top bit is worth instead of , so int8 holds to and . Adding uses the same circuit as unsigned addition, and negating is "flip every bit, add 1" (, flipped , plus one ). The price is that integers wrap around: in int8, (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 elements, the size of a single large embedding or attention tensor.
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:
The loss, by hand. The exact loss lies between 2 and 4, so and . The significand is ; its fractional part times is , which rounds to . Read back, : off by , a relative error of . struct.pack('>f', loss).hex() gives 401a1637, the same 32 bits (measured). The card does the same for other values and formats:
The two extreme exponent fields are reserved. Every ML bug involving NaN starts in this table:
| Exponent field | Fraction | Meaning | Value (float32) |
|---|---|---|---|
| 1 to 254 | anything | normal | : from to |
| 0 | 0 | zero | or : two zeros, equal when compared; |
| 0 | not 0 | subnormal (denormal) | : no hidden 1, so fewer significant bits; down to |
| 255 | 0 | infinity | : the result of overflow, or of |
| 255 | not 0 | NaN ("not a number") | the result of , , , , ; 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 (gradual underflow), so only when (Goldberg 1991, "Denormalized Numbers"); without them the gap between 0 and would be times wider than the gap just above it. The price: 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 ; torch.finfo(torch.float32) prints the constants (eps, max, smallest_normal, tiny).
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 , not (bfloat16's smallest subnormal).
Between two consecutive powers of two, and (one binade), a format with significant bits has exactly 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 between 1 and 2 and 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 (: 8 values per binade) is small enough to draw every value:
Machine epsilon is the gap between 1 and the next float. The unit roundoff is the largest relative error of one rounding: libraries report (torch.finfo(...).eps, C's FLT_EPSILON), numerical analysis texts write (Higham 2002, chapter 2), and mixing them up is a factor of two. bits are about 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 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 .
Take with . Neighbouring floats there are apart, so the nearest one is at most half that away: . Divide by :
Here means " rounded to the format". Check on the loss: float32 ; float16 , error ; bfloat16 , error (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%.
IEEE 754 requires every basic operation ( 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:
| Sum | Neighbours | Result | Why |
|---|---|---|---|
| float16 | and | exactly halfway; 1 has last bit 0 (even) | |
| float16 | and | halfway; is the even one, so the tie goes up | |
| bfloat16 | and | halfway, 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 sits a fraction of the way from to the next float , return with probability , so . Example (derived): a bfloat16 weight sits where the gap is ; an update of is 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 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 that becomes units of the new scale is rounded by nearest to (so ) every time, but stochastically to three times in four and once, 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).
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).
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.
| Format | sign / exp / mantissa | bias | largest | smallest normal | smallest subnormal | overflows at | First defined | |
|---|---|---|---|---|---|---|---|---|
| float64 | 1 / 11 / 52 | 1023 | 709.78 | IEEE 754-1985 (2019 edition) | ||||
| float32 | 1 / 8 / 23 | 127 | 88.72 | IEEE 754-1985 | ||||
| TF32 | 1 / 8 / 10 | 127 | n/a | 88.72 | NVIDIA A100, 14 May 2020 (Ampere in depth) | |||
| float16 | 1 / 5 / 10 | 15 | 11.09 | IEEE 754-2008 (binary16) | ||||
| bfloat16 | 1 / 8 / 7 | 127 | 88.72 | Google Brain for TPUs (blog, Aug 2019) | ||||
| FP8 E4M3 | 1 / 4 / 3 | 7 | 6.10 | Micikevicius et al., Sep 2022; OCP OFP8 rev. 1.0, approved 20 Jun 2023 | ||||
| FP8 E5M2 | 1 / 5 / 2 | 15 | 10.96 | same two documents |
for mantissa bits. "Largest" is for the IEEE-style formats and for E4M3, whose top exponent holds numbers (only S.1111.111 is NaN, and there is no infinity: OFP8 spec, table 2). " overflows at" is 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).
The stage stores the running example's loss, , 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.
10000000 (128, so ), then 23 fraction bits: 0 10000000 00110100001011000110111, which reads back as .10000 = 16, still ) and TF32's 10 mantissa bits: the same , relative error , but the range now ends at 65,504.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.
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 rounds to 1024 in both. Know which one your kernel does before you trust an FP8 tensor's max.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 ( in float32), as long as it neither overflows nor underflows.
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 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 is backward stable, and
So there are two separate ways to get a bad answer: a badly conditioned problem (large : 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.
Subtracting two nearly equal floats is exact (the Sterbenz lemma: if , then is a float), but it exposes the rounding errors the two numbers already carried, now measured against a tiny result:
The rule: when , the relative error of is the inputs' relative error times , and the fix is always to rewrite the formula so the subtraction of nearly equal quantities never happens.
3f800347), relative error , within . Subtracting 1 is exact, but the four leading digits that agreed are gone and the result has a relative error of : the input's own error times , within the bound . Green: correct digits; orange: digits that are rounding noise. Derived, src/derive_new_visuals.py.Measured with : in float32, rounds to 1 (the gap above 1 is ), so , 100% error; in float64, , a relative error of , which is times float64's : eight of sixteen digits gone because was rounded first.
How much does a small relative change in change ? Divide the two relative changes and let the input change shrink to zero:
An input known to relative accuracy gives an output known to about , whatever algorithm you use. Worked values (derived):
| At | Meaning | |||
|---|---|---|---|---|
| 10,001 | 4 of float32's 7 digits are lost (the figure above) | |||
| 10,000 | near 1 is ill-conditioned in : pass instead (log1p) | |||
| 1,000 | large logits amplify their own errors | |||
| any | 0.5 | harmless | ||
| 0.9994 | perfectly well-conditioned: overflow there is the algorithm's fault |
The last row uses , the softmax; for several inputs the condition number sums and divides by . Matrices have their own condition number, : Linear algebra, section 11, where the float32 normal equations lose 77% of the answer and QR keeps it.
log1p and expm1 compute and directly from , with no rounded to cancel: at in float64, log(1 + x) keeps about 8 correct digits and log1p(x) all 16 (measured). Section 8 uses both inside softplus and BCE.
Measured in float64 at : log(1 + x) gives (relative error ), log1p(x) gives ; exp(x) - 1 is off by the same and expm1(x) is exact.
The variance expanded into the one-pass "computational formula" subtracts two huge, nearly equal numbers. Measured in float32 on three numbers near 10,000 (stored as , , ; exact variance of the stored values ):
| Method | float32 result | What happened |
|---|---|---|
| one pass, | , where float32's gap is 32; the true difference, 0.02, is far below one gap. A variance cannot be negative: of it is NaN. | |
| two passes: mean first, then | the subtraction happens before squaring, on numbers of size 0.1 | |
| Welford, one pass | updates the mean and the sum of squared deviations together; 0.7% off here, never negative |
Welford's algorithm (Welford 1962) keeps a running mean and sum of squared deviations , so nothing large is ever subtracted from something large:
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 into NaN.
and , so (measured, float32).
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: but ; but , because near the gap is 2, so is a tie that rounds back and the 1 is absorbed. Addition is still commutative ( exactly); it is chains of additions in different orders that differ.
Adding left to right (recursive summation), and pass through roundings, through , and so on, so to first order in
, , and so on. Multiplying out, . Each product of at most factors lies within . Subtract the exact sum and bound each term by . The full statement with the term is in Higham 2002, chapter 4.
The bound grows with and is relative to , 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 , where the gap becomes 2 and adding 1 is a tie that rounds back (to even). Three fixes:
sum docstring).Read Kahan's four lines as: is the new term corrected by last step's loss; is the rounded new sum; is what actually got added, so is minus what was lost. In exact arithmetic 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.
The same error growth on many numbers: add 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 ): the naive 16-bit running sum is useless past a few thousand terms (float16 59% low at , bfloat16 50% low at ); pairwise and Kahan stay within one rounding; Kahan in bfloat16 fails at (87% error) exactly as its bound warns, since is no longer small; the float32 accumulator is the best by orders of magnitude. At 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 ); 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.
recompute.py reproduces the uniform cases at , 1,000 and 10,000 in NumPy.Sum the first of a million numbers drawn uniformly from , 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.
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.
src/derive_new_visuals.py.Measured on this laptop:
| Experiment | Distinct results | Note |
|---|---|---|
| 8 numbers (exact sum 0), 10,000 shuffles, plain left-to-right loop | 258 | results from to |
same, Python 3.13 built-in sum | 102 | reproduces the 102 printed by Thinking Machines, 10 Sep 2025 |
| normal float32 values, sequential fp32 sum, 20 random orders | 20 of 20 | spread 0.0043 around the exact 29.3288 |
torch.sum of float32 on the CPU, 5 runs each at 1, 2, 4, 8 threads | 1 per thread count, 3 overall | 1 or 2 threads , 4 threads , 8 threads (exact ) |
index_add_ of float32 into 10 slots, 20 runs, Apple GPU (MPS) | 20 of 20 | the 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.
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.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).A.sum(-1)[0] "is not guaranteed to be bitwise equal" to the sum of the slice (numerical accuracy notes).The softmax turns logits into probabilities, and the loss is the negative log of the target's:
For : , , , sum , so and the loss for the target sat is . Now take . is about , past float32's largest value () and even float64's (), so it rounds to ; the sum is , 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 . Only the algorithm fails.
Multiply the top and bottom by the same ; the value is unchanged for any :
Then every exponent is at most 0, every lies in , nothing can overflow, and the denominator lies between 1 (the largest term is exactly ) and . Terms that underflow to 0 are far below 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:
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.
cross_entropy measured the same: , .The values at this step, as stored bits
For : , that is (derived; the old Topic: math child page's example, logits , gives the same way, rechecked). Never take the log of a softmax: underflows to 0 even in float64 (smallest about ), and , while the log-softmax gives : a huge, honest, finite loss, with gradient . For the same reason every likelihood is a sum of logs: 1,000 tokens each with probability 0.1 have likelihood , which underflows even float64, while its log, , 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).
The stable softmax reads the logits twice (max, then sum). Milakov and Gimelshein update both in one pass (2018): keep the running max and the running sum , and rescale the old sum when the max changes:
On : ; then ; then , 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 entries go through the same formulas. The error analysis of the shifted formulas is Blanchard, Higham and Higham 2021.
torch.logsumexp is exactly the formula above, with one extra guard: if the max is infinite (a row of all , as in a fully masked attention row), it shifts by 0 instead, so the result is rather than NaN from :
// 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 , sum and multiply by the reciprocal (SoftMaxKernel.cpp, lines 60 to 91). Excerpts are saved in src/inputs/pytorch_v2.14.1/excerpts.txt.
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 for every . Predict where the naive binary cross-entropy breaks in float16, then switch the format:
logsigmoid. The sigmoid gives a probability from one logit, and its log appears in every binary loss. Naively, in float32: overflows (past ), , (measured); the true value is . Splitting on the sign gives one formula:
Binary cross-entropy with logits. For a logit and a label (or a soft label in ), , and with :
Worked: , gives ; gives (derived). Naively in float32 with , : rounds to exactly 1, , loss (measured); the stable form gives . PyTorch v2.14.1 computes (1 - target).mul_(input).sub_(log_sigmoid_input), the middle form (Loss.cpp, lines 349 to 364). softplus, , is the same shape: naively in float32 (measured); stably .
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 and DPO's loss are exactly a logsigmoid.logsigmoid. For , . For , multiply top and bottom by : , so . 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: , and (from ). Substitute: , which collects to , and the logsigmoid line gives the last form.
softplus is a smooth ReLU and the negative of . PyTorch's nn.Softplus(beta=1.0, threshold=20.0) takes a shortcut: when it returns unchanged. What it drops, , is a thousand times smaller than float32's gap at 20 (), 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 , not machine epsilon: LayerNorm's default turns a constant row's into 0; Adam's is itself 0 in float16, one reason optimiser state stays in float32.
nn.LayerNorm, v2.14.1). For a constant row, without the result is NaN; with it, . It also caps the gain for nearly constant rows at 316.rms_norm_eps ).torch.optim.Adam, v2.14.1). In float16, is below the smallest subnormal () and becomes 0: one reason optimiser state stays in float32.layer_norm, group_norm and norm in float32 for this kind of reason (amp docs).| Function | Fails when | Stable form | PyTorch |
|---|---|---|---|
| any (fp32) | logsumexp | ||
| a probability underflows | log_softmax, cross_entropy | ||
logsigmoid | |||
| BCE of | rounds to 0 or 1 ( in fp32) | binary_cross_entropy_with_logits | |
softplus | |||
| , | direct series | log1p, expm1 | |
| variance | large mean, small spread | two-pass or Welford | var, norms (Welford) |
F.normalize () |
"": float32 equals 1 once is below half of float32's gap under 1 (), that is for (derived). The chart above shows 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).
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 ), the fraction an update of size would not change at all:
| Update size | float32 weights | float16 weights | bfloat16 weights |
|---|---|---|---|
| 0% | 0.00005% | 1.3% | |
| 0% | 15.2% | 83.8% | |
| 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 . Typical LLM learning rates are to , decayed lower at the end of training.
At a median weight of 0.107, bfloat16's gap is , so any step below is lost: most of a run at learning rate 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.
In the float32 reference step the median is , below float16's smallest normal number (): 68% of SmolLM2's gradients live in float16's subnormal range, 7.2% are below its smallest subnormal , and 5.0% are below 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 ". Loss scaling multiplies the loss by before the backward pass; by the chain rule every gradient is multiplied by , shifting the histogram right by binades; the gradients are divided by in float32 before the update, so the step is unchanged. Too small an leaves gradients in the underflow zone; too large pushes the largest past 65,504 into infinity. Predict the largest safe , then drag:
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 and works and 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.
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, ); 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.
bfloat16 has float32's 8 exponent bits, so its smallest normal number is ; SmolLM2's smallest gradient is , 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.
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 , 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.
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 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.
loss > 10 is false for NaN and never fires.| Operation | Result | Typical ML cause |
|---|---|---|
| , (fp32) or (fp16) | naive softmax or sigmoid, an exponentiated log-variance | |
| any result above 65,504 in fp16 | attention scores, sums of squares, large activations, too large a loss scale | |
| , , | NaN | normalising by an overflowed sum; Adam's once both overflow |
| NaN | a norm or standard deviation of a zero or constant vector without | |
| , | , | log of an underflowed probability; division by an underflowed count |
| , for | NaN | a variance that cancelled to a negative number (section 4) |
| , | NaN | a cosine similarity that rounds to (measured: torch.acos(torch.tensor(1.0000001)) is NaN; clamp first) |
| gradient of at 0 | an 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 , target sat, returns loss = inf, not NaN (, ), 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].
GradScaler, a few skipped steps are normal; skipped steps every iteration are not.torch.isfinite(output).all() and records the module name; the first to fail is the culprit, everything after it collateral.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).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 had this shape, and the fixes are architectural (owned by Normalisation, residuals and stability): PaLM's auxiliary z-loss, , 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).
==: in every binary format; compare with torch.testing.assert_close or math.isclose(a, b, rel_tol=...), a few times the dtype's (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).eps is .GradScaler they are times too large until scaler.unscale_(optimizer).Practice: the root's Gradient lab, panel 5, pushes a logit past each format's overflow point.
Type any number, or move the slider, and see what each format stores: its bits (sign, exponent, mantissa), the value you get back, the rounding error, the gap to the neighbouring numbers, and what happens at the edges (subnormals, underflow to 0, overflow to infinity or, in FP8 E4M3, saturation or NaN). Click any bit to flip it: the number the new bits encode becomes the input. Every format is emulated exactly by this page's code, which matches ml_dtypes and NumPy on 17,610 test values (recompute.py). It extends Reading sections 1 to 3; block formats (MXFP4, NVFP4, NF4) are in the Quantization and precision page's Bit explorer.
"Gap here" is one ulp at this magnitude; "relative error" is , at most for normal numbers. TF32 is shown as the 19 bits a tensor core reads, rounded to nearest even here; in memory it is a float32, and PyTorch's notes say the tensor core reads "only the first 10 bits of the input mantissa", which would truncate instead and can differ by one step. float64 is JavaScript's own number type, so it is exact by construction. Neighbour buttons step to the next representable number down or up.
Reading times for knowledge base pages are each page's own stated time where it gives one, otherwise estimated from the length of its Reading tab (about 230 words a minute). Times for outside resources are for the part recommended, checked on 5 October 2026. Every link opens in a new tab.
Any number in float64, float32, TF32, bfloat16, float16, FP8 E5M2 and E4M3: bits you can flip, stored value, rounding error, gap, neighbours, and what adding a small does.
One prediction of a tiny next-token model followed through one training step; this page's running example (logits , loss 2.408) comes from it. Tabs: Notation decoder, Gradient lab (its panel 5, "Overflow and the log-sum-exp trick", is the short version of section 7 here). 16 min, plus 6 in closed details.
Vectors to SVD; its section 11 is the condition number of a matrix, with a float32 normal-equations run that loses 77% of the answer. 45 min, plus 13 in closed details.
Jacobians, layouts, vector-Jacobian products and autodiff: where the gradients that underflow in section 9 come from, and derived. 32 min, plus 22 in closed details.
Distributions to losses, MLE, MAP, Bayes; why log-likelihoods are summed in log space. 32 min, plus 16 in closed details.
Estimation, bias and variance, bootstrap, hypothesis tests; the estimators whose computation section 4 makes stable. 33 min, plus 6 in closed details.
Derivatives to convexity, Hessians, Newton, Lagrange; the derivative inside the condition number of section 4. 32 min, plus 11 in closed details.
Entropy, cross-entropy, KL; why the softmax loss is a cross-entropy and why assigning probability exactly 0 makes it infinite. 38 min, plus 8 in closed details.
ELBO, VAEs, diffusion: log-likelihoods and log-variances that need every trick in section 8. 23 min, plus 18 in closed details.
The 8- and 4-bit side in depth: INT8, INT4, NF4, GPTQ, AWQ, MXFP4, NVFP4, FP8 training recipes, outliers; formats and block scales in sections 1 and 2, GPTQ, AWQ and outliers in sections 3 and 4. 25 min, plus 10 in closed details.
FP8 training at 671B: tile and block scaling and promotion to FP32 every 128 elements, animated in Quantise and accumulate. About 32 min.
QK-norm, logit caps and z-loss: the architectural fixes that keep logits inside the formats of section 3 (section 10 here names them). About 31 min.
The online softmax of section 7 inside a fused attention kernel; Run the kernel tab. About 20 min.
Why an LLM service does not give the same answer twice (temperature, batch invariance) and what that means for testing. 28 min, plus 15 in closed details.
Where reductions across GPUs (all-reduce, reduce-scatter) add numbers in an order set by the network. 32 min, plus 5 in closed details.
The classic tutorial: rounding error, guard digits, cancellation, the IEEE standard, signed zero, denormals. Read sections 1 and 2. About 60 min.
The reference. Chapter 1 (principles: cancellation, conditioning, stability), chapter 2 (floating point, the standard model), chapter 4 (summation: recursive, pairwise, compensated). About 3 hours for the three chapters.
Rounding-error analysis of the shifted formulas of section 7. About 40 min.
One page: compensated summation. About 5 min.
The one-pass variance of section 4. About 5 min.
The standard itself (paywalled); the formats, rounding modes and special values of sections 1 and 2. Reference.
Master weights, loss scaling, FP32 accumulation; section 3 is the argument reproduced on SmolLM2 in section 9. About 25 min.
E4M3 and E5M2, table 1, and which tensors get which. About 20 min.
Tables 1 to 3: encodings, special values, saturating and non-saturating conversion. About 15 min.
Why bf16 keeps float32's exponent. About 10 min.
bf16 across image, speech, language and recommendation models. About 25 min.
4-bit pretraining at 12B and 10T tokens: Hadamard transforms, 2D scaling, stochastic rounding. About 40 min.
Stochastic rounding and Kahan summation instead of float32 master weights. About 30 min.
Non-associativity, atomics, batch invariance; the 80 unique completions. About 30 min.
The one-pass softmax. About 15 min.
Non-associativity, extremal values, TF32, reduced-precision reductions, denormal flushing on AMD. About 15 min.
Seeds, cuDNN, deterministic algorithms, DataLoader workers. About 10 min.
Which ops autocast to 16 bits and which to float32; the BCE note. About 15 min.
NumPy dtypes for bfloat16, FP8 and FP4, used to check every bit pattern here. About 5 min.
src/recompute.py (every worked number), src/inputs/measure_a.py (bits, summation, order, threads, MPS), src/inputs/measure_b.py (SmolLM2-135M training step), src/inputs/nan_demo.py, PyTorch v2.14.1 excerpts in src/inputs/pytorch_v2.14.1/, the OFP8 extract in src/inputs/ofp8_spec_extract.txt.