Variance in float32 with a first-element shift, a local centring and a compensated tree sum¶
Salvatore Pennacchio, November 2026.
Abstract¶
The variance of float32 data with a large offset and a small wobble loses its digits in the subtraction of two almost equal numbers: on 3000 values around 10⁶ with a spread of 1, the one-pass formula mean(x²) - mean(x)² returns -196608 where the variance is 0.989742. We describe stable_var, a variance for float32 in four steps: a shift by the first element, a local centring, a sum of the squares by a binary tree of error-free TwoSum additions, and a two-term correction. It returns exactly 0.0 on identical values, up to 1e38 and on complex64. On four datasets, on a CPU and on a GPU, its maximum relative error is between 1.15·10⁻⁷ and 1.64·10⁻⁷, and it is at most equal to the error of the formula of tf.nn.moments, which has no shift, on three of the four datasets in each of the four combinations of backend and execution mode (eager, jit); it is worse on one dataset on the CPU and on one dataset on the GPU under jit, and we do not explain why. It costs 3.59 times the formula of tf.nn.moments on a CPU and 2.24 times on a GPU. On stacks of 1 to 1024 normalised layers on a GPU, the gradient of the stack with the usual layer normalisation is wrong by up to 21 %, and with stable_var by less than 0.006 % in each of 66 stacks. We state what was not measured.
1. The problem¶
The variance of a sample is the average of the squared distances from the mean, Var(x) = (1/n) Σ (xᵢ - mean(x))². A robot joint reports its angle as a float32 every millisecond; the angle sits around a large offset, the wobble around it is small, and the controller needs the variance of the wobble. The one-pass formula mean(x²) - mean(x)² subtracts two numbers of the order of mean(x)² to get a number of the order of the wobble squared, and the float32 mantissa is not wide enough.
We take 3000 float32 values from a normal distribution of mean 10⁶ and standard deviation 1 (seed 0). The float64 variance of the same float32 values is 0.989742; the one-pass formula in float32 gives -196608.000000. The two terms are of the order of 10¹², their rounding errors of the order of 10⁵, a million times the wobble.
The same failure on a stock index quoted near 4500 in steps of 0.25 (3000 values, float32): the true variance is 0.2528, the usual formula returns 0.0000, as if the market stood still, and stable_var returns 0.2528.

Figure 1. The problem.
Why the one-pass formula fails¶
A float32 number \(v\) with \(2^{e} \le |v| < 2^{e+1}\) is a multiple of \(\mathrm{ulp}(v) = 2^{e-23}\), and so \(2^{-24}\,|v| < \mathrm{ulp}(v) \le 2^{-23}\,|v|\). Let \(\mu\) be the mean and \(\sigma\) the standard deviation of the values. The two terms of the one-pass formula \(\overline{x^2} - \bar{x}^{\,2}\) are both about \(\mu^2\), and the difference of two float32 numbers of that size is a multiple of \(\mathrm{ulp}(\mu^2)\): it is \(0\) or at least one step of the grid. The quantity to find, \(\sigma^2\), is smaller than one step as soon as
and it can already be smaller from \(\mu/\sigma > 2^{11.5} \approx 2900\), according to where \(\mu^2\) sits in its binade. This is the case of the three examples of this paper: a stock index near 4500 that moves by 0.25 (\(\mu/\sigma \approx 9000\)), a joint around 1000 that vibrates by 0.01 (\(10^{5}\)), and 3000 values around \(10^6\) with a spread of 1 (\(10^{6}\)). For the last one \(\mu^2 = 10^{12}\), the spacing of the float32 numbers there is \(2^{16} = 65536\), and the variance, \(0.99\), is far below one step of the grid: the one-pass formula returns \(-196608\).
The shift removes the cause. After \(y_i = x_i - x_1\) the values are of the order of \(\sigma\) and not of \(\mu\), so the squares and the sums are of the order of \(\sigma^2\), and their rounding errors are a fraction \(2^{-24}\) of \(\sigma^2\) and not of \(\mu^2\): to the first order the relative error does not depend on \(\mu/\sigma\) any more. What is left is the error of the sum of the \(n\) squares, which the compensated tree reduces, and the error of \(m\), which the second term of the formula cancels to the first order. The shift itself costs no error when the values are within a factor of two of \(x_1\), because the subtraction is then exact. The formula of tf.nn.moments, which centres on the computed mean first, avoids the first failure and keeps the error of \(x - \bar{x}\); Section 4 measures what is left of it.
Contributions. (1) The condition under which the one-pass formula fails in float32, \(\mu/\sigma\) above a few thousand, and the reason: the grid of the float32 numbers near \(\mu^2\). (2) The kernel stable_var: the shift, the local centring and the two terms of Healy [3], with the compensated tree of Kahan in which each merge uses the TwoSum, so that it runs in \(\lceil\log_2 n\rceil\) vectorised levels on a CPU and on a GPU. (3) The measurements on a CPU, a GPU and a TPU: the accuracy on four datasets, the gradient of a stack of up to 1024 normalised layers, the cost of a training step, and the variance of values stored in bfloat16 and float8. (4) The declared limits.
2. Related work¶
Chan, Golub and LeVeque [1] survey the algorithms for the sample variance with their round-off error bounds, including an analysis of the computation on shifted data: even a crude estimate of the mean used as a shift gives a large gain in accuracy without a first pass. Healy [3], for the mean and the variance in Monte-Carlo simulations, takes the first observation as the shift K, sums with Kahan's compensation and applies the two-term formula T/n - (M - K)²; his Algorithm 2 is the shifted naive algorithm with Kahan summation. The shift is exact when the values are within a factor of two of it (Sterbenz; Lemma 5 of [4]).
TwoSum returns the rounded sum of two floating-point numbers and its exact rounding error [2, Algorithm 3.1]; see also Theorem 7 of [4]. The compensated tree of Kahan uses it at each merge.
This kernel adds to the algorithm of [3] the local centring d = y - m before the squares, a compensated binary tree of Kahan, where each merge uses TwoSum [2, 4], in place of the sequential Kahan sum, and the evaluation one slice at a time with vmap. The tree has log₂(n) vectorised levels, so it runs on a GPU.
The TwoSum against the papers¶
The function _two_sum of the kernel is the TwoSum, the same three lines as Algorithm 3.1 of [2] and as TWO-SUM, Theorem 7, of [4]: x = fl(a + b), z = fl(x - a), y = fl((a - (x - z)) + (b - z)), with a + b = x + y exactly. In this the kernel is not different from the papers. What is different is how it is used. Kahan summation [3] and the cascaded summation of [2], Algorithm 4.1, run along the elements in a loop: the second keeps one running sum of the errors, sigma_i = fl(sigma_(i-1) + q_i), and the Kahan-Babuska algorithm is the same with FastTwoSum in place of TwoSum. The kernel adds the pieces in a binary tree of log₂(n) levels, and at each level, for every pair of partial sums (S, C), it calls TwoSum three times, on the high parts, on the carries and on their sum; the new carry is e1 + e2 + e3. In the text of [2] and [3] there is no tree of TwoSum, and [2] cites parallel summation only in its list of references. The error analysis of [2] is for the sequential algorithms; for the tree we found no proof in the papers, and the carries e1 + e2 + e3 are added with ordinary floating-point additions, so its accuracy is shown here by measurements. The compensated tree is the idea and the choice of the author, and it is not classic Kahan summation.
The baseline in the tests is the formula of tf.nn.moments in TensorFlow [5], mean(d²) - mean(d)² with d = x - mean(x), which has no shift. An issue of TensorFlow reports its inaccuracy in float32 [6].
3. The kernel¶
stable_var returns the variance in the input dtype, with the axis, ddof and keepdims arguments of the other reducers of the library. Four steps, all in the input dtype.
- Shift. Subtract the first element along the reduction axis,
y = x - x[0]. When the values are within a factor of two of it, the subtraction is exact, and the large common exponent is gone. For[1000.0, 1000.01, 1000.02]in float32 the shifted values are[0, 0.01000977, 0.02001953]. - Local centring. The mean
mof the shifted values is at the level of the wobble, and so is its rounding error, not at the level of the offset. - Compensated tree. The residuals
d = y - mare formed ands2 = Σ d²is accumulated by a binary tree. At each level the pairs of partial sums are added withTwoSum, and the rounding errors are carried up the tree. - Two-term correction and division. With
s1 = Σ d, the biased variance ismax(s2/n - (s1/n)², 0), multiplied byn / (n - ddof). The mean isx[0] + m.

Figure 2. The shift.

Figure 3. The centre: the shifted values and the same values after subtracting their mean.
The idea of a carry that keeps the low-order bits can be shown with the sequential summation of Kahan [7], which is not the one the kernel uses. For the array [1.0] + [1e-7] * 100000 in float32 the exact sum is 1.01; the sequential sum gives 1.01192093 (error 1.9·10⁻³) and the Kahan sum 1.00999999 (error 9.5·10⁻⁹).

Figure 4. The TwoSum: with a = 16777216 and b = 1 the plain float32 sum is 16777216, and the TwoSum returns s = 16777216 and e = 1.

Figure 5. The compensated tree of Kahan: eight numbers added in pairs over three levels, each merge using the TwoSum, the sums in blue and the carries in gold. For 1.0 and seven numbers of 1e-8 the plain float32 sum is 1.00000000, the compensated tree gives 1.00000012, and the exact sum is 1.00000007.
The formulas and the algorithms¶
Let \(x \in \mathbb{F}^n\) be the values of one slice, in float32, and \(\mathrm{fl}(\cdot)\) the rounding of the float32 arithmetic. Every operation below is one float32 operation, except where a sum is said to be ordinary or compensated.
TwoSum. For two float32 numbers \(a\) and \(b\), Algorithm 3.1 of [2] and Theorem 7 of [4] give
\begin{aligned}
s &= \mathrm{fl}(a+b),\\
z &= \mathrm{fl}(s-a),\\
e &= \mathrm{fl}\bigl((a-(s-z))+(b-z)\bigr),
\end{aligned}
\qquad\text{with}\qquad a+b = s+e \ \text{ exactly.}
%caption: TwoSum$(a,b)$
\Require float32 numbers $a$, $b$
\Ensure $s$ and $e$ with $a+b=s+e$ exactly
\State $s \gets \mathrm{fl}(a+b)$
\State $z \gets \mathrm{fl}(s-a)$
\State $e \gets \mathrm{fl}\bigl((a-(s-z))+(b-z)\bigr)$
\State \Return $s$, $e$
The shift, the centring and the two terms. With \(y_i = x_i - x_1\), the subtraction is exact when \(x_i\) is within a factor of two of \(x_1\) (Sterbenz; Lemma 5 of [4]). The mean of the shifted values and the residuals are
For any constant \(m\) the variance of \(x\) is \(\frac{1}{n}\sum_i (x_i-m)^2 - \bigl(\frac{1}{n}\sum_i (x_i-m)\bigr)^2\). With the computed \(m\) the mean of the \(d_i\) is zero in exact arithmetic and is not zero in float32: keeping the second term cancels the linear part of the error of \(m\). The biased variance is
\sigma^2 = \max\Bigl(\tfrac{1}{n}\,S_2 - \bigl(\tfrac{1}{n}\,S_1\bigr)^{2},\ 0\Bigr),
\qquad S_2 = \sum_{i=1}^{n} d_i^{2}\ \text{(compensated tree)},
\qquad S_1 = \sum_{i=1}^{n} d_i\ \text{(ordinary sum)},
and, with ddof, \(\sigma^2_{\mathrm{ddof}} = \frac{n}{n-\mathrm{ddof}}\,\sigma^2\); the mean is \(x_1 + m\).
The complete formula. Putting the pieces together, with \(\mathrm{CT}\) the sum of Algorithm 2 below:
\begin{aligned}
\mathrm{stable\_var}(x) &= \frac{n}{n-\mathrm{ddof}}\;
\max\Bigl(\frac{1}{n}\,\mathrm{CT}\bigl(d_1^{2},\dots,d_n^{2}\bigr) - \Bigl(\frac{1}{n}\sum_{i=1}^{n} d_i\Bigr)^{2},\; 0\Bigr),\\
d_i &= (x_i - x_1) - m, \qquad m = \mathrm{fl}\Bigl(\frac{1}{n}\sum_{i=1}^{n}(x_i - x_1)\Bigr).
\end{aligned}
The compensated tree. For \(v \in \mathbb{F}^n\), with \(S^{(0)}_k = v_k\) and \(C^{(0)}_k = 0\), each level adds the pairs at the same time:
\begin{aligned}
(s_1,e_1) &= \mathrm{TwoSum}\bigl(S^{(\ell)}_{2k-1},S^{(\ell)}_{2k}\bigr),\\
(s_2,e_2) &= \mathrm{TwoSum}\bigl(C^{(\ell)}_{2k-1},C^{(\ell)}_{2k}\bigr),\\
(s_3,e_3) &= \mathrm{TwoSum}(s_1,s_2),\\
S^{(\ell+1)}_{k} &= s_3, \qquad C^{(\ell+1)}_{k} = \mathrm{fl}\bigl(\mathrm{fl}(e_1+e_2)+e_3\bigr),
\end{aligned}
and the result is \(\mathrm{fl}\bigl(S^{(L)}_1 + C^{(L)}_1\bigr)\) after \(L=\lceil \log_2 n\rceil\) levels; a level of odd length is completed with a zero.
%caption: CompensatedTree$(v)$
\Require $v \in \mathbb{F}^n$
\Ensure the compensated sum of $v$
\State $S \gets v$, $C \gets 0$
\While{$|S| > 1$}
\If{$|S|$ is odd}
\State append $0$ to $S$ and to $C$
\EndIf
\For{$k = 1,\dots,|S|/2$ \textbf{in parallel}}
\State $(s_1,e_1) \gets \mathrm{TwoSum}(S_{2k-1},S_{2k})$
\State $(s_2,e_2) \gets \mathrm{TwoSum}(C_{2k-1},C_{2k})$
\State $(s_3,e_3) \gets \mathrm{TwoSum}(s_1,s_2)$
\State $S'_k \gets s_3$, $\quad C'_k \gets \mathrm{fl}(\mathrm{fl}(e_1+e_2)+e_3)$
\EndFor
\State $S \gets S'$, $C \gets C'$
\EndWhile
\State \Return $\mathrm{fl}(S_1 + C_1)$
%caption: StableVar$(x,\mathrm{ddof})$
\Require $x \in \mathbb{F}^n$, $\mathrm{ddof}$
\Ensure the variance of $x$
\State $y_i \gets x_i - x_1$ for $i = 1,\dots,n$
\State $m \gets \mathrm{fl}\bigl(\tfrac{1}{n}\sum_i y_i\bigr)$, $\quad d_i \gets y_i - m$
\State $S_2 \gets \mathrm{CompensatedTree}(d_1^2,\dots,d_n^2)$, $\quad S_1 \gets \sum_i d_i$
\State $\sigma^2 \gets \max\bigl(S_2/n - (S_1/n)^2,\ 0\bigr)$
\State \Return $\sigma^2\, n/(n-\mathrm{ddof})$
The program of Appendix A writes these three algorithms out in Python and runs them, with no library of ours.
The dtype policy: float32 in gives float32 out; float64 in gives float64 out when jax_enable_x64 is on (off, JAX promotes to float32); float16 and bfloat16 are computed in float32 and returned in the input dtype; integers give float32; complex input gives the real E|z - mean(z)|². ddof = n returns nan when the variance is positive and 0.0 when the values are identical.
The same path is on the estimators, through the dtype keyword of RunningMoments: on a float32 block of 500 values around 1000 with a spread of 0.01, RunningMoments(dtype=np.float32) gives a variance of 1.029553·10⁻⁴ against 1.029553·10⁻⁴ in float64, a relative difference of 4.91·10⁻⁹. The default dtype=None keeps the float64 result, bit for bit.
4. Experiments¶
The tests are those of the script benchmarks/stable_variance_float32.py of the library, which calls dense_armor.core.signals.stats.stable.stable_var itself. Three claims were declared in the first commit of the script and not changed after the run: (1) the kernel returns exactly 0.0 on every identical-values case, under jit; (2) on each of the four datasets its maximum relative error is at most the one of the baseline formula, in eager mode and under jit; (3) its time is at most 4.0 times the time of the baseline on a [4096, 4096] array, axis=1. The original target for the time was 2.0 times; it was not reached, and the threshold of 4.0 was chosen after the measurement.
The numbers of the CPU are in benchmarks/stable_variance_float32.json (JAX 0.11.1), the ones of the GPU in benchmarks/stable_variance_float32_gpu.json (JAX 0.12.0.1).
4.1 Identical values¶
The variance of identical values is exactly 0.0 for 1e10, 7.5e10, 1e15 and 1e38 in float32 and for 7.5e10 in complex64, on the CPU and on the GPU, under jit. The baseline formula gives nan at 1e38. In the example [1e10, 1e10, 1e10] the result is the bit pattern 0x00000000.
4.2 The four datasets¶
Maximum relative error against the float64 variance of the same float32 values, for the baseline formula of tf.nn.moments (base) and for stable_var (kernel), eager and under jit.
CPU:
| dataset | base eager | kernel eager | base jit | kernel jit |
|---|---|---|---|---|
N(10³, 0.01), [1000, 64], axis 0 |
1.44·10⁻⁷ | 1.17·10⁻⁷ | 1.18·10⁻⁷ | 1.17·10⁻⁷ |
N(10⁴, 1), [64, 1000], axis 1 |
1.59·10⁻⁷ | 1.15·10⁻⁷ | 1.59·10⁻⁷ | 1.15·10⁻⁷ |
N(0, 1), [1000, 64], axis 0 |
1.94·10⁻⁷ | 1.36·10⁻⁷ | 1.94·10⁻⁷ | 1.36·10⁻⁷ |
N(10⁶, 1), [1000, 64], axis 0 |
1.18·10⁻⁷ | 1.22·10⁻⁷ | 0.997·10⁻⁷ | 1.22·10⁻⁷ |
GPU:
| dataset | base eager | kernel eager | base jit | kernel jit |
|---|---|---|---|---|
N(10³, 0.01), [1000, 64], axis 0 |
1.35·10⁻⁷ | 1.17·10⁻⁷ | 1.35·10⁻⁷ | 1.17·10⁻⁷ |
N(10⁴, 1), [64, 1000], axis 1 |
1.70·10⁻⁷ | 1.15·10⁻⁷ | 1.70·10⁻⁷ | 1.15·10⁻⁷ |
N(0, 1), [1000, 64], axis 0 |
1.44·10⁻⁷ | 1.36·10⁻⁷ | 1.44·10⁻⁷ | 1.64·10⁻⁷ |
N(10⁶, 1), [1000, 64], axis 0 |
1.25·10⁻⁷ | 1.22·10⁻⁷ | 1.25·10⁻⁷ | 1.22·10⁻⁷ |
Claim 2 holds on the GPU in eager mode and fails there under jit (the dataset N(0, 1)), and fails on the CPU in both modes (the dataset N(10⁶, 1)). In bold, the cases in which the kernel is worse than the baseline: by 3 % (N(10⁶, 1), eager, CPU), 22 % (the same under jit) and 14 % (N(0, 1), jit, GPU). Where the kernel is better, the error is lower by up to 32 %.
4.3 The speed¶
A synthetic [4096, 4096] float32 array, axis=1, under jit, 15 runs after warm-up with block_until_ready, the median of each of three sessions on the CPU. The ratio is the median of the medians of the kernel over the median of the medians of the baseline.
| naive two-pass | base | kernel | kernel / base | range over the sessions | |
|---|---|---|---|---|---|
| CPU | 51.4 ms | 57.7 ms | 207.4 ms | 3.59 | 3.55 to 4.60 |
| GPU | 0.706 ms | 0.696 ms | 1.558 ms | 2.24 | 2.20 to 2.27 |
The kernel costs 3.59 times the baseline formula on the CPU and 2.24 times on the GPU. The target of 2.0 times was not reached. On the CPU the upper end of the range comes from the first session of the kernel (median 264.9 ms), the other two being 205.2 and 207.4 ms.
4.4 The depth: a stack of normalised layers on a GPU¶
The script benchmarks/stable_variance_depth.py of the library stacks layers of the form x <- OFFSET + SPREAD * tanh(LN(x) @ W), with W orthogonal times 0.7, a batch of 128 rows of width 512, an offset of 1000, and two layer normalisations in float32: the usual one, (x - mean) / sqrt(var + eps) with jnp.mean and jnp.var, and the one with stable_var, in which the variance is the one of stable_var and the mean is subtracted on the data shifted by the first element. For each depth the gradient of sum(c * x_L) with respect to x_0 is computed in float32 by jax.grad and, as a reference, in float64 by replaying the backward pass layer by layer on the same float32 inputs, so that the comparison isolates the error of the backward pass. The matrix products use the highest precision, so that the layer normalisation is the only difference. The runs were made on a Kaggle GPU session with JAX 0.11.1 (benchmarks/stable_variance_depth_gpu.json, benchmarks/stable_variance_depth_grid_gpu.json).
With a spread of 0.004, 11 depths from 1 to 1024 layers, median time of 11 runs:
| layers | gradient error, usual | gradient error, stable_var |
time, usual | time, stable_var |
time ratio |
|---|---|---|---|---|---|
| 1 | 3.66·10⁻³ | 3.45·10⁻⁷ | 0.31 ms | 0.37 ms | 1.20 |
| 2 | 7.87·10⁻³ | 4.88·10⁻⁷ | 0.57 ms | 0.74 ms | 1.29 |
| 4 | 1.11·10⁻² | 6.95·10⁻⁷ | 0.96 ms | 1.37 ms | 1.43 |
| 8 | 1.77·10⁻² | 1.04·10⁻⁶ | 1.71 ms | 2.46 ms | 1.44 |
| 16 | 2.54·10⁻² | 1.62·10⁻⁶ | 3.15 ms | 4.56 ms | 1.45 |
| 32 | 3.74·10⁻² | 2.65·10⁻⁶ | 4.36 ms | 8.83 ms | 2.03 |
| 64 | 5.35·10⁻² | 4.54·10⁻⁶ | 8.05 ms | 17.42 ms | 2.17 |
| 128 | 7.58·10⁻² | 8.33·10⁻⁶ | 11.71 ms | 34.56 ms | 2.95 |
| 256 | 1.06·10⁻¹ | 1.56·10⁻⁵ | 23.34 ms | 35.78 ms | 1.53 |
| 512 | 1.50·10⁻¹ | 3.06·10⁻⁵ | 47.30 ms | 63.16 ms | 1.34 |
| 1024 | 2.04·10⁻¹ | 5.91·10⁻⁵ | 95.30 ms | 127.99 ms | 1.34 |

Figure 6. The error of the gradient and the time of a step against the number of layers (spread 0.004).
The same 11 depths with six values of the offset over the spread (66 stacks in all, 3 timed runs each), over the 11 depths of each row:
| offset / spread | error, usual | error, stable_var |
times closer to the reference | time ratio |
|---|---|---|---|---|
| 250000 | 3.8·10⁻³ to 2.1·10⁻¹ | 3.3·10⁻⁷ to 6.0·10⁻⁵ | 3461 to 17447 | 1.12 to 3.09 |
| 79365 | 1.2·10⁻³ to 8.0·10⁻² | 3.2·10⁻⁷ to 1.1·10⁻⁵ | 3777 to 6949 | 1.29 to 3.10 |
| 25000 | 3.7·10⁻⁴ to 2.8·10⁻² | 3.4·10⁻⁷ to 2.9·10⁻⁵ | 962 to 2012 | 1.00 to 2.95 |
| 7937 | 1.1·10⁻⁴ to 7.5·10⁻³ | 3.2·10⁻⁷ to 3.9·10⁻⁵ | 192 to 647 | 1.05 to 2.11 |
| 2500 | 4.1·10⁻⁵ to 2.2·10⁻³ | 3.4·10⁻⁷ to 3.6·10⁻⁵ | 61 to 199 | 0.76 to 2.06 |
| 794 | 1.2·10⁻⁵ to 7.2·10⁻⁴ | 3.5·10⁻⁷ to 1.7·10⁻⁵ | 35 to 67 | 1.23 to 2.36 |
The kernel is closer to the float64 reference in all 66 stacks, by a factor between 35 and 17447 (median 962). The usual layer degrades with the depth and with the offset over the spread, up to 21 % at 1024 layers and an offset over the spread of 250000; with stable_var the error stays below 0.006 %. No gradient is NaN or infinite. The time of a step with stable_var is between 0.76 and 3.1 times the time with the usual layer, with a median of 1.42: it is lower in 2 of the 66 stacks and higher in 64.

Figure 7. The gradient of a stack of normalised layers: the usual layer rises to 21 %, the layer with stable_var stays on the floor, below 0.006 %.
4.5 The cost in a network step¶
The step of a stack of 8 feed-forward blocks of a transformer (hidden size 4096, width 1024, 4096 tokens), forward and backward, on a Kaggle GPU in float32, with the usual layer normalisation and with stable_var; the median of 7 runs. The gradient is finite in both cases.
| usual | with stable_var |
|
|---|---|---|
| forward and backward step | 458.9 ms | 465.6 ms |
| normalisation alone | 0.61 ms | 1.28 ms |
| share of the normalisation in the step | 1.1 % | 2.2 % |
The normalisation alone is 2.1 times slower with stable_var, and the step is 1.45 % longer: the normalisation is a small share of the work of a step, which is mostly matrix products. The share falls with the width of the network, and the cost of the step should fall with it; Section 4.6 shows this only in part.
4.6 The same on a TPU, by width¶
The training step of the decoder of benchmarks/train_small_lm.py of the library, on one TPU core, in bfloat16 with float32 master weights, with the LayerNorm of the library and with LayerNorm(n, stable=True). There are 4 blocks, a batch of 8 and 30 steps, and each pair is run twice in turn: the median of the step times.
| width | parameters | step, usual | step, stable=True |
extra cost | loss of the last 10 steps, usual and stable |
|---|---|---|---|---|---|
| 384 | 9.5 M | 6.62 ms | 7.16 ms | +8.2 % | 2.9094 and 2.9094 |
| 768 | 37.9 M | 10.94 ms | 11.25 ms | +2.8 % | 3.0266 and 3.0250 |
| 1536 | 151.2 M | 25.04 ms | 25.89 ms | +3.4 % | 3.2563 and 3.2547 |
The extra cost is 8.2 % at width 384 and between 2.8 % and 3.4 % at 768 and 1536; in this test it does not keep falling between 768 and 1536, and beyond 1536 it was not measured. A single run of 50 steps of the 14.2-million-parameter decoder gave 10.89 ms against 11.57 ms (+6 %), and another 10.92 ms against 12.16 ms (+11 %): one run varies by several points. The loss is the same to the second decimal; these are 30 steps and not a converged training. The numbers are in benchmarks/stable_variance_cost_tpu.json of the library.
4.7 In bfloat16 and float8¶
The values are stored in bfloat16, float8_e4m3fn and float8_e5m2 (a GPU test, 64 rows of 4096 values N(offset, 1)), and the reference is the float64 variance of the stored values. Casting to float32 and using jnp.var has an error between 2.8e-08 and 1.6e-07, and stable_var between 0 and 2.2e-08; with the variance computed in the small type the error is about 1e-3 for bfloat16 and NaN for float8_e4m3fn. When the storage has already lost the wiggle, no method can give it back: bfloat16 at an offset of 1000 keeps 3 distinct values, and float8 at an offset of 100 keeps 1 or 2. stable_var accepts bfloat16 and returns it in the input dtype. The numbers are in benchmarks/stable_variance_lowprec_gpu.json of the library.
4.8 What this covers and what it does not¶
- The large sums of a normalisation are carried out in float32, also when the rest of the network is in half precision: Micikevicius et al. [8] write that large reductions, which come up when the statistics of the normalisation layers are accumulated and in the softmax, should be carried out in FP32.
stable_varworks in float32 also for bfloat16 input. - RMSNorm [9] does not subtract the mean and divides by the root mean square, so
stable_var, which is a variance, does not apply to it; it applies toLayerNorm. - The effect on a real network such as Llama has not been measured.
4.9 Ablation: the contribution of each step¶
Same datasets and the same structure (a vmap over one-dimensional slices), with one step changed at a time. The four columns of accuracy count the datasets, out of four, on which the maximum error of the variant is not larger than that of the reference formula; the speed is the median ratio to the reference formula, with the minimum and the maximum over the sessions.
| variant | CPU eager | CPU jit | GPU eager | GPU jit | [1e38]*3 CPU eager / jit |
[1e38]*3 GPU eager / jit |
speed CPU | speed GPU |
|---|---|---|---|---|---|---|---|---|
| formula of reference (two-term, no shift, tree sum) | 4/4 | 4/4 | 4/4 | 4/4 | nan / nan | nan / nan | 1.00 (1.00-1.00) | 1.00 (1.00-1.00) |
| shift + centring, tree sum, no compensation, no two-term | 2/4 | 0/4 | 3/4 | 2/4 | 0 / 0 | 0 / 0 | 1.01 (0.94-1.02) | 1.01 (1.00-1.05) |
| shift + centring + two-term, tree sum, no compensation | 2/4 | 0/4 | 3/4 | 2/4 | 0 / 0 | 0 / 0 | 1.82 (1.78-1.89) | 1.00 (0.98-1.07) |
| no shift, two-term, compensated tree | 4/4 | 4/4 | 4/4 | 4/4 | 0 / nan | nan / nan | 2.22 (2.11-2.28) | 2.17 (2.16-2.30) |
| shift + centring, compensated tree, no two-term | 3/4 | 3/4 | 4/4 | 3/4 | 0 / 0 | 0 / 0 | 1.75 (1.65-1.80) | 1.87 (1.82-1.93) |
| shift + centring + two-term, compensated tree (the kernel) | 3/4 | 3/4 | 4/4 | 3/4 | 0 / 0 | 0 / 0 | 2.27 (2.24-2.35) | 2.19 (2.16-2.30) |
| shift + centring, Kahan sequential scan (previous version) | 3/4 | 3/4 | 4/4 | 3/4 | 0 / 0 | 0 / 0 | 1.62 (1.55-1.64) | 42.96 (41.71-45.79) |
- The shift is the step that gives the exact zero on
[1e38]*3: the variant without it returns nan under jit on the CPU and in both modes on the GPU, and the kernel returns 0. - The two-term correction does not change the result: the kernel and the variant without it have the same errors on all sixteen cells (four datasets, eager and jit, CPU and GPU).
- The compensated tree keeps the error under jit at the level of the reference: the shifted variants without compensation are at most equal on 0 of 4 datasets on the CPU and on 2 of 4 on the GPU under jit, the kernel on 3 of 4 on both.
- The sequential Kahan scan of the previous version has the same accuracy and the same zero as the kernel, and costs 1.62 times the reference on the CPU and 42.96 times on the GPU, against 2.27 and 2.19 for the compensated tree.
5. Declared limits¶
- The accuracy is at most equal to the baseline formula on three of the four datasets in each combination of backend and mode. It is worse on N(10⁶, 1) on the CPU, in eager mode and under
jit, and on N(0, 1) underjiton the GPU. The cause is not explained. - The speed is 3.59 times the baseline on the CPU and 2.24 times on the GPU; the threshold of 4.0 was chosen after the measurement.
- Not measured: float64 (
[1e307]*3), the four datasets and the speed benchmark on a TPU, other array sizes. - The baseline of the tests has no shift; the nearest comparison with a shifted baseline is the ablation of Section 4.9, where the variants with the shift and without the compensation are measured.
stable_varis a function, not an estimator: it has nolearn_one, nobudget_s, nomemory_class.- The 1965 paper of Kahan [7] is bibliographic only, not read.
- The depth test is one synthetic stack of layers, not a trained network; it was run in one GPU session (the session saw two devices), with 11 timed runs per depth in the first table and 3 in the second.
- The time ratio of 2.95 at 128 layers is out of line with its neighbours (2.17 and 1.53) and was not investigated.
- The accuracy of the compensated tree is shown by measurements; the papers have no proof for it.
- The TPU test is one core, 30 steps and one session per width, not a converged training; float8 is only a storage type in the low precision test, because the GPU used has no float8 products.
6. Reproduction¶
python benchmarks/stable_variance_float32.py in the library writes benchmarks/stable_variance_float32.json with the backend, the JAX version and the sessions of the speed measurement. The GPU numbers were obtained with the same script. As a check, the script was run again on a Kaggle GPU session with JAX 0.11.1, with stable.py and the script taken unchanged from the library: the accuracy numbers are equal to the ones of stable_variance_float32_gpu.json to all the digits, the claims are the same, and the speed ratio is 2.22 (range 2.18 to 2.25). The standalone program of Appendix A, papers/float32_variance/reproduce_standalone.py, computes the examples and the accuracy runs of this paper with no library of ours: python reproduce_standalone.py. The depth test is python benchmarks/stable_variance_depth.py (the first table) and python benchmarks/stable_variance_depth.py --grid (the second) in the library, run on a Kaggle GPU session. The figures are drawn by docs/assets/stable_variance/make_explained.py and make_depth_figure.py of the library from those results. The code blocks of the documentation page of stable_var were run with the function and their printed outputs are the ones shown there.
References¶
- T. F. Chan, G. H. Golub, R. J. LeVeque. Algorithms for Computing the Sample Variance: Analysis and Recommendations. The American Statistician 37(3), 242-247, 1983.
- T. Ogita, S. M. Rump, S. Oishi. Accurate Sum and Dot Product. SIAM Journal on Scientific Computing 26(6), 1955-1988, 2005. Algorithm 3.1 (
TwoSum). - J. Healy. Accurate and consistent calculation of the mean and variance in Monte-Carlo simulations. arXiv:2206.10662v7, 2022. Algorithm 2.
- J. R. Shewchuk. Adaptive Precision Floating-Point Arithmetic and Fast Robust Geometric Predicates. Discrete and Computational Geometry 18(3), 305-363, 1997. Theorem 7 (
Two-Sum); Lemma 5 (Sterbenz). - TensorFlow,
tensorflow/python/ops/nn_impl.py, functionmoments, lines 1480-1487 (master, read on 2026-10-29). - TensorFlow, issue #117286: the inaccuracy of
tf.nn.momentsin float32. - W. Kahan. Further remarks on reducing truncation errors. Communications of the ACM 8(1), 40, 1965.
- P. Micikevicius et al. Mixed Precision Training. ICLR 2018. Section 3.3, the large reductions in FP32.
- B. Zhang, R. Sennrich. Root Mean Square Layer Normalization. NeurIPS 2019. RMSNorm has no re-centering.