Rounding errors and numerically sound algorithms
Apply the standard floating-point error model to cancellation, accurate summation and stable reformulations including logsumexp, softmax and online variance.
After this lesson you can
- Bound rounding error of simple expressions and recursive summation using the standard model.
- Identify catastrophic cancellation and rewrite formulas using stable identities and functions.
- Implement pairwise and Kahan summation and Welford's algorithm and compare their errors.
- Implement stable logsumexp, softmax, softplus and cross-entropy from logits in float32 and float16.
- Explain why parallel reductions are not bitwise reproducible.
Before you start
Motivation: two failures without warning
The previous lesson showed what numbers exist on the machine: floating-point numbers, their machine epsilon and rounding to nearest. This lesson concerns what happens when you compute with them. Each operation incurs a tiny error, of order in float64, which usually does not matter. But two mechanisms turn such tiny errors into completely false results, and appear in production code every day. Before theory, watch them fail.
import numpy as np
# 1. Un softmax con temperatura: al bajar T, la pérdida se vuelve NaN
logits = np.array([2.0, 1.0, 0.5, -1.0], dtype=np.float32)
with np.errstate(all="ignore"):
for T in [1.0, 0.1, 0.01]:
e = np.exp(logits / np.float32(T))
print(f"T = {T:<5} softmax ingenuo = {e / e.sum()}")
# 2. La varianza de una serie de precios con la fórmula de los apuntes
rng = np.random.default_rng(0)
precios = 1e9 + rng.normal(0.0, 1.0, size=1000) # media 1e9, desviación típica 1
print("\nmedia(x²) − media(x)² =", np.mean(precios**2) - np.mean(precios) ** 2)
print("np.var(x) =", np.var(precios))With , softmax returns nan for the two most likely classes: does not fit in float32, becomes inf, and is undefined. Variance calculated as “mean of squares minus square of mean,” the formula in any statistics textbook, comes out negative, , on data whose variance is . This is not arbitrary: and are about , and between and consecutive doubles are separated by , so their difference can only be a multiple of 128. Neither failure raises an exception: NaN propagates through the training graph and negative variance enters a square root or position size.
Neither is a NumPy or IEEE 754 failure: both formulas are mathematically correct and numerically unsound. The goal is to predict these failures using a bound, recognize them in formulas and rewrite them to avoid them. The path:
- A one-line model for each operation’s error and algebra for accumulating them.
- Catastrophic cancellation: why subtracting similar numbers reveals earlier errors.
- Summing millions of numbers without losing digits: recursive, pairwise, Kahan and exact summation.
- Exponentials without overflow: log-sum-exp, softmax, softplus and cross-entropy from logits.
- One-pass statistics: Welford’s algorithm and batch merging.
- Why a parallel reduction may not give the same result twice.
The standard model
Let be a binary format with significand bits (including the implicit bit): in float64, in float32, in float16 and in bfloat16 (the IEEE 754 formats). With rounding to nearest, every real in the normal range rounds to with
is unit roundoff: half the relative spacing between consecutive numbers, half machine epsilon . It is in float64, in float32, in float16 and in bfloat16.
IEEE 754 requires the four operations and square root to be computed as if the exact operation were performed and the result then rounded. That is all needed to analyze algorithms.
Three observations before using it:
- Error is relative to the result, not the operands. If is small because , absolute error of the sum is also small. What can be large is error and already carried: we return to this with cancellation.
- Assumptions matter. Outside the normal range the model fails: a product in the subnormal range loses relative precision (subnormals have fewer bits), and one that overflows gives . Addition and subtraction are the good exception: if falls in the subnormal range, the result is exact, because and are integer multiples of the smallest subnormal , their sum is too and, being below , fits in significand bits.
- Library functions are outside the model. IEEE 754 recommends but does not require correctly rounded
exp,logorcos. Common math libraries guarantee errors of one or a few ulps, practically equivalent to with small .
Checking is inexpensive: compare each float32 operation with its exact value, which fractions.Fraction calculates without rounding.
import numpy as np
from fractions import Fraction
import operator
u32 = 2.0**-24
rng = np.random.default_rng(0)
a = rng.uniform(-10, 10, 4000).astype(np.float32)
b = rng.uniform(-10, 10, 4000).astype(np.float32)
ops = {"+": (np.add, operator.add), "−": (np.subtract, operator.sub),
"×": (np.multiply, operator.mul), "/": (np.divide, operator.truediv)}
for nombre, (f_np, f_exacta) in ops.items():
c = f_np(a, b)
peor = 0.0
for ai, bi, ci in zip(a.tolist(), b.tolist(), c.tolist()):
exacto = f_exacta(Fraction(ai), Fraction(bi))
if exacto != 0:
peor = max(peor, abs(float((Fraction(ci) - exacto) / exacto)))
print(f"x {nombre} y en float32: max |δ|/u = {peor / u32:.4f}")
# Un error relativo del orden de u en cada operación no impide sorpresas:
print("\n0.1 + 0.2 == 0.3:", 0.1 + 0.2 == 0.3, " (0.1 + 0.2) - 0.3 =", (0.1 + 0.2) - 0.3)For all four operations the worst observed is below , as the model promises. The final line reminds us that , and were already rounded when written: the model concerns the operation, not the data.
Algebra of factors
An algorithm performs many operations, each contributing its factor. What allows whole algorithms to be analyzed is that products of factors combine into one with a clean bound.
Proof
Each factor lies in interval : if , because ; if , because and . Thus the product lies in . Bernoulli’s inequality gives , used twice. Above, . Below, .
∎Notation denotes “some number with ,” different at each occurrence, and calculation rules follow directly: , and . While , : each chained operation adds one to the bound.
Catastrophic cancellation
Start with the simplest case. Suppose and approximate two numbers, with small relative errors from earlier calculations. Even if subtraction were exact,
Factor is huge when . If and agree in their first decimal digits, the factor is of order and the result loses correct digits.
Surprisingly, the subtraction itself incurs no error in that case. This is a classic result.
Proof
Assume ( is symmetric and or is trivial). Write with integer , and the exponent of (with if subnormal). Since , its exponent is , so is also an integer multiple of . Then with integer , and since , also . An integer of fewer than bits times a power of 2 with exponent at least is representable.
∎Thus the correct statement is: subtraction does not create errors; it reveals them. Subtracting similar numbers already carrying errors gives an exact result, but exactly the difference between two wrong values.
The lab example:
Its limit as is , by the Taylor polynomial . In float64, is accurate to relative error of one . Subtraction is exact by Sterbenz. Yet when is small, is tiny and absolute error of , of order , becomes relative error .
The figure shows what the bound says: correct digits in the result are almost exactly 16 minus the number of common digits of 1 and . Below , is less than half a spacing from 1 () and rounds exactly to 1: the formula gives 0. Just above, up to , and the formula returns , traversing the entire interval from 1 to without relating to .
The solution is another formula. With identity there is no subtraction: has relative error of one , squaring and division add three more, and the result has relative error of a few for all .
import numpy as np
print(" x (1 − cos x)/x² 2 sen²(x/2)/x² error relativo 2u/x²")
for k in [1, 2, 4, 6, 7, 8]:
x = 10.0**-k
ingenua = (1 - np.cos(x)) / x**2
estable = 2 * np.sin(x / 2) ** 2 / x**2
print(f"1e-{k:<2} {ingenua:.15f} {estable:.15f} {abs(ingenua - estable) / estable:.1e} {2 * 2**-53 / x**2:.1e}")
# La raíz pequeña de x² + b x + c con b = 1e8, c = 1 (raíces ≈ −1e8 y −1e-8)
b, c = 1e8, 1.0
d = np.sqrt(b * b - 4 * c)
print("\nraíz pequeña, fórmula del colegio :", (-b + d) / 2)
print("raíz pequeña, 2c / (−b − √(b²−4c)):", 2 * c / (-b - d))
# Diferencias de precios: dos cotizaciones de 4 cifras decimales
p1, p0 = 101.37, 101.36
print("\np1 − p0 en float64:", p1 - p0, " error relativo:", abs((p1 - p0) - 0.01) / 0.01)
print("p1 − p0 en float32:", np.float32(p1) - np.float32(p0))
print("en céntimos enteros:", (round(p1 * 100) - round(p0 * 100)) / 100)The table confirms the prediction: measured relative error grows like (two orders of magnitude per order of ) and stays below bound , which assumes the worst possible rounding of , until it reaches 1. With error is and the result keeps about 8 digits; with , none: the formula returns exactly 0. The other two cases show the same phenomenon:
- The quadratic formula. With , the small root subtracts two nearly equal numbers: is already rounded and subtraction reveals its error. The large root subtracts nothing, and by Vieta , so is obtained without cancellation. In general, calculate and the roots are and .
- Price differences. and are not binary-representable; each carries relative error up to and subtraction amplifies it about times. In float64 the difference’s relative error is , about 4600 times , but digits remain; in float32 it is , retaining only four digits. When data are exact decimals (cents, ticks), subtracting as integers and converting at the end eliminates the problem.
Reformulation: the catalog
All the preceding solutions follow the same recipe: locate subtraction of nearly equal quantities already carrying error and rewrite the expression using an exact identity so that subtraction disappears or uses exact data. This is stable reformulation. The most useful:
| Unstable expression | Where it fails | Stable reformulation |
|---|---|---|
| , | ||
log1p(x) | ||
expm1(x) | ||
log1p((x - y) / y) | ||
Notice the sixth row: also has a subtraction, but of the original data, which are exact, and by Sterbenz is calculated without error if . In , and are subtracted after rounding. The problem is not subtraction itself; it is subtracting numbers that already contain error.
Functions log1p and expm1 deserve comment. with first computes , rounded with absolute error up to , huge relative to : about 9 of its 16 digits are lost (the library-functions cell below gives instead of ), and even a perfect logarithm cannot recover them. log1p receives directly and never forms . That is why they exist in C, NumPy, PyTorch and every serious library: they are not shortcuts but the way to calculate those functions accurately.
Summing accurately
Addition seems the most innocent operation and is repeated most: means, norms, losses, accumulated gradients, P&L, integrals. The obvious algorithm is recursive summation: and .
The proof idea, completed in the guided exercise at the end, is to follow each summand: and pass through additions, through , and only through the last. Each addition contributes a factor , the lemma groups them into , and the worst has factors.
Three practical consequences:
- The bound is relative to , not . If summands have different signs and cancel, can be far smaller than and relative error with respect to huge. This is cancellation again, now spread across the sum.
- Order matters. With model variant , each step incurs error , and summing gives the finer bound : the sizes of partial sums matter. For same-sign summands it helps to add smallest to largest so partial sums grow as late as possible; with mixed signs there is no universally best order (Higham, 1993).
- The bound is worst-case. If rounding errors behave as independent zero-mean variables, typical error grows like rather than ; Higham and Mary (2019) turned this into a rigorous high-probability bound.
Pairwise summation
In recursive summation passes through additions. If a balanced binary tree replaces the chain (sum pairs, then pairs of pairs, and so on), each summand passes only through the tree’s depth.
Deriving that bound is the guided exercise’s final step. The improvement is enormous: for , the constant changes from to . It costs no extra additions because the count is the same. This is what np.sum does in many cases, as the lab shows.
Compensated summation: Kahan and Neumaier
One can do better still and obtain error that does not grow with . The key is that error of a floating-point sum is itself a representable number that can be calculated.
Kahan (1965) applied this to recursive summation: each step calculates what was just lost and subtracts it from the next summand.
Its analysis (Higham, 2002, chapter 4) gives : while , error no longer depends on . The cost is four operations per summand instead of one and a chain dependency preventing naive vectorization.
Kahan has a weakness: Fast2Sum analysis requires . If a summand exceeds the accumulated sum, is not the part of that entered and the correction is lost. Neumaier (1974) fixed this by comparing magnitudes each step:
and returns at the end. You will implement it in a code exercise, with a case where Kahan fails and Neumaier does not.
With uniform data in , recursive-sum error grows with clearly below its worst-case bound: it rises about three orders of magnitude over five decades of , closer to than , as probabilistic analysis predicts. Sorting these data barely changes anything: with , smallest-to-largest and largest-to-smallest recursive sums remain the same order of magnitude as unsorted, because with similarly sized summands partial sums grow nearly alike in any order. With alternating signs, partial sums stay small and recursive summation makes much smaller errors relative to . Pairwise and Kahan stay near the error of the best possible float32 result, the rounded exact sum (relative error up to with respect to ). With “one 1 and many tiny values” recursive summation stagnates: each summand is less than half float32 spacing around 1, and the sum does not move, so error grows exactly like . The bit zoom shows why Kahan does not stagnate: the bits of that cannot store are exactly those appearing in .
Summation lab
Implement four sums from scratch in float32. Variables are np.float32 scalars, so each operation rounds to float32 as on a GPU. Pairwise summation is written iteratively over arrays: adding x[0::2] + x[1::2] is one tree level, and repeating until one element remains traverses the entire tree.
import numpy as np
import math
f32 = np.float32
def suma_recursiva(x):
s = f32(0)
for xi in x:
s = s + xi
return s
def suma_por_pares(x):
x = np.asarray(x, dtype=np.float32)
while len(x) > 1:
if len(x) % 2: # número impar: el último pasa al siguiente nivel tal cual
x = np.append(x[:-1][0::2] + x[:-1][1::2], x[-1])
else:
x = x[0::2] + x[1::2] # un nivel del árbol, cada suma redondeada a float32
return x[0]
def suma_kahan(x):
s, c = f32(0), f32(0)
for xi in x:
y = xi - c
t = s + y
c = (t - s) - y # menos lo que se perdió al sumar y
s = t
return s
def suma_neumaier(x):
s, c = f32(0), f32(0)
for xi in x:
t = s + xi
if abs(s) >= abs(xi):
c += (s - t) + xi
else:
c += (xi - t) + s
s = t
return s + c
u = 2.0**-24
gamma = lambda k: k * u / (1 - k * u)
rng = np.random.default_rng(0)
datos = (rng.integers(0, 2**24, 10**5) / 2**24).astype(np.float32) # uniformes en [0, 1)
print(" n recursiva por pares Kahan Neumaier cota rec. cota pares")
for n in [10**2, 10**3, 10**4, 10**5]:
x = datos[:n]
exacta = math.fsum(x.astype(float)) # suma exacta, redondeada una vez
sa = math.fsum(np.abs(x).astype(float))
errs = [abs(float(f(x)) - exacta) / sa for f in (suma_recursiva, suma_por_pares, suma_kahan, suma_neumaier)]
assert errs[0] <= gamma(n - 1) and errs[1] <= gamma(math.ceil(math.log2(n))) and errs[2] <= 2 * u + n * u * u
print(f"{n:>6} " + " ".join(f"{e:.2e}" for e in errs) + f" {gamma(n - 1):.1e} {gamma(math.ceil(math.log2(n))):.1e}")
print("\nla suma recursiva coincide con np.cumsum(x)[-1]:", suma_recursiva(datos[:1000]) == np.cumsum(datos[:1000])[-1])All four sums respect their bounds (assert do not trigger) and the pattern matches the figure. Recursive error moves from with to with : twenty times greater for a thousand times more summands, near and far below its bound . Pairwise, Kahan and Neumaier stay below for every size, at the final rounding level. The last line shows something useful: np.cumsum accumulates in order, so its last element is the recursive sum. What does np.sum do?
import numpy as np
import math
rng = np.random.default_rng(1)
x = (rng.integers(0, 2**24, 10**6) / 2**24).astype(np.float32)
exacta = math.fsum(x.astype(float))
rel = lambda v, ref: abs(float(v) - ref) / ref
print(f"np.sum(x) error relativo {rel(np.sum(x), exacta):.1e}")
print(f"np.cumsum(x)[-1] error relativo {rel(np.cumsum(x)[-1], exacta):.1e} (recursiva)")
print(f"np.sum(x[::2]) error relativo {rel(np.sum(x[::2]), math.fsum(x[::2].astype(float))):.1e} (con paso 2)")
# Una matriz 1000×1000 en orden C: las filas son contiguas en memoria
A = x.reshape(1000, 1000)
filas = A.sum(axis=1) # suma a lo largo del eje rápido
columnas = A.sum(axis=0) # suma a lo largo del eje lento
e_filas = max(rel(filas[i], math.fsum(A[i].astype(float))) for i in range(1000))
e_cols = max(rel(columnas[j], math.fsum(A[:, j].astype(float))) for j in range(1000))
print(f"\nA.sum(axis=1), peor fila: {e_filas:.1e}")
print(f"A.sum(axis=0), peor columna: {e_cols:.1e}")
print("A.sum(axis=0) es exactamente la recursiva por filas:", np.array_equal(columnas, np.cumsum(A, axis=0)[-1]))
print("Con float64 como acumulador, axis=0:", f"{max(rel(c, math.fsum(A[:, j].astype(float))) for j, c in enumerate(A.sum(axis=0, dtype=np.float64))):.1e}")The numpy.sum documentation says NumPy often uses partial pairwise summation, always when axis is omitted, but along an axis only when it is the fast memory axis. On a vector of elements, np.sum gives error versus for recursive summation, about 250 times less; the same holds for a stride-2 vector, noncontiguous but one-dimensional. In the matrix, axis=1 traverses contiguous rows and uses pairwise summation (worst row ); axis=0 adds row by row, exactly recursive summation for each column (checked on the penultimate line), with thirteen times greater error in the worst column. A cheap solution for float32 data is float64 accumulation using dtype=np.float64: the last line gives error 0 because here each column adds one thousand 24-bit values and the sum fits exactly in a double’s 53 bits.
What does compensation cost? In pure Python each operation pays interpreter overhead, so compare ratios rather than absolute times.
import time
x_lista = (np.random.default_rng(2).integers(0, 2**24, 2 * 10**5) / 2**24).astype(np.float32)
def cronometra(f, *args, reps=3):
mejor = float("inf")
for _ in range(reps):
t0 = time.perf_counter()
f(*args)
mejor = min(mejor, time.perf_counter() - t0)
return mejor
t_rec = cronometra(suma_recursiva, x_lista)
t_kahan = cronometra(suma_kahan, x_lista)
x64 = x_lista.astype(float)
t_np = cronometra(np.sum, x64, reps=20)
t_fsum = cronometra(math.fsum, x64.tolist(), reps=5)
print(f"Kahan / recursiva (bucles en Python): {t_kahan / t_rec:.1f}×")
print(f"math.fsum / np.sum (código compilado): {t_fsum / t_np:.0f}×")Times depend on the machine, but ratios are stable: in Python loops Kahan costs about twice recursive summation (here ), less than the four-to-one operation ratio because much of the time is interpreter-loop overhead. The production comparison is the second: np.sum (compiled and pairwise) is over an order of magnitude faster than math.fsum (exact, but managing partial sums element by element). In compiled code the difference is structural: pairwise performs the same additions as recursive summation with independent branches, so vectorizes equally well; Kahan performs four operations per summand in a chain where each step needs the previous . Numerical libraries therefore choose pairwise by default and leave compensated summation for cases where it is needed.
Exponentials without overflow
The exponential is the most dangerous floating-point function: its argument has only a narrow viable interval. overflows when , which is in float64, in float32 and bfloat16 and only in float16 (whose maximum is ). It rounds to 0 when is very negative: below in float64, about in float32 and in float16 (where is below half the smallest subnormal). Neural networks constantly compute exponentials of logits.
The log-sum-exp trick
Function is a smooth maximum (introduced as maximum smoothing): it satisfies . Its value is perfectly reasonable even if every overflows. The problem is the formula, not the function.
With that shift all exponents are , so no exponential overflows, and the maximum term equals exactly , so the sum lies in : it is never 0 and the logarithm is never . Terms rounded to 0 are far smaller than and would not change that 1 when added: losing them does not change the result.
Blanchard, Higham and Higham (2021) analyzed rounding error in these formulas. Their main conclusion is that shifted versions are as accurate as unshifted ones and can be used confidently; their recommended algorithm adds a detail, using log1p for the maximum term, with the maximum index, avoiding information loss when the sum of other terms is small.
Softmax, log-softmax and cross-entropy
The same shift fixes softmax, because it is invariant to adding a constant to all logits:
Blanchard and coauthors also compare two ways to calculate softmax: divide by the sum, as in the left formula, or calculate without division. They find the second has a worse error bound and larger errors in their experiments, and recommend division.
The second formula, log-softmax, is what training actually needs. Softmax cross-entropy for an example with class is
and is calculated this way from logits. Computing softmax first and then its logarithm is a classic mistake: if is so small it rounds to 0 (normal early in training or for a very unlikely class), , although the true loss is finite and its gradient well-defined.
The figure shows three distinct failures and the shift fixes only two. Overflow () and total underflow () disappear when subtracting the maximum. The third, in cross-entropy, remains even with correctly calculated softmax: only never forming the probability avoids it, as log_softmax does. Also notice stable-softmax error against float64: in float16 it is of order to , the size of in that format. Subtracting the maximum avoids disaster; it does not make an 11-bit format exact.
The sigmoid family
For binary classification the functions differ, but the principle is the same. With :
- Softplus, . For large , overflows; for very negative , rounds to 1 and everything is lost. Stable form is , obtained by factoring out .
- Log-sigmoid, .
- Binary cross-entropy from the logit. With and label , , whose stable form is . This is exactly what
torch.nn.BCEWithLogitsLosscomputes; its documentation says it is more stable than a sigmoid followed byBCELossbecause it uses the log-sum-exp trick. - for , appearing when subtracting probabilities on a log scale. Neither obvious formula works throughout. Mächler (2012) showed the good choice is when and when . You will implement it in an exercise.
Minimal stable-function library
Implement the whole library in NumPy so it works in float16, float32 and float64 without converting formats, and compare it with SciPy.
import numpy as np
def logsumexp(z, axis=-1):
z = np.asarray(z)
m = np.max(z, axis=axis, keepdims=True)
m = np.where(np.isfinite(m), m, 0) # si todo es −inf, no restar −inf − (−inf) = NaN
s = np.sum(np.exp(z - m), axis=axis, keepdims=True)
return np.squeeze(m + np.log(s), axis=axis)
def log_softmax(z, axis=-1):
z = np.asarray(z)
m = np.max(z, axis=axis, keepdims=True)
d = z - m
return d - np.log(np.sum(np.exp(d), axis=axis, keepdims=True))
def softmax(z, axis=-1):
z = np.asarray(z)
e = np.exp(z - np.max(z, axis=axis, keepdims=True))
return e / np.sum(e, axis=axis, keepdims=True)
def softplus(x):
x = np.asarray(x)
return np.maximum(x, 0) + np.log1p(np.exp(-np.abs(x)))
def log_sigmoid(x):
return -softplus(-np.asarray(x))
def bce_con_logits(z, y):
z = np.asarray(z)
return np.maximum(z, 0) - y * z + np.log1p(np.exp(-np.abs(z)))
def ce_con_logits(z, y):
"""Entropía cruzada media de un lote: z de forma (B, K), y enteros de forma (B,)."""
lp = log_softmax(z, axis=-1)
return -np.mean(lp[np.arange(len(y)), y])
def log1mexp(a):
a = np.asarray(a, dtype=float)
return np.where(a <= np.log(2), np.log(-np.expm1(-a)), np.log1p(-np.exp(-a)))
z = np.array([[1000.0, 999.0, 990.0], [-1000.0, -1001.0, -1010.0], [0.5, 0.2, -0.3]])
y = np.array([0, 2, 1])
with np.errstate(all="ignore"):
ingenuo = np.log(np.sum(np.exp(z), axis=1))
print("log Σ exp ingenuo:", ingenuo)
print("logsumexp estable:", logsumexp(z))
print("entropía cruzada media:", ce_con_logits(z, y))
print("softplus(±800):", softplus(np.array([800.0, -800.0])), " log σ(−800):", log_sigmoid(-800.0))
print("BCE(z = 40, y = 0):", bce_con_logits(40.0, 0), " ingenua:", -np.log(1 - 1 / (1 + np.exp(-40.0))))Outputs show three failure modes and their fixes: naive log Σ exp gives inf in the first row and -inf in the second, while the shifted version gives finite values; cross-entropy is computed without forming a probability; and naive BCE with logit 40 gives inf because rounds to 0, when the correct value is 40. Now compare with SciPy in all three formats and sweep extreme inputs.
import numpy as np
from scipy import special
rng = np.random.default_rng(3)
for dt in [np.float16, np.float32, np.float64]:
z = (rng.normal(size=(200, 10)) * 30).astype(dt)
ref = special.logsumexp(z.astype(np.float64), axis=1)
err_lse = np.max(np.abs(logsumexp(z).astype(np.float64) - ref) / np.abs(ref).clip(1))
ref_ls = special.log_softmax(z.astype(np.float64), axis=1)
err_ls = np.max(np.abs(log_softmax(z).astype(np.float64) - ref_ls) / np.abs(ref_ls).clip(1))
print(f"{np.dtype(dt).name:8s} error de logsumexp {err_lse:.1e} de log_softmax {err_ls:.1e} (u = {2.0**-(np.finfo(dt).nmant + 1):.1e})")
# Test de propiedades: entradas extremas en los tres formatos, nada de inf ni NaN
extremos = [0.0, 1e-8, -1e-8, 1.0, -1.0, 20.0, -20.0, 80.0, -80.0, 700.0, -700.0, 1e4, -1e4]
fallos = 0
for dt in [np.float16, np.float32, np.float64]:
big = float(np.finfo(dt).max) / 4
vals = np.array([v for v in extremos if abs(v) < big], dtype=dt)
with np.errstate(over="ignore"):
for i in range(len(vals)):
for j in range(len(vals)):
fila = np.array([vals[i], vals[j], vals[(i + j) % len(vals)]], dtype=dt)
r = [logsumexp(fila), log_softmax(fila), softmax(fila), softplus(fila), log_sigmoid(fila),
bce_con_logits(fila, 1), ce_con_logits(fila[None, :], np.array([2]))]
fallos += sum(int(not np.all(np.isfinite(v))) for v in r)
print("\nresultados no finitos en el barrido:", fallos)
a = np.array([1e-20, 1e-5, 0.5, np.log(2), 1.0, 10.0, 50.0, 700.0])
print("log1mexp:", log1mexp(a))In all three formats error of logsumexp and log_softmax is of order for each format: the shifted version loses no precision, as Blanchard and coauthors predict. The property sweep finds no nonfinite result in any of the seven functions.
One-pass statistics
Return to the initial negative variance. For data points, population variance is with , and identity permits one-pass computation accumulating and . This “textbook formula” subtracts two nearly equal numbers.
How nearly equal? Chan and Lewis (1979) defined the variance condition number,
which measures how much larger data are than their dispersion. Even if both sums were calculated perfectly, rounding once introduces absolute error up to : relative error in . Actual sums add factor (or if pairwise). For prices with standard deviation 1, and : the result has no correct digits and its sign is luck.
The two-pass formula, first calculating and then , avoids that subtraction: deviations are small and positive quantities are added. Its drawback is needing data twice, impossible with streaming data (market ticks, training metrics, a batch-normalization moving average).
Proof
The new mean satisfies , hence . It suffices to show , because that is . Write and, for the first , use decomposition , obtained by expanding the square and using . Then
∎Welford never forms : it works with deviations from the current mean, of the size of data dispersion. In the analysis of Chan, Golub and LeVeque (1983), this update algorithm’s error bounds grow with , versus for the one-pass formula; two-pass is better still, with a first-order term independent of .
The figure confirms the analysis: naive-formula error follows , slope 2 on a log scale, and no digits remain from in float64 or in float32; beyond that, naive variance is a multiple of double spacing near and negative at many swept values. Welford error grows with slope 1, like , while two-pass error barely moves until enormous values. In float32 two-pass loses this advantage: calculated mean carries error of up to about units, and exactly, so that error enters squared. The “corrected” two-pass version analyzed by Chan, Golub and LeVeque subtracts term , estimating precisely . In float32 with a different phenomenon appears: data themselves have been quantized to multiples of , because needs 20 of 24 bits. No algorithm recovers what was lost when storing data; subtract a reference level before converting to float32.
Batch merging
Parallel or block processing requires combining summaries and . Chan, Golub and LeVeque (1979) gave the formula: with and ,
The proof uses the same decomposition: and likewise for , with and , so the two extra terms sum to . Applied on a binary tree of blocks, this is the authors’ pairwise algorithm, the variance analogue of pairwise summation. Covariance combines similarly, with , and updates observation by observation with .
import numpy as np
class Momentos:
"""Media, varianza y covarianza de pares (x, y) en una pasada, con fusión por lotes."""
def __init__(self):
self.n, self.mx, self.my, self.Mx, self.My, self.C = 0, 0.0, 0.0, 0.0, 0.0, 0.0
def actualiza(self, x, y):
self.n += 1
dx = x - self.mx
dy = y - self.my
self.mx += dx / self.n
self.my += dy / self.n
self.Mx += dx * (x - self.mx)
self.My += dy * (y - self.my)
self.C += dx * (y - self.my)
return self
def fusiona(self, o):
r = Momentos()
r.n = self.n + o.n
if r.n == 0:
return r
dx, dy = o.mx - self.mx, o.my - self.my
f = self.n * o.n / r.n
r.mx = self.mx + dx * o.n / r.n
r.my = self.my + dy * o.n / r.n
r.Mx = self.Mx + o.Mx + dx * dx * f
r.My = self.My + o.My + dy * dy * f
r.C = self.C + o.C + dx * dy * f
return r
def var_x(self): return self.Mx / self.n
def cov(self): return self.C / self.n
rng = np.random.default_rng(4)
x, y = rng.normal(size=1000), rng.normal(size=1000)
y = 0.6 * x + 0.8 * y
uno = Momentos()
for a, b in zip(x, y):
uno.actualiza(a, b)
bloques = []
for k in range(0, 1000, 128): # lotes de 128, fusionados al final
m = Momentos()
for a, b in zip(x[k:k + 128], y[k:k + 128]):
m.actualiza(a, b)
bloques.append(m)
total = Momentos()
for m in bloques:
total = total.fusiona(m)
print("var: Welford", uno.var_x(), " por lotes", total.var_x(), " np.var", np.var(x))
print("cov: Welford", uno.cov(), " por lotes", total.cov(), " np.cov", np.cov(x, y, bias=True)[0, 1])All three forms agree to the last digits. Now the motivating experiment: simulated asset returns and prices, processed in blocks as they might arrive from a feed.
import numpy as np
from fractions import Fraction
def var_exacta(v):
q = [Fraction(float(t)) for t in v]
m = sum(q) / len(q)
return float(sum((t - m) ** 2 for t in q) / len(q))
def var_ingenua(v):
return np.mean(v * v) - np.mean(v) ** 2
def var_welford_bloques(v, tam=250):
total = Momentos()
for k in range(0, len(v), tam):
m = Momentos()
for a in v[k:k + tam]:
m.actualiza(a, 0.0)
total = total.fusiona(m)
return total.var_x()
rng = np.random.default_rng(5)
r = rng.normal(5e-4, 0.01, size=2000) # rendimientos diarios
print("rendimientos: κ ≈", f"{np.sqrt(1 + np.mean(r)**2 / np.var(r)):.3f}")
ex = var_exacta(r)
for nombre, f in [("ingenua", var_ingenua), ("np.var", np.var), ("Welford por bloques", var_welford_bloques)]:
print(f" {nombre:20s} error relativo {abs(f(r) - ex) / ex:.1e}")
print("\nprecios M + ruido con σ = 1:")
print(" M κ ingenua np.var Welford por bloques")
z = rng.normal(0, 1, size=2000)
for M in [1e2, 1e4, 1e6, 1e8, 1e10]:
p = M + z
ex = var_exacta(p)
kappa = np.sqrt(1 + np.mean(p) ** 2 / ex)
errs = [abs(f(p) - ex) / ex for f in (var_ingenua, np.var, var_welford_bloques)]
print(f" 1e{int(np.log10(M)):<3} {kappa:.1e} " + " ".join(f"{e:.1e}" for e in errs))For returns, (mean is far smaller than standard deviation) and all three formulas agree to the last digit: the naive formula is not always bad, but is bad when is large. For prices, each row multiplies and by 100, and naive-formula error multiplies by about , i.e. : with , with , no digits with and error times variance with . Block Welford grows like , about a hundredfold per row, from to , as Chan, Golub and LeVeque predict. np.var, which makes two passes, is most accurate: worst error with . With all data use two passes; for streaming, Welford. Practically, if using the one-pass formula for price variances, volatility or network normalization, first subtract a reference level or use Welford.
Library functions that exist for this reason
All of this is already implemented and tested in libraries. Knowing that they exist and why is half the work.
| Function | What it avoids |
|---|---|
np.log1p(x), np.expm1(x) | forming or subtracting when |
np.hypot(x, y) | overflow of in |
scipy.special.logsumexp | overflow of ; supports weights and signs |
scipy.special.xlogy(x, y), xlog1py | entropy’s NaN (returns 0 if ) |
scipy.special.log_softmax, log_expit | from first computing probability |
torch.nn.functional.log_softmax, cross_entropy | the same in PyTorch; cross_entropy accepts logits |
torch.nn.functional.logsigmoid, softplus, BCEWithLogitsLoss | sigmoid followed by logarithm |
math.fsum, np.sum | recursive summation (exact and pairwise respectively) |
np.var, np.std | one-pass formula (they use two passes) |
import numpy as np
from scipy import special
x = 1e-10
print("log(1 + x):", np.log(1 + x), " log1p(x):", np.log1p(x), " (exacto ≈ 9.9999999995e-11)")
print("exp(x) − 1:", np.exp(x) - 1, " expm1(x):", np.expm1(x))
with np.errstate(all="ignore"):
g = np.float64(1e200)
print("sqrt(x² + y²) con x = y = 1e200:", np.sqrt(g * g + g * g), " hypot:", np.hypot(g, g))
print("0·log 0:", 0.0 * np.log(0.0), " xlogy(0, 0):", special.xlogy(0.0, 0.0))
z = np.array([1000.0, 999.0, 990.0])
print("log_softmax de SciPy:", special.log_softmax(z), " log_expit(−800):", special.log_expit(-800.0))The same names exist in PyTorch, where they matter most because models are trained in float16 or bfloat16:
import torch
import torch.nn.functional as F
z = torch.tensor([[12.0, 10.0, 3.0, -2.0, -20.0]], dtype=torch.float16)
y = torch.tensor([4])
F.cross_entropy(z.float(), y) # recibe logits: internamente log_softmax + nll_loss
torch.log(torch.softmax(z, dim=-1))[0, 4] # MAL: el softmax de la clase 4 se redondea a 0 y log 0 = -inf
F.log_softmax(z.float(), dim=-1)[0, 4] # BIEN
F.binary_cross_entropy_with_logits(z[:, 0].float(), torch.ones(1)) # no sigmoid + BCELoss
Nonassociativity and reproducibility
In floating point, and are distinct operations with distinct roundings: addition is not associative. A sum of numbers has many possible orders and generally each gives a slightly different result. This directly affects parallel code.
A parallel reduction distributes the vector among threads, each summing its part, then combines partial sums. The tree depends on , block size and, if partials combine through atomic operations (atomicAdd in CUDA), the order in which threads finish, decided by the scheduler each run. Parallel reductions are correct algorithms, but floating-point results depend on the tree.
import math
import numpy as np
print("(0.1 + 0.2) + 0.3 =", (0.1 + 0.2) + 0.3, " 0.1 + (0.2 + 0.3) =", 0.1 + (0.2 + 0.3))
rng = np.random.default_rng(6)
x = rng.normal(size=2**20).astype(np.float32)
def reduccion_paralela(x, hilos):
parciales = np.cumsum(x.reshape(hilos, -1), axis=1)[:, -1] # cada hilo suma su trozo en orden
return np.cumsum(parciales)[-1] # y se combinan los parciales
resultados = {p: reduccion_paralela(x, p) for p in [1, 2, 4, 8, 16, 32, 64, 128, 256, 1024]}
for p, s in resultados.items():
print(f"{p:5d} hilos: {s:.9g}")
distintos = len(set(float(s) for s in resultados.values()))
ulp = np.spacing(np.float32(abs(np.sum(x.astype(np.float64)))))
vals = np.array([float(s) for s in resultados.values()])
print("valores distintos:", distintos, "de", len(resultados), " ulp del resultado:", ulp,
" dispersión:", round((vals.max() - vals.min()) / float(ulp)), "ulp")
exacta = math.fsum(x.astype(float))
print("error de 1 hilo y de 1024 hilos, en ulp:", round((float(resultados[1]) - exacta) / float(ulp)), round((float(resultados[1024]) - exacta) / float(ulp)),
" np.sum (por pares):", round((float(np.sum(x)) - exacta) / float(ulp)))
print("permutar los datos cambia la suma recursiva:", np.cumsum(rng.permutation(x))[-1] != np.cumsum(x)[-1])
# Acumular en float16: la suma de unos se estanca
unos = np.ones(5000, dtype=np.float16)
print("\nsuma de 5000 unos en float16:", np.cumsum(unos, dtype=np.float16)[-1], " en float32:", np.cumsum(unos, dtype=np.float32)[-1])The ten “thread counts” give ten different results for the same vector, spread over 280 ulps: one thread has error 7 ulps and 1024 has 27, while np.sum (pairwise) stays at 4. All are equally legitimate and within the bound, none matching another. On a GPU, with much more balanced reduction trees, differences usually remain in the last bits, but the phenomenon is the same. This is what happens when identical training runs diverge in the last bit and then, due to training’s chaotic nature, much more.
The last line is another warning: in float16 a sum of ones stops at 2048. From onward float16 spacing is 2, so lies exactly halfway between 2048 and 2050 and ties to even chooses 2048. In bfloat16 with 8 significand bits, stagnation occurs at . Hence metrics, accumulated losses and accumulated gradients are stored in float32 even when the model computes at reduced precision.
Bitwise reproducibility is possible, but must be requested: fix reduction order (same thread and block count, no atomics), enable torch.use_deterministic_algorithms(True) in PyTorch (which raises an error if an operation lacks a deterministic version), and set CUBLAS_WORKSPACE_CONFIG with cuBLAS. See GPU nondeterminism and GPU reductions for detail.
Common mistakes
Exercises
More than one answer may be correct.
More than one answer may be correct.
-O3 -ffast-math and its error matches recursive summation. What happened?torch.sum and obtain results differing in the last bit. What is the most likely cause?Step 1 of 4. How do you write step under the standard model?
log1mexp(a) for , accepting a scalar or NumPy array with relative error of a few throughout the range from to . Use Mächler's rule: if and if . Tests compare against a high-precision mpmath reference.import numpy as np
def log1mexp(a):
a = np.asarray(a, dtype=float)
return np.log(1 - np.exp(-a))neumaier(xs), Neumaier compensated summation over a list of Python floats (float64), and define caso_dificil, a list for which Kahan summation (provided as kahan) differs from math.fsum and yours equals math.fsum exactly. Hint for the case: Kahan's weakness is a summand whose magnitude exceeds the accumulated sum.import math
def kahan(xs):
s = c = 0.0
for x in xs:
y = x - c
t = s + y
c = (t - s) - y
s = t
return s
def neumaier(xs):
# tu código: suma y corrección, comparando |s| con |x| en cada paso
return sum(xs)
caso_dificil = [1.0, 2.0, 3.0]Summary
- Standard model. with ; chained factors combine into with .
- Catastrophic cancellation. Subtracting nearly equal numbers is exact (Sterbenz) but reveals existing errors: relative error multiplies by . Use identities: , in the quadratic formula,
log1p,expm1, . - Sums. Recursive: . Pairwise: , at the same cost (what
np.sumdoes along the fast axis). Kahan and Neumaier: .math.fsum: exact. - Exponentials. Subtract the maximum before exponentiation (log-sum-exp, softmax) and never form a probability only to take its logarithm:
log_softmax,cross_entropyfrom logits,softplusandlogsigmoidwith . - Variance. loses digits; Welford updates mean and centered sum of squares in one pass, and Chan, Golub and LeVeque merging combines batches.
- Reproducibility. Addition is not associative; parallel reductions change last bits according to the tree. Accumulate in float32, compare with tolerances and fix order when identical results are required.
These ideas recur throughout the syllabus: attention softmax and its online FlashAttention version (online softmax) apply the log-sum-exp trick by blocks; cross-entropy is calculated from logits; log returns and portfolio variances suffer cancellation; and the next lesson, conditioning and backward stability, precisely separates issues caused by the problem from those caused by the algorithm.