ELLMEngineering Large
Language Models
Download PDF

Chapter 51

Online Statistics and Sampling

On this page

Moments, samples, and tail or window summaries answer different questions. Stable moments describe center and spread; uniform samples preserve inclusion probabilities. Each needs a contract for the quantity and time range it represents.

The runnable examples/streaming.py reference includes mergeable Welford moments and exact immutable-record top-k. Its tests compare moments against Python's independent statistics implementation and compare partitioned top-k against a full sort. The remaining algorithms below are derivations and illustrative excerpts, not implementations certified by that suite.

Online mean and variance

For observations x_1, ..., x_n, define:

  • count n;
  • mean mu_n = (1/n) sum_i x_i;
  • centered sum of squares M2_n = sum_i (x_i - mu_n)^2.

The variance of the observed population is M2_n / n. For independent, identically distributed observations with finite variance, M2_n / (n - 1) is an unbiased estimator of the generating distribution's variance when n >= 2. Serial correlation or nonidentical sampling can invalidate that interpretation without changing the recurrence.

The algebraically simple formula variance = mean(x^2) - mean(x)^2 can catastrophically cancel when the variance is small relative to the squared mean. For values near 10^9 separated by units, both terms are near 10^18; subtracting them can discard the meaningful low-order bits.

Deriving Welford's update

Assume state (n, mu_n, M2_n) and a new observation x. Let n' = n + 1 and delta = x - mu_n.

The new mean is:

mu_n' = (n mu_n + x) / n' = mu_n + delta / n'.

Define delta2 = x - mu_n'. Since mu_n' = mu_n + delta / n', we have delta2 = delta * n / n'.

For the old observations, shifting the center from mu_n to mu_n' gives:

sum_{i=1}^n (x_i - mu_n')^2 = M2_n + n (mu_n - mu_n')^2,

because the cross term contains sum_i (x_i - mu_n) = 0. Adding the new observation and simplifying yields:

M2_n' = M2_n + delta * delta2.

That produces the stable update:

Example status: Illustrative Python excerpt; not standalone.

def update(state, x):
    n, mean, M2 = state
    n2 = n + 1
    delta = x - mean
    mean2 = mean + delta / n2
    delta2 = x - mean2
    M2_2 = M2 + delta * delta2
    return n2, mean2, M2_2

The method avoids subtracting two nearly equal large accumulated moments. It does not make floating point exact: use an adequate accumulator dtype, reject non-finite inputs according to policy, and consider compensated summation or pairwise reduction for extreme dynamic range.

Merging two variance states

Let disjoint partitions A and B have states (n_A, mu_A, M2_A) and (n_B, mu_B, M2_B). Let n = n_A + n_B and delta = mu_B - mu_A.

The combined mean is:

mu = mu_A + delta * n_B / n.

The combined centered sum is:

M2 = M2_A + M2_B + delta^2 * n_A n_B / n.

The final term accounts for separation between partition means. It follows by writing each deviation from the combined mean as (x - mu_A) + (mu_A - mu) or (x - mu_B) + (mu_B - mu). Within-partition cross terms vanish because centered deviations sum to zero.

This merge is associative over exact arithmetic and therefore supports tree reduction. Floating-point results still depend slightly on merge order. Balanced pairwise merging usually limits error better than repeatedly merging a huge state with a tiny state.

Handle empty states explicitly. For vector features, mean and elementwise M2 have feature shape. A full covariance needs a matrix outer-product accumulator and costs O(d^2) state, not O(d).

Weighted updates and removals

For positive weights, store total weight W, weighted mean mu, and:

M2 = sum_i w_i (x_i - mu)^2.

Adding (x, w) is the same as merging the current state with a one-point state:

W' = W + w,

delta = x - mu,

mu' = mu + (w/W') delta,

M2' = M2 + w delta (x - mu') = M2 + (W w/W') delta^2.

Two weighted states merge by replacing counts n_A, n_B in the parallel formula with total weights W_A, W_B.

If an exactly known point (x, w) leaves a window and W' = W - w > 0, reverse the update:

mu' = (W mu - w x) / W',

M2' = M2 - w (x - mu)(x - mu').

Removal is more sensitive to floating-point error, especially when W' is tiny relative to W. Periodically rebuilding from live window state can be safer. If the removed point is not stored exactly, Welford state alone cannot reconstruct it.

Roundoff can leave a tiny negative M2 after removal or merging. Clamp only a value within a justified floating-point tolerance of zero; a materially negative result indicates corrupted state, mismatched removal, or an implementation error.

"Sample variance" for weights is not one universal formula. Frequency weights model repeated observations; reliability or inverse-variance weights use a different effective degrees-of-freedom correction. State the statistical interpretation before dividing weighted M2.

Worked variance trace

For [4, 7, 13, 16], the state evolves:

New value n mean M2
4 1 4 0
7 2 5.5 4.5
13 3 8 42
16 4 10 90

The population variance is 90/4 = 22.5; the unbiased sample variance is 90/3 = 30. Splitting into A=[4,7] and B=[13,16] gives means 5.5 and 14.5, with M2_A=M2_B=4.5. The merge correction is (14.5-5.5)^2 * 2*2/4 = 81, so combined M2 = 4.5 + 4.5 + 81 = 90.

Uniform reservoir sampling

The goal is a simple random sample without replacement of size min(k, N) from a stream whose final length N is unknown. For N >= k, every size-k subset must be equally likely; each item then has inclusion probability k / N. If N < k, retain every item.

Algorithm R fills the reservoir with the first k items. For the item at one-based position i > k, draw j uniformly from {1, ..., i}. If j <= k, replace reservoir slot j; otherwise discard the item.

Example status: Illustrative Python excerpt; not standalone.

def reservoir_sample(stream, k, rng):
    if k < 0:
        raise ValueError("k must be nonnegative")
    reservoir = []
    for i, item in enumerate(stream, start=1):
        if i <= k:
            reservoir.append(item)
        else:
            j = rng.randint(1, i)  # inclusive
            if j <= k:
                reservoir[j - 1] = item
    return reservoir

Uniformity proof

Proceed by induction on processed length i.

  • After i = k, every item is present with probability 1 = k/k.
  • Assume every earlier item is present after i - 1 updates with probability k/(i - 1).
  • New item i is inserted exactly when j <= k, which has probability k/i.
  • An earlier retained item is replaced only when the algorithm chooses its particular slot. That occurs with probability 1/i, so it survives the update with probability (i - 1)/i.

Therefore an earlier item's final inclusion probability is:

(k / (i - 1)) * ((i - 1) / i) = k / i.

The invariant holds for all i >= k, and at N >= k every item has probability k/N. Equal marginal probabilities alone do not prove uniform subsets. For a fixed size-k subset after step i, if it excludes item i, its probability is (1 - k/i) / choose(i-1, k) = 1 / choose(i, k). If it includes item i, there are i-k possible predecessor subsets, each replacing its one extra member with probability 1/i; the total is again (i-k) / (i * choose(i-1, k)) = 1 / choose(i, k). This establishes the stronger uniform-subset invariant.

The algorithm processes every record and makes one random draw after the reservoir fills. Skip-based reservoir algorithms improve constants for very long streams by sampling how many records to skip before the next replacement, while preserving the same sample distribution.

Distributed sampling

Concatenating arbitrary per-shard reservoirs and sampling uniformly from their items is biased when shard sizes differ. A record on a small shard has a larger chance of entering its local reservoir.

Two exact approaches are:

  • assign every record an independent continuous random priority derived from a stable record ID and sampling seed, retain the k smallest priorities per shard, then retain the global k smallest priorities; or
  • merge local uniform reservoirs with weights derived from shard counts using the appropriate multivariate hypergeometric allocation.

The priority approach has the same compositional proof as distributed top-k: a record outside a shard's local k smallest priorities cannot be among the global k smallest. Stable hash-derived priorities also make replay deterministic, but only if record identity and seed are stable and the hash behaves as a suitable pseudorandom function.

For the shard-allocation approach, let shard sizes be n_1, ..., n_p, total N, and let s_j be the number of final sample records drawn from shard j, with sum_j s_j = k. A uniform global subset induces the multivariate hypergeometric law:

P(s_1, ..., s_p) = product_j choose(n_j, s_j) / choose(N, k).

First draw the allocation vector from this distribution. Then choose a uniform size-s_j subset from each shard. A local uniform reservoir of size min(k, n_j) is sufficient: choosing a uniform s_j subset of that reservoir is itself uniform over size-s_j subsets of the shard. This method requires trustworthy shard counts and coordinated random allocation.

Weighted sampling without replacement

For positive item weights w_i, "weighted" needs a target law. One common law chooses each next item with probability proportional to its weight among items not yet selected. Generate independent U_i uniform on (0,1], define:

priority_i = -ln(U_i) / w_i,

and retain the k smallest priorities. Since -ln(U_i) is exponential with rate one, dividing by w_i gives an exponential random variable with rate w_i. For k = 1, the probability that item i has the minimum clock is:

P(i first) = w_i / sum_j w_j.

The memoryless property of exponential clocks makes the next minimum proportional to the remaining weights, producing sequential probability-proportional-to-size sampling without replacement.

The priority is composable across shards: keep local k smallest, then global k smallest. Compute -ln(U)/w rather than U^(1/w) to avoid numerical underflow. Zero or negative weights are outside this model. Inclusion probability is not generally k w_i / sum_j w_j; that expression can exceed one and ignores without-replacement dependence.

Sampling with replacement, weighted sampling, and time-decayed sampling have different distributions. Do not label them "reservoir sampling" without naming the target probability and random-priority construction.

Sampled traces are not the request population

OpenTelemetry sampling guidance distinguishes head decisions, made before a trace completes, from tail decisions that can retain traces based on observed latency or errors. Tail sampling is useful for diagnosis, but its selected traces generally do not represent production traffic uniformly. Measure request counters and SLO histograms before selective trace export, or use a defensible sampling estimator.

Here is an original example. A service handles 10,000 requests: 100 fail and 9,900 succeed. Retain every failure and independently retain each success with probability 0.01. If the realized sample contains 100 failures and 99 successes, the raw sampled error fraction is 100/199 ~= 50.25%, while the population fraction is 1%.

When each request has a known nonzero inclusion probability p_i, estimate a total by sum(y_i / p_i) over retained requests. In the example, weighted failures are 100 and weighted requests are 100 + 99/0.01 = 10,000. Their ratio is 1%. The total estimator is unbiased under its sampling design; a ratio of two estimated totals is not generally unbiased, and this realized sample is unusually convenient. If the complete request count is independently known, divide the estimated failure total by that known count instead.

Keep inclusion probabilities, policy versions, and sampling units with the data. A request-level metric cannot silently use span-level inclusion probabilities. Adaptive quotas, head-plus-tail selection, collector drops, and incomplete traces can make the effective probability unknown. A class sampled with probability zero cannot be recovered by weighting. Report that blind spot, and do not derive a population p99 from a failure-enriched trace sample. Weighted moments and quantiles need estimators that explicitly support those weights.

Worked check: does keeping every error make an unweighted sample suitable for an error-rate dashboard? No. It improves diagnostic coverage while altering the denominator. Separate diagnostic trace selection from population measurement.

Check your design: sampling and moments

When merging two partitions, explain why averaging their means without counts is wrong. For sampling, explain why equal-size samples from unequal-size partitions cannot simply be concatenated and treated as uniform. The answer must weight observations by the populations represented, not by how many summary objects happen to arrive.