15.8 Problem set A: representation, rounding, and cancellation
A bigram that computes its loss in float64 numpy on tiny logits never meets a numerical problem. A trained model does. Its logits reach the hundreds, so exp overflows float32 at about and the naive softmax returns NaN. Its weights are stored in bf16 (the SmolLM2 checkpoint loaded in The Llama-family model: config, weight loading, and download in AI Engineering is), so rounding must match PyTorch exactly or parity checks fail in the last bit. Its evaluation sums per-token losses (The evaluation harness and the model zoo), and a float32 accumulator silently stops growing.
Concepts from other sections (16)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- logits: unnormalized log-scores that softmax turns into probabilities; here the table stores . Read more: 6.1 Byte bigram: counts, logits, safetensors v0 in AI Engineering
- BF16: a 16-bit float with float32’s sign and exponent and 7 mantissa bits; the top half of a rounded float32. Read more: 6.7 Safetensors for every dtype, atomic checkpoints, and the token stream in AI Engineering
- fp16: a 16-bit format with 5 exponent bits and 10 mantissa bits; finer precision but a maximum of 65504 and a smallest subnormal of . Read more: 17.1 Mixed precision, loss scaling, gradient accumulation, and activation checkpointing in AI Engineering
- Newton’s method: the iteration , jumping to the zero of the tangent line. Read more: 7.2 Newton’s Method
- ties to even: rounding a value exactly halfway between two representable numbers to the one with an even last bit. Read more: 23.2 Candle model runner (Llama + bigram, int4), Rust KV cache, sampler and PCG32 in AI Engineering
- Biased exponent: the stored exponent field , equal to the true exponent plus a bias (127 in float32, 15 in float16) so it can be stored unsigned. Read more: 15.1 IEEE 754 anatomy, ulps, and round to nearest even
- rounding error: the error from floating-point rounding, about in a difference quotient. Read more: 7.1 Derivatives and Finite Differences
- Variance: the expected squared distance from the mean; its square root is the standard deviation. Read more: 13.1 Random variables, expectation, variance, and normal draws by Box-Muller
- Log-sum-exp (LSE): , computed stably as . Read more: 15.2 Stable numerics: logsumexp, softmax, and compensated sums
- Subnormal: a value with exponent field 0, no implicit leading 1, and a fixed exponent , filling the gap between zero and the smallest normal. Read more: 15.1 IEEE 754 anatomy, ulps, and round to nearest even
- Bit view: reinterpreting the bytes of an array as another dtype without changing any bit, as opposed to a value cast. Read more: 15.1 IEEE 754 anatomy, ulps, and round to nearest even
- Negative log-likelihood (NLL): , the surprise of the true token under the model, in nats. Read more: 17.2 Perplexity, bits per byte, NLL accumulator
- Pairwise summation: recursive halving of a sum, with error growing like . Read more: 15.2 Stable numerics: logsumexp, softmax, and compensated sums
- Fused cross-entropy: the gradient computed directly from logits. Read more: 14.3 Matrix differentials, the trace trick, and closed-form VJPs
- Condition number: how much the exact answer of a problem moves relative to a change in its input. Read more: 15.3 Error analysis, condition numbers, and tolerance budgets
- Round to nearest, ties to even: IEEE 754’s default rounding, which breaks exact ties toward the code whose last kept bit is 0. Read more: 15.1 IEEE 754 anatomy, ulps, and round to nearest even
IEEE 754 anatomy, ulps, and round to nearest even emulates bf16 and fp16 rounding, and Stable numerics writes the stable reductions every later operation calls. This pen-and-paper set makes sure you can predict each of those failures by hand before you read the code that avoids it. It covers representation and rounding (q1 to q5) and cancellation and stable rewrites (q6 to q11, ending with a short proof). Problem set B continues with error bounds, Newton’s method, polynomial approximation, and low precision.
The proof in q11 uses the habits of Discrete math 1 problem set, and q10 relies on the fact, from Vectors, matrices, row-major layout, and matmul, that float sums depend on their order. Work each problem before opening its answer. Each answer gives the final value, the derivation, and the common wrong answer with the reason it is wrong. Exact values are written as powers of two or fractions.
Learning objectives
- Decompose a number into float32 fields and compute the gap between neighbouring floats in float32, bf16, and fp16.
- Round exact ties to even in bf16 and recognise which decimal values are not representable in binary.
- Predict when cancellation, overflow, or absorption in a running sum destroys a result, and rewrite the formula to avoid it.
- Prove that softmax is shift invariant and that the max shift prevents overflow.
The facts every problem uses
Section titled “The facts every problem uses”These are the symbols used in the problems. Note that here counts stored fraction bits, so the unit roundoff is .
| Symbol | Meaning | Type / shape |
|---|---|---|
| sign bit, biased exponent field, fraction field | unsigned integers | |
| fraction bits: 23 (float32), 10 (fp16), 7 (bf16) | integer | |
| bias | 127 (float32, bf16), 15 (fp16) | integer |
| rounded to the nearest representable value | float | |
| gap between the two floats around | float | |
| unit roundoff, : the largest relative rounding error | float | |
| scalar |
Representation
Section titled “Representation”A normal binary float with fraction bits represents
where is the exponent width. The leading 1 is implicit (not stored). The exponent field holds zero and the subnormals , which fill the gap below the smallest normal ; holds () and NaN (). To decompose a number, write it as in binary: , so , , and the fraction bits are followed by 20 zeros, the integer . The three formats compare as follows:
| Format | Exponent bits | Fraction bits | Bias | Gap at 1 () | Largest finite |
|---|---|---|---|---|---|
| float32 | 8 | 23 | 127 | ||
| bf16 | 8 | 7 | 127 | ||
| fp16 | 5 | 10 | 15 |
bf16 is the top 16 bits of a float32, so converting is a rounding of the low 16 bits. Within one binade the floats are equally spaced with gap , and the gap doubles at each power of two: the integers above are not all float32 values, and above float32’s gap is 8.
Rounding
Section titled “Rounding”Every arithmetic result is rounded to a representable value. Round to nearest, ties to even (RNE), the IEEE 754 default, picks the nearest float and, when the exact result is halfway between two, the one whose last fraction bit is 0. Ties to even avoids the upward drift that “round half up” would add over many operations. The relative error of one rounding is at most the unit roundoff , half the gap at 1: with . Decimal fractions such as have infinite binary expansions, because their denominator has the factor 5, so they are always rounded.
Cancellation
Section titled “Cancellation”Subtraction of two floats is exact when they are within a factor 2 of each other (Sterbenz), so the damage is never the subtraction itself. It is that the operands already carry rounding errors from earlier steps, and subtracting nearly equal numbers cancels their shared leading digits and leaves those errors as the whole result. in float32 is 0 because already rounded to . The cure is an algebraically equal form that does not subtract nearly equal quantities: multiply by the conjugate, ; use ; compute a variance from deviations rather than from .
Overflow and the max shift
Section titled “Overflow and the max shift”overflows float32 above and float64 above about , and is NaN. Softmax and log-sum-exp are unchanged by subtracting a constant from every input (q11), so subtracting keeps every exponent at most 0:
Summation
Section titled “Summation”Adding a small number to a large running sum rounds the small number away when it is below half a gap: in float32, because the gap at 1 is . A long sum then stops growing. Kahan summation carries a compensation term that captures the low-order bits each addition drops and feeds them back; pairwise summation adds in a balanced tree so that every partial sum is of similar size. Stable numerics implements both.
Two worked examples
Section titled “Two worked examples”Before the problems, here are two siblings of q1 and q6, worked in full.
First, decompose as float32. . The sign is , the exponent , and the fraction bits are followed by 21 zeros, so . The answer is [0, 124, 2097152]. Check: .
Second, a cancellation. Evaluate in float32 at . The gap at 1 is , so lies between and , closer to 1 (since ), and rounds to 1. Then : the answer is , a 100% relative error, although the true value is . Algebra gives the stable form . The same structure, a sum that has already rounded away the part you are about to subtract back out, is q6.
The problems
Section titled “The problems”A float32 has 1 sign bit, 8 exponent bits (bias 127), and 23 fraction bits; float16 (fp16) has 1, 5 (bias 15), and 10; bfloat16 (bf16) has 1, 8 (bias 127), and 7. The tag after each question is its answer type.
Representation and rounding
Section titled “Representation and rounding”q1. Give the float32 fields , the fraction as the unsigned integer stored in its 23 bits, for (a) and (b) . [vector]
Answer
(a) . : sign 0, biased exponent , and the fraction after the implicit 1 is all zeros.
(b) , where . : sign 1, exponent , and the 23 fraction bits are followed by 20 zeros, the integer .
A common mistake is or for the exponent, which forgets the bias; another is a fraction of 1 for , which stores the implicit leading 1 (it is never stored). Reading the fraction bits as the decimal 5 gives , which ignores their position in the 23-bit field.
q2. Give the gap between and the next larger representable number in (a) float32, (b) bf16, (c) fp16. [number]
Answer
(a) , (b) , (c) . In the binade the floats are with the number of stored fraction bits, so the next float after 1 is .
A common mistake is for float32: that is the unit roundoff , half the gap. For bf16, counts the implicit bit as stored (bf16 has 8 significant bits but 7 stored fraction bits), and is fp16’s gap, not bf16’s.
q3. (a) Give the largest finite fp16 value. (b) The smallest positive normal float32 value is ; give . [number]
Answer
(a) . The largest exponent field that is not infinity/NaN is , so the exponent is , and the largest significand is all ones, . A common mistake is , which would need exponent 16 (that field is reserved for infinity), or , the largest uint16.
(b) . The smallest normal exponent field is 1, so the exponent is with significand 1. A common mistake is , which uses the field value 0 (reserved for zero and subnormals); is the smallest subnormal, .
q4. Round to bf16 with RNE: (a) , (b) . [number]
Answer
(a) . bf16’s gap at 1 is , so the neighbours are (fraction 0000000) and (fraction 0000001). is exactly halfway; ties to even picks the neighbour whose last bit is 0, which is 1. A common mistake is , rounding the tie up.
(b) . is halfway between (fraction 0000001, odd) and (fraction 0000010, even), so it rounds up to the even one. Answering truncates or rounds ties down; ties to even goes up here and down in (a).
q5. Is exactly representable in any binary floating-point format? [bool]
Answer
False. Every binary float is for integers (or ). in lowest terms has the factor 5 in its denominator, which no power of two can cancel, so its binary expansion never terminates. Every format rounds it.
Cancellation and stable rewrites
Section titled “Cancellation and stable rewrites”q6. Let and .
(a) Evaluate in float32 with every operation rounded to float32 (RNE). What does it return? [number]
(b) Give the true value of , exactly or to at least 7 significant digits. [number, rtol 1e-6]
Answer
(a) . lies in , where the float32 gap is . is representable, and is within half a gap of it, so it rounds to . Both square roots are then , and the subtraction gives 0.
(b) . Multiply by the conjugate: , which subtracts nothing and is accurate in float32 too. A common mistake for (a) is to give this true value () instead of what float32 computes. For (b), is ; the denominator is the sum of two roots, about .
q7. Which formula computes accurately in float64 at ? [choice]
(a) 1 - cos(x) (b) 2 * sin(x / 2)^2
Answer
(b). , and the float64 gap just below 1 is , so rounds to exactly 1 and (a) returns 0. The identity computes from a small number that was never subtracted from 1, so every digit is correct.
q8. (a) Give exactly. [number]
(b) In float64, what does the naive softmax exp(x) / sum(exp(x)) return for its first entry at ? Answer one of 0.5, inf, nan, 0. [choice]
Answer
(a) . Shift by : . Common mistakes are (dropping the ) and (forgetting to add the shift back).
(b) nan. overflows float64 (above about ) to , the sum is , and is NaN. A common mistake is inf: the exponential does overflow to infinity, but the division then produces NaN. The true value, 0.5, is what the max-shifted softmax returns.
q9. The data are .
(a) Give their population variance exactly. [number]
(b) In float64, which algorithm returns it to full precision: one pass (the mean of minus the square of the mean) or two passes (compute the mean, then average the squared deviations)? Answer one or two. [choice]
Answer
(a) . The mean is , the deviations are , and . A common mistake is 1, the sample variance (dividing by ).
(b) two. Each exceeds , where the float64 gap is 2, so the squares are rounded by up to 1 each; the one-pass formula subtracts two numbers near whose difference is , so the rounding errors are the same size as the answer (it can even come out negative). The two-pass method subtracts the mean first (exact here, Sterbenz), then squares small numbers.
q10. You sum the float32 values followed by copies of , left to right, rounding every addition to float32.
(a) What does the naive loop return? [number]
(b) Give the exact real sum , the value compensated (Kahan) summation recovers. [number]
Answer
(a) . The float32 gap at 1 is , and is below half of it (), so every rounds back to 1. The running sum never moves, all times.
(b) . Kahan summation keeps the dropped low-order part in a compensation variable; once those parts accumulate past half a gap, they enter the sum. A common mistake is to swap the two answers: (a) asks what float32 returns, not the exact sum.
q11. Prove that for every real , and that with every exponent is at most 0, so no overflows and the denominator is at least 1. [proof]
Answer
Claim. For and every real , , where . With , , every exponent is at most 0, so no term overflows, and the denominator is at least 1.
Shift invariance. Using , where cancelling is allowed because .
Bounds with . For every , , so and . No term can overflow, whatever the size of . The index with contributes , and every other term is positive, so the denominator : it is never 0, and the division never produces or NaN. (The denominator is at most , also finite.)
What it avoids. Without the shift, overflows float32 for above about and float64 above about , and is NaN: the failure of q8(b). With it, the same mathematical value is computed from numbers in . This is how softmax and logsumexp in Stable numerics are written.
A complete proof has four parts: the factor cancelled because it is positive, each shifted term in , the denominator at least 1 because the maximum term is , and the overflow thresholds this avoids.
Common mistakes
Section titled “Common mistakes”The errors this set is designed to expose recur in real code. Each one maps to a problem:
| Pitfall | Symptom | How to avoid it |
|---|---|---|
| Forgetting the exponent bias, or storing the implicit 1 | decompose_f32 disagrees with the bit view | q1: add 127 to the exponent; the leading 1 is implicit |
| Confusing the gap at 1 with the unit roundoff | tolerances off by a factor 2 | q2: the gap is , the unit roundoff is half of it |
| Thinking fp16 reaches 65536 | overflow to inf in mixed precision | q3: the top exponent field is reserved, so the maximum is |
| Rounding ties up instead of to even | bf16 results differ from torch in the last bit | q4: on a tie, pick the neighbour whose last fraction bit is 0 |
| Trusting the naive formula’s output | a 0 where the answer is | q6: rewrite with the conjugate so nothing nearly equal is subtracted |
| Exponentiating before subtracting the max | NaN from inf / inf at logit 1000 | q8 and q11: shift by the maximum first |
| One-pass variance on data far from 0 | negative or garbage variances | q9: subtract the mean before squaring |
| Accumulating a long sum naively in float32 | NLL totals that stop growing | q10: compensated (Kahan) or pairwise summation |
Where this leads
Section titled “Where this leads”q1 to q4 become code in IEEE 754 anatomy, ulps, and round to nearest even (decompose_f32, ulp, round_to_bf16, round_to_fp16), and q8, q10, and q11 become logsumexp, softmax, kahan_sum, and pairwise_sum in Stable numerics. In AI Engineering, the fused cross-entropy of Losses with a fused backward computes log_softmax with the max shift, The Llama-family model: config, weight loading, and download loads bf16 weights (q2 to q4), and Mixed precision, loss scaling, gradient accumulation, and activation checkpointing explains why bf16 needs no loss scaling and fp16 does (q3). Problem set B makes q6’s loss of digits quantitative with error bounds and condition numbers.
Further reading
Section titled “Further reading”- Goldberg, “What Every Computer Scientist Should Know About Floating-Point Arithmetic” (1991).
- Higham, Accuracy and Stability of Numerical Algorithms, chapters 1 to 4.
Key terms
Section titled “Key terms”- Implicit leading bit: the 1 in front of the fraction of a normal float, which is not stored.
- Binade: an interval within which floats are equally spaced.
- Unit roundoff: the largest relative error of one rounding, half the gap at 1.
- Cancellation: the loss of significant digits when subtracting nearly equal numbers that already carry rounding error.
- Absorption: a small addend vanishing entirely because it is below half the gap of a large running sum.
Summary
Section titled “Summary”- A float is sign, biased exponent, and fraction; its value is , and the gap between neighbours doubles every binade (q1, q2).
- bf16 keeps float32’s 8 exponent bits and drops 16 fraction bits, so it has float32’s range and a gap of at 1; fp16 has a gap of but overflows at 65504 (q2, q3).
- Round to nearest, ties to even, sends an exact halfway value to the neighbour with an even last bit, which is what makes
round_to_bf16agree with torch bit for bit (q4). - Subtracting nearly equal numbers loses every digit they share; the fix is an algebraically equal formula that never subtracts them (q6, q7, q9).
- Shifting softmax and log-sum-exp by the maximum changes nothing mathematically and removes overflow (q8, q11).