Floating point, overflow and the log-sum-exp trick
Computers keep a fixed number of digits. See where that bites - cancellation, overflow, underflow - and the standard fixes - working in logs, subtracting the maximum before exponentiating, and choosing the precision on purpose.
What runs in CodeSplash
- Deep neural network (torch MLP) Verified in Python and R
You will be able to
- Say roughly how many significant digits float64, float32 and bfloat16 keep, and what machine epsilon is
- Recognize catastrophic cancellation, overflow and underflow in a calculation
- Compute log-sum-exp and softmax stably, and explain why likelihoods are summed in logs
Read first
A fixed number of digits
ReadA floating-pointFloating-point numberA number stored as a sign, digits and a power of two. Float64 keeps about 16 significant digits, float32 about 7. number stores a sign, a fixed number of binary digits and a power of two.
| Type | Bits | Significant digits | Largest value |
|---|---|---|---|
| float64 | 64 | about 16 | about |
| float32 | 32 | about 7 | about |
| bfloat16 | 16 | about 3 | about |
| float16 | 16 | about 3 | 65,504 |
Machine epsilonMachine epsilonThe gap between 1 and the next representable number: the relative rounding error of one floating-point step. is the gap between 1 and the next number: in float64 and in float32. Every arithmetic step can add a relative error of that size.
Cancellation
ReadSubtracting two nearly equal numbers keeps their difference but not their accuracy. The digits they shared cancel, and what is left is mostly rounding error.
The textbook variance formula does exactly that when values are large and close together, such as timestamps or sensor readings around : in float32 it can even come out negative. The two-pass formula, subtract the mean first and then square, avoids it. Centering data before fitting helps for the same reason.
Overflow and underflow
Readis larger than any float64, so it becomes infinity (overflow). is smaller than the tiniest float64, so it becomes 0 (underflow).
Both show up in ordinary models. A softmax over scores in the hundreds overflows. The likelihood of 10,000 rows is a product of 10,000 probabilities and underflows to 0, at which point every model looks equally impossible.
The fix for products is to work in logs: sum log-probabilities instead of multiplying probabilities. Hidden Markov models and every maximum-likelihood fit in CodeSplash do this.
Log-sum-exp
ReadLogs turn products into sums, but some formulas need the log of a sum of exponentials, such as a softmax denominator or a mixture likelihood. Let . Then
Every exponent is now at most 0, so nothing overflows, and the largest term is exactly , so the sum can't underflow to 0. That is the log-sum-expLog-sum-explog Σ exp(xᵢ), computed as m + log Σ exp(xᵢ − m) with m the largest xᵢ, so nothing overflows. trick. The same shift gives a stable softmaxSoftmaxTurns a vector of scores into probabilities: exponentiate each, divide by the total. Subtracting the max first keeps it stable.: subtract the maximum score before exponentiating.
import numpy as np
x = np.array([1000., 1001., 1002.])
print(np.exp(x) / np.exp(x).sum()) # nan: inf / inf
z = np.exp(x - x.max())
print(z / z.sum()) # [0.090 0.245 0.665]
print(x.max() + np.log(np.exp(x - x.max()).sum())) # log-sum-expx <- c(1000, 1001, 1002)
exp(x) / sum(exp(x)) # NaN: Inf / Inf
z <- exp(x - max(x))
z / sum(z) # 0.090 0.245 0.665
max(x) + log(sum(exp(x - max(x)))) # log-sum-expChoosing the precision
ReadLarge-scale training often uses mixed precisionMixed precisionTraining with low-precision math for speed and memory while keeping sensitive sums and master weights in higher precision.: bfloat16 or float16 for the heavy matrix products, float32 for weights and sums. It is faster and halves memory, and float16 needs loss scaling so small gradients don't underflow.
CodeSplash makes the opposite trade. Its torch learners train in float64 in both engines, so Python and R results can be compared to many digits. Matching digits is only possible when rounding error is far below the differences being checked.
Check: precision
CheckpointCheck yourself
Roughly how many significant decimal digits does float32 keep?
Show the answer
Answer: b
Float32 has a 24-bit significand, about 7 decimal digits. Float64 keeps about 16.
Check yourself
Readings are all close to 1,000,000,000 with a spread of a few units. Why can give a wrong, even negative, variance?
Show the answer
Answer: a
Catastrophic cancellation: subtracting nearly equal large numbers. Subtract the mean first, then square.
Check yourself
Using the log-sum-exp trick on : the maximum is 1000. To the nearest whole number, what is ?
Show the answer
Answer: 1000
. The smaller terms are negligible, and no step overflowed.
Check yourself
Why does subtracting the maximum score before a softmax not change its result?
Show the answer
Answer: a
. Same answer, no overflow.
Check yourself
Why do model fits sum log-likelihoods instead of multiplying likelihoods?
Show the answer
Answer: a
The maximizing parameters are the same either way, but only the log version can be computed for large data.
Recap
Recap- Float64 keeps about 16 digits, float32 about 7; machine epsilon is the size of one rounding error.
- Watch for cancellation (subtracting near-equal numbers), overflow and underflow.
- Work in logs, and subtract the maximum before exponentiating: that is log-sum-exp and stable softmax.
Concepts in this lesson