Algorithmadvanced
Chan-Golub-LeVeque parallel variance algorithm
Also called pairwise variance algorithm, parallel variance merge.
Merges the counts, means and sums of squared deviations of two partitions into those of their union, so that variance can be computed in parallel or by divide and conquer.
- Time
- Θ(n) worst · best
- Space
- Θ(log n) extra
- Counts
- depth Θ(log n) worstflops 10 n - 9 worst
- Where
- n = the number of data values, at least 2
- Properties
- deterministicexact in exact arithmeticofflineparallelrecursive
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Tony F. Chan, Gene H. Golub, Randall J. LeVeque, 1979
The Chan-Golub-LeVeque algorithm combines the summaries and of two disjoint parts of a data set, each a count, a mean and a sum of squared deviations, into the summary of their union, in a constant number of operations. Because the merge is exact and associative, the sample variance of values can be computed by any tree of merges: in parallel with span , or by the pairwise recursion, whose rounding error grows more slowly than that of a one-pass loop. Welford's algorithm is the special case in which the second part has one value.
In plain words
Split the data into two piles and give each pile to a different worker. Each worker reports three numbers: how many values it has, their average, and their total squared distance from that average. To get the same three numbers for all the data, add the counts, and take the average of the two averages weighted by the counts. The total squared distance is the two totals plus a correction for the gap between the two averages: the square of the gap, times the two counts multiplied together, divided by the total count.
Since piles can be merged in any order and grouping, the data can be cut into many piles and the results merged in a tree. Cutting the data in halves again and again and merging back up also makes the rounding errors smaller than in a loop over the values one at a time.
The problem
The merge. The input is two summaries and , where are the count, the mean and the sum of squared deviations of a nonempty multiset of reals, and likewise for . The output is the summary of . The data themselves are not available.
The variance. The input is with . The output is , and , computed by merges.
The algorithm
COMBINE((n_a, m_a, M_a), (n_b, m_b, M_b)) ▷ n_a, n_b ≥ 1- 1
n ← n_a + n_b - 2
δ ← m_b - m_a ▷ gap between the means - 3
m ← m_a + δ · n_b / n - 4
M ← M_a + M_b + δ · δ · n_a · n_b / n ▷ between-part term - 5
return (n, m, M) PAIRWISE(x, lo, hi) ▷ summary of x[lo .. hi - 1], hi - lo ≥ 1- 6
if hi - lo = 1 then return (1, x[lo], 0) - 7
mid ← lo + ⌊(hi - lo) / 2⌋ - 8
a ← PAIRWISE(x, lo, mid) ▷ lines L8 and L9 may run in parallel - 9
b ← PAIRWISE(x, mid, hi) - 10
return COMBINE(a, b) PAIRWISE-VARIANCE(x_1, ..., x_n) ▷ n ≥ 2- 11
(n, m, M) ← PAIRWISE(x, 0, n) - 12
return m, M / (n - 1), M
Line L3 moves the mean of toward the mean of by the fraction of the gap. Line L4 adds the between-part sum of squares, , written in the form . Both lines use the difference of two means, not the difference of two large sums of squares, so nothing in the merge cancels catastrophically.
Chan, Golub and LeVeque state the merge with the sums and in place of the means, as (their formula (1.5b)). Since , it is the same number in exact arithmetic. For equal halves, , it reduces to (their (1.6)).
Any other tree of merges gives the same exact result: one Welford accumulator per thread, or per block of a file, followed by a tree of COMBINE calls, is the usual parallel form.
Example
Take , in exact arithmetic. PAIRWISE splits it at into and , and the second part at its middle into and .
| merge | |||||
|---|---|---|---|---|---|
| 4 | 5 | ||||
| 5 | |||||
| 10 | |||||
| 5 | 8 |
So , and , as on sample variance. The last merge reads: , and .
Correctness
With the mean of the union, and , so the term of line L4 equals . The shift identity , applied to and to , then shows that is the sum of squared deviations of the union around its mean. So one merge is exact. The same identity, with the counts as weights, shows that merging three summaries in either grouping gives , so COMBINE is associative and commutative, and PAIRWISE is correct by induction on the length. The full proofs are below.
Proof: The merge formula is exact, associative and commutativefull
The arithmetic is exact. A summary is a triple with . The summary of a nonempty finite list is with and .
Lemma 1 (weighted shift). Let , , real and . Then for every real ,
Proof. Write and expand. The cross terms add up to , and the last terms add up to .
Lemma 2 (the merge in centred form). For summaries and , COMBINE (lines L1 to L5) returns with
Proof. Line L1 gives . With (line L2), line L3 gives . Then and , so
which is the term that line L4 adds to .
Theorem 1 (merge). If and for nonempty lists and , then COMBINE, the summary of the concatenation.
Proof. Let = COMBINE. The list has values with sum , so its mean is by Lemma 2. Its sum of squared deviations splits over the two parts:
by Lemma 1 with unit weights and , once for (mean , ) and once for . By Lemma 2 this is .
Theorem 2 (associativity and commutativity). COMBINE is commutative, and associative on all summaries, not only on summaries of data.
Proof. Lemma 2 is symmetric in and , so COMBINE is commutative. For three summaries , let be the mean of COMBINE and the mean of the full merge, which is in either order. By Lemma 2 twice, the of COMBINE(COMBINE is
Lemma 1 with weights , points (whose weighted mean is ) and turns the bracket into . So
which is symmetric in . The same expression results from COMBINE, COMBINE, so the two are equal.
Hence the summaries with COMBINE form a commutative semigroup, and every tree of merges over a partition of the data into nonempty parts gives the same exact result . Adding the triple as an identity, with the rule that COMBINE returns the other argument when one count is 0, makes it a commutative monoid.
Theorem 3 (PAIRWISE). For , PAIRWISE returns .
Proof. By induction on . For , line L6 returns , the summary of one value. For , line L7 gives , since . Both calls of lines L8 and L9 have length between 1 and , so by induction they return and . By Theorem 1, line L10 returns the summary of their concatenation, which is .
Corollary. For , PAIRWISE-VARIANCE returns the mean, and of . Each call on length makes two calls on strictly shorter lengths, so the recursion terminates.
Cost. The recursion tree has leaves and internal nodes, one COMBINE each. Counting the counts as integers, COMBINE does 10 floating-point operations: one subtraction in line L2; a multiplication, a division and an addition in line L3; and in line L4 the products , , , the division by and two additions. With the division of line L12 the total is . The recursion depth is , so the stack is . The two calls of lines L8 and L9 are independent, so with them run in parallel the span satisfies , which gives , with work .
Complexity
PAIRWISE on values makes merges. Counting the counts as integers, each merge does 10 floating-point operations (one in line L2, three in line L3, six in line L4), and line L12 adds one division, so the count is exactly . Chan, Golub and LeVeque count the sum form for a power of 2 as multiplications and additions; their form needs fewer operations per merge.
- Work and span. In the work-span model with lines L8 and L9 in parallel, the work is and the span is . With processors, each running Welford's algorithm on a block of values and then merging in a tree, the time is .
- Space. The recursion is deep, so the stack is . A bottom-up version that keeps one summary per level of a binary counter also uses summaries and reads the data once, in order.
Rounding error. With the condition number defined on Welford's algorithm, Table 1 of Chan, Golub and LeVeque gives the bound for the updating algorithms and for the pairwise algorithm, with small constants dropped. They mark the pairwise bound as a conjecture, based on the bound for Youngs and Cramer's updating and on experiments. Barlow (1990) gave a rounding error analysis of the pairwise algorithm and proved that it is numerically stable. The same improvement from to is proved for plain sums by pairwise summation.
Measured errors. The relative error of in double precision against the exact value of the stored data, computed with fractions.Fraction, for data with standard normal (). The rows come from random.Random(1), one run each, drawn after the four rows of the table on Welford's algorithm, in the order 1000, (that table's third row), .
| textbook | Welford | pairwise | |
|---|---|---|---|
| 1000 | |||
These are single runs, not bounds. In each row the pairwise error is 4 to 30 times smaller than the Welford error, and both are far below their bounds. One run per row cannot show the growth in that the bounds describe; the Welford error at happens to be the smallest of its column.
Properties
- Exact in exact arithmetic, for every split and every tree of merges.
- Associative and commutative. The summaries form a commutative monoid with the identity , if COMBINE returns the other argument when one count is 0. So the merge is a valid operator for a parallel reduction, a segment tree, or the combine step of MapReduce.
- Order dependent in floating point. Different trees give results that differ in the last digits.
- Constant size summaries. A part of any size is described by three numbers.
Variants and improvements
- Welford's algorithm. COMBINE with gives , and , which is Welford's update.
- Covariance. For pairs, merge the two means separately and the co-moment by ; the vector version merges covariance matrices with the outer product .
- Weights. Replace the counts by sums of weights; the formulas do not change.
- Higher moments. The third and fourth central sums also merge in closed form, with more terms in .
- Removing a part. Solving the merge for given the union and removes a part, but it subtracts and can lose accuracy.
- Corrected two-pass. When the data fit in memory, Chan, Golub and LeVeque recommend the corrected two-pass algorithm, , where the second term estimates the rounding error of the first.
When to use it
Use the merge whenever partial results must be combined: threads, GPU blocks, distributed workers, database partitions, or a stream summarized per time window and later rolled up. Use the pairwise recursion when the data are in memory and the accuracy of a one-pass method is not enough but a second pass is not wanted. When one pass over a stream on one processor is all that is needed, Welford's algorithm is simpler.
Pitfalls
- Merging variances instead of sums. Averaging the two variances, even weighted by counts, ignores the between-part term . For and the parts have 8 and 26, which add to 34, while the union has 64.
- The divisor. Merge the sums of squared deviations , not or , and divide only at the end by or , saying which one.
- Integer overflow. In a language with fixed-width integers, can overflow; compute it in floating point.
- Empty parts. Line L3 divides by , so two empty parts cannot be merged; treat a part with count 0 as the identity.
- Textbook parts. If each part computes its by the textbook formula , the merge inherits that cancellation. Compute the parts with Welford's algorithm or by pairwise merging.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/chan-parallel-variance/. The authors are listed in prov/EJXH8E.jsonl.
from collections.abc import Sequence
from typing import NamedTuple
class Summary(NamedTuple):
"""Count n, mean and sum of squared deviations m2 of a nonempty part."""
n: int
mean: float
m2: float
def combine(a: Summary, b: Summary) -> Summary:
"""Return the summary of the union of the parts summarized by a and b.
Precondition: a.n >= 0, b.n >= 0; a part with n = 0 is the identity.
Cost: 10 arithmetic operations. Exact for Fraction means and sums.
"""
if a.n == 0:
return b
if b.n == 0:
return a
n = a.n + b.n # @line L1
delta = b.mean - a.mean # @line L2
mean = a.mean + delta * b.n / n # @line L3
m2 = a.m2 + b.m2 + delta * delta * a.n * b.n / n # @line L4
return Summary(n, mean, m2) # @line L5
def summarize(xs: Sequence[float], lo: int = 0, hi: int | None = None) -> Summary:
"""Summary of xs[lo:hi] by pairwise merging. Precondition: hi - lo >= 1.
Cost: Theta(hi - lo) operations and Theta(log(hi - lo)) recursion depth.
"""
if hi is None:
hi = len(xs)
if hi - lo == 1: # @line L6
return Summary(1, xs[lo], 0 * xs[lo])
mid = lo + (hi - lo) // 2 # @line L7
a = summarize(xs, lo, mid) # @line L8
b = summarize(xs, mid, hi) # @line L9
return combine(a, b) # @line L10
def chan_parallel_variance(xs: Sequence[float]) -> tuple[float, float, float]:
"""Return (mean, sample variance with divisor n - 1, sum of squared deviations).
Precondition: len(xs) >= 2. Cost: 10 n - 9 arithmetic operations.
"""
if len(xs) < 2:
raise ValueError("need at least two values")
n, mean, m2 = summarize(xs, 0, len(xs)) # @line L11
return mean, m2 / (n - 1), m2 # @line L12
test_chan_parallel_variance.py 121 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/chan-parallel-variance/. The authors are listed in prov/EJXH8E.jsonl.
import math
import random
from fractions import Fraction
from chan_parallel_variance import Summary, chan_parallel_variance, combine, summarize
def exact_summary(xs):
"""Oracle: the two-pass formula in exact arithmetic."""
n = len(xs)
m = sum(xs, Fraction(0)) / n
return Summary(n, m, sum(((x - m) ** 2 for x in xs), Fraction(0)))
def welford(xs):
"""Welford's one-value update, written out independently."""
k, m, s = 0, Fraction(0), Fraction(0)
for x in xs:
k += 1
d = x - m
m += d / k
s += d * (x - m)
return Summary(k, m, s)
def random_tree_merge(rng, parts):
"""Merge a list of summaries in a random order and a random tree shape."""
parts = list(parts)
while len(parts) > 1:
i = rng.randrange(len(parts) - 1)
a, b = parts[i], parts[i + 1]
if rng.random() < 0.5:
a, b = b, a
parts[i:i + 2] = [combine(a, b)]
return parts[0]
def test_running_example():
a = exact_summary([Fraction(3), Fraction(7)])
b = exact_summary([Fraction(7), Fraction(9), Fraction(14)])
assert a == (2, 5, 8) and b == (3, 10, 26)
assert combine(a, b) == (5, 8, 64)
assert chan_parallel_variance([Fraction(v) for v in (3, 7, 7, 9, 14)]) == (8, 16, 64)
def test_split_and_pairwise_equal_two_pass():
rng = random.Random(1983)
for _ in range(600):
n = rng.randint(2, 14)
xs = [Fraction(rng.randint(-40, 40), rng.randint(1, 7)) for _ in range(n)]
cut = rng.randint(1, n - 1)
whole = exact_summary(xs)
assert combine(exact_summary(xs[:cut]), exact_summary(xs[cut:])) == whole
assert summarize(xs) == whole
assert welford(xs) == whole
m, v, s = chan_parallel_variance(xs)
assert (m, s) == (whole.mean, whole.m2) and v == whole.m2 / (n - 1)
def test_any_tree_of_merges_gives_the_same_result():
rng = random.Random(77)
for _ in range(500):
n = rng.randint(2, 12)
xs = [Fraction(rng.randint(-20, 20)) for _ in range(n)]
cuts = sorted(rng.sample(range(1, n), rng.randint(0, n - 1)))
bounds = [0] + cuts + [n]
parts = [exact_summary(xs[i:j]) for i, j in zip(bounds, bounds[1:])]
assert random_tree_merge(rng, parts) == exact_summary(xs)
def test_associative_and_commutative_on_arbitrary_summaries():
rng = random.Random(5)
def rand_summary():
return Summary(rng.randint(1, 9), Fraction(rng.randint(-30, 30), rng.randint(1, 5)),
Fraction(rng.randint(0, 50), rng.randint(1, 5)))
for _ in range(500):
a, b, c = rand_summary(), rand_summary(), rand_summary()
assert combine(a, b) == combine(b, a)
assert combine(combine(a, b), c) == combine(a, combine(b, c))
def test_welford_is_the_case_of_one_new_value():
rng = random.Random(11)
for _ in range(500):
k = rng.randint(1, 20)
a = Summary(k, Fraction(rng.randint(-50, 50), 3), Fraction(rng.randint(0, 99), 7))
x = Fraction(rng.randint(-50, 50), 2)
d = x - a.mean
merged = combine(a, Summary(1, x, Fraction(0)))
assert merged.mean == a.mean + d / (k + 1)
assert merged.m2 == a.m2 + d * (x - merged.mean) == a.m2 + Fraction(k, k + 1) * d * d
def test_identity_and_short_input():
a = Summary(3, Fraction(2), Fraction(5))
empty = Summary(0, Fraction(0), Fraction(0))
assert combine(a, empty) == a and combine(empty, a) == a
try:
chan_parallel_variance([1.0])
except ValueError:
pass
else:
raise AssertionError("expected ValueError")
def test_float_error_on_shifted_data():
rng = random.Random(3)
u = 2.0 ** -53
for c in (0.0, 1e4, 1e6):
for n in (2, 17, 1000):
xs = [c + rng.gauss(0.0, 1.0) for _ in range(n)]
whole = exact_summary([Fraction(x) for x in xs])
_, v, _ = chan_parallel_variance(xs)
kappa = math.sqrt(1 + n * float(whole.mean) ** 2 / float(whole.m2))
rel = abs(Fraction(v) - whole.m2 / (n - 1)) / (whole.m2 / (n - 1))
assert rel <= 50 * kappa * u * max(1.0, math.log2(n))
History
Chan, Golub and LeVeque gave the formula for combining two samples and the pairwise algorithm in a Stanford report in 1979 and surveyed the algorithms for the sample variance in The American Statistician in 1983, with error bounds in terms of the condition number . Their bound for the pairwise algorithm was stated as a conjecture. Barlow (1990) proved, by a rounding error analysis, that the pairwise algorithm is numerically stable.
References
- Tony F. Chan, Gene H. Golub and Randall J. LeVeque, Algorithms for computing the sample variance, analysis and recommendations, The American Statistician 37(3), 1983, pp. 242 to 247 (the formulas (1.5) and (1.6) for combining two samples, the pairwise algorithm, Table 1 of error bounds, and Section 4 on parallel use)
- Updating formulae and a pairwise algorithm for computing sample variances, the whole report (the first presentation of the pairwise algorithm)
- Jesse L. Barlow, Error analysis of a pairwise summation algorithm to compute the sample variance, Numerische Mathematik 58(6), 1990, pp. 583 to 590 (the rounding error analysis that proves the pairwise algorithm stable)
- Nicholas J. Higham, Accuracy and Stability of Numerical Algorithms, second edition, SIAM, 2002, Section 1.9 (computing the sample variance)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag EJXH8E Edit this page History Report an error Markdown