Rounding and range
Finite floating-point formats round most real numbers to nearby representable values. In binary64, the next value above is Under round-to-nearest, adding to leaves the rounded result at At a larger magnitude the gap between adjacent numbers grows. Floating point also has finite exponent range. A large exponential can overflow, and a sufficiently small positive exponential can round to zero.
In a mixed-precision computation, format choices may differ for storage, products and accumulation. Accumulating reduced-precision products in wider precision can reduce additional rounding in the sum. It cannot restore bits already lost when values were converted to a narrower format.
Shift before exponentiating
Define for a nonempty vector of finite logits. Set Factor out of the sum to obtain
The shifted exponentials are at most one, and at least one equals one. This avoids exponential overflow for finite inputs. Use the second expression directly when you need the log probability. Subtracting a rounded from a very large can lose precision. Also, taking the log of a rounded softmax result can fail when a tiny probability rounds to zero. Extremely large differences between finite logits can themselves exceed the floating-point range.
For logits subtract to obtain The second token has probability and log probability The direct exponential of overflows in binary64.
Run the same calculation on a second vector whose logits are separated by one thousand. The smaller log probability remains finite even though its exponential rounds to zero.
from math import exp, fsum, log
for logits, target in [([1000.0, 1001.0], 1), ([0.0, -1000.0], 1)]:
largest = max(logits)
shifted = [value - largest for value in logits]
log_normalizer = log(fsum(exp(value) for value in shifted))
print(f"{shifted[target] - log_normalizer:.4f}")-0.3133
-1000.0000Exercises
Find the probability assigned to one of four equal finite logits.
Show solution✓ Checked
After shifting, every exponential equals one. Each probability is
What happens to and softmax if you add to every logit?
Show solution✓ Checked
Factoring out adds to log-sum-exp. It cancels between numerator and denominator of each softmax probability.
For logits give a bound on how far the first token’s negative log probability lies above zero.
Show solution✓ Checked
It equals For so the loss is strictly between and in exact arithmetic. A float can round it to zero.