One pass, and no room

The moments past the second

Past the second moment no sign trick works, and the estimator that does — pick one position of the stream, count how often its key comes again, report m(r^k − (r − 1)^k) — is unbiased for every moment on every stream. Its variance can be computed exactly rather than sampled, and on real streams it is nowhere near its guarantee: 103 copies give F3 to ten per cent on a flat stream of 2,048 keys, and 2,630 on a moderately skewed one. The guarantee asks for 48,381, and it is not loose. One heavy key among 2,047 keys seen once needs 11,799.

The estimate that squares the stream estimated the second frequency moment, F2=xfx2F_2 = \sum_x f_x^2, with one register. Each key gets a random sign, the register adds up the signed arrivals, and the estimate is the register squared. The cross terms between different keys cancel in expectation because the signs are independent, and what survives is exactly xfx2\sum_x f_x^2.

The other two questions a stream answers cheaply have their own instruments: its length needs a counter, and its number of distinct keys a bank of registers reading leading zeros. Nothing like the sign trick works for the third moment. Cubing a signed sum leaves cross terms of the form fx2fyf_x^2 f_y, and no choice of signs makes them vanish in expectation while keeping fx3\sum f_x^3. The moments past the second have no one-register trick, and they are not exotic: F3F_3 measures how concentrated a stream is more sharply than F2F_2 does, and the high moments are what a skew estimate for load balancing is built from.

Alon, Matias and Szegedy gave a different estimator in the same 1996 paper that introduced the sign trick, and it works for every kk. It is older in spirit and simpler. This page computes exactly what it costs.

Pick a position, count what follows

Choose one position of the stream uniformly at random. Count how many times the key at that position occurs from there to the end, including itself, and call it rr. Report

X=m(rk(r1)k),X = m\,(r^k - (r-1)^k),

where mm is the length of the stream. In a stream processor the position is chosen by reservoir sampling and rr is a counter that restarts when the sample is replaced, so one copy holds one key and one count.

A key seen 6 times: its positions report 91, 61, 37, 19, 7, 1 times the stream's length for the third moment, and they add to 216, which is 6³The sampling estimator picks one position of the stream, counts the occurrences r of that position's key from there to the end, and reports m(r^k − (r − 1)^k), with m the stream's length. For one key seen 6 times, its first position has r = 6 and its last r = 1. For k = 2 the 6 positions report 11, 9, 7, 5, 3, 1 times m, summing to 36 = 6^2 times m. For k = 3 the 6 positions report 91, 61, 37, 19, 7, 1 times m, summing to 216 = 6^3 times m. Each position is chosen with probability 1/m, so the key contributes exactly 6^k to the estimator's mean, and over every key the mean is Fₖ. The first position of a frequent key reports most of its weight, which is where the variance comes from.020406080r = 6r = 5r = 4r = 3r = 2r = 1the key's positions in stream order, and how many of its occurrences are still to comereport, in units of the stream's lengthk = 2k = 3sum 36 = 6^2sum 216 = 6^3one key, frequency 6each position is chosen with probability 1/m
Fig. 1 One key seen 6 times, and what the estimator reports if each of its positions is the one chosen, in units of the stream’s length. For the third moment: 91, 61, 37, 19, 7 and 1, from the first occurrence to the last, adding to 216, which is 6³. For the second: 11, 9, 7, 5, 3 and 1, adding to 36.

The reports telescope. A key of frequency ff occupies ff positions, whose rr values run f,f1,,1f, f-1, \ldots, 1, and the differences rk(r1)kr^k - (r-1)^k over that run add up to fkf^k. Each position is chosen with probability 1/m1/m and reports mm times its difference, so the key contributes exactly fkf^k to the mean. Summed over keys the mean is FkF_k — for every kk, on every stream, with no assumption about hashing or independence at all.

The plate also shows where the trouble will be. A key’s first position carries most of its weight: 91 of the 216 for a key seen six times, and for a key seen a thousand times, the first position alone reports 3×1063 \times 10^6 stream lengths out of a total of 10910^9. Whether the estimator is good depends on how often the rare, heavy reports come up, and that is a property of the stream, not of the estimator.

Its variance is a sum over the stream

Because the report is a fixed function of the position chosen, the estimator’s whole distribution is the list of mm values it would report, one per position, each with probability 1/m1/m. Its mean and variance are sums over that list, and they can be computed exactly for any stream without drawing a single position.

What follows uses streams of 60,000 items over 2,048 keys, drawn from a Zipf distribution with exponent ss. At s=0s = 0 the stream is flat. At s=1.1s = 1.1 it is the stream the estimate that squares the stream measured, eighty-six times more concentrated than a flat one.

On a Zipf stream with s = 0.5, 62% of positions report less than a tenth of F3 and 2.3% report more than ten times itEvery position of a 60,000-item stream over 2,048 keys, sorted by what the sampling estimator reports if that position is the one chosen, as a share of F3, with the cumulative share of positions below each value, on a logarithmic horizontal axis. Flat stream: median 0.667 of the moment, 20% below a tenth, 61% below the moment itself, the largest 7.8 times it. Zipf s = 0.5: median 0.059 of the moment, 62% below a tenth, 89% below the moment itself, the largest 93.6 times it. Zipf s = 1.1: median 0.005 of the moment, 68% below a tenth, 83% below the moment itself, the largest 15.2 times it. The mean of every curve is exactly one; what differs is how much of it sits in a few positions.0.0010.010.1110100what one position reports, as a multiple of F3share of positions reporting less0%25%50%75%100%the momentflat streamZipf s = 0.5Zipf s = 1.1k = 3, every position countedeach curve's mean is exactly one
Fig. 2 Every position of the stream, by what it would report for F3 as a multiple of F3, with the share of positions below each value. On the flat stream the median position reports 0.667 of the moment and none reports more than 7.8 times it. At s = 0.5, 62% of positions report less than a tenth and 2.3% more than ten times, up to 93.6. At s = 1.1, the median position reports 0.005 of the moment.

Every curve on the plate has mean exactly one, and they could hardly look less alike. On the flat stream the reports are spread fairly evenly around the moment. At s=0.5s = 0.5, nine positions in ten report less than the truth and a few report tens of times it. At s=1.1s = 1.1 the median position reports half a per cent of the truth, and the mean is made almost entirely of the first positions of a handful of heavy keys.

Where the moment lives explains the difference between the two skewed streams. At s=1.1s = 1.1 the most frequent key occurs 10,186 times, holds 86% of F3F_3 by itself, and occupies 17% of the stream’s positions, so a random position lands on it one time in six. At s=0.5s = 0.5 no key is that dominant. The most frequent occurs 618 times and holds 32% of F3F_3, and it takes the three heaviest keys to make half the moment — keys that occupy only 2.4% of the positions. Half of what the estimator has to find sits in one position in forty, spread across three keys whose early positions report very different amounts. That is the hard case: a moment concentrated in few positions, but not concentrated enough to be in one key.

A single copy of this estimator is therefore almost always an underestimate and occasionally a large overestimate. That shape is what the estimate that is a median of means was built for. Averaging copies narrows the spread, and taking a median of several averages protects against the rare average that caught a heavy report.

The cost depends on the skew, and not in the obvious direction

The relative variance, the variance of one copy divided by the square of the moment, is the number of copies needed for a relative standard deviation of one, and every copy count below scales from it.

The sampling estimator's relative variance for F3 is 1.02 on a flat stream, 26.29 at s = 0.5 and 1.85 at s = 2The exact variance of one copy of the sampling estimator divided by the square of the moment it estimates, on 60,000-item Zipf streams over 2,048 keys, against the Zipf exponent, on a logarithmic vertical axis. Sampling, F4: 1.94, 15.49, 71.84, 35.26, 14.90, 7.41, 4.62, 2.71. Sampling, F3: 1.02, 3.38, 26.29, 19.65, 9.41, 4.94, 3.15, 1.85. Sampling, F2: 0.38, 0.60, 3.15, 5.67, 3.79, 2.24, 1.49, 0.90 — at s = 0, 0.25, 0.5, 0.75, 1, 1.25, 1.5, 2. The tug-of-war estimator for F2 with four-wise signs, dashed: 2.00, 2.00, 1.96, 1.66, 1.21, 0.84, 0.57, 0.28. On a flat stream sampling is five times better than signs for F2; from s = 0.5 upwards it is worse. Every moment peaks at a moderate skew.0.313103000.250.50.7511.251.52Zipf exponent s of the stream — 0 is flatvariance of one copy ÷ moment²sampling, F4sampling, F3sampling, F2signs, F22,048 keys, 60,000 items, exactdashed: tug-of-war
Fig. 3 The variance of one copy divided by the moment squared, on 60,000-item Zipf streams over 2,048 keys, against the Zipf exponent. For F3: 1.02 on a flat stream, 3.38 at s = 0.25, 26.29 at 0.5, 19.65 at 0.75, 9.41 at 1, 3.15 at 1.5, 1.85 at 2. F2 and F4 peak at the same moderate skews. The dashed line is the sign estimator for F2: 2.00 on a flat stream, falling to 0.28 at s = 2.

Every moment is cheapest at the two ends of the skew and dearest in the middle. The same exponent was the hard case in the skew a few counters cannot repair, for a different reason: there a series stopped converging at exactly one half. On a flat stream the relative variance for F3F_3 is 1.02. At s=0.5s = 0.5 it is 26. At s=2s = 2 it is back below 2.

A flat stream is cheap because every key looks the same. The estimator is then sampling one key’s run, and a run of length ff has the same shape whichever key it belongs to. For large ff the relative variance tends to k2/(2k1)1k^2/(2k-1) - 1: 0.33 for F2F_2, 0.8 for F3F_3, 1.29 for F4F_4. A stream dominated by one key is cheap for the mirror-image reason: nearly every position belongs to that key, and again one run is being sampled.

In between, the stream is a mixture of keys of very different weights, and the estimator’s value depends on which kind of key it lands on. Exactly, to leading order, the relative variance is

k22k1F1F2k1Fk21,\frac{k^2}{2k-1}\cdot\frac{F_1\,F_{2k-1}}{F_k^2} - 1,

and the ratio in the middle is a measure of how unequal the frequencies are, as seen by the kk-th moment. It is one for a flat stream and one for a single-key stream, and at s=0.5s = 0.5 for k=3k = 3 it is 15.2. The formula reproduces every value on the plate to two decimal places.

The second moment shows how differently two unbiased estimators can behave on the same stream. On a flat stream the sampling estimator’s relative variance for F2F_2 is 0.38 and the sign estimator’s is 2.00, so sampling is five times better. From s=0.5s = 0.5 upwards it is worse, and at s=1.1s = 1.1 it is three times worse. The sign estimator’s variance, 2(F22F4)2(F_2^2 - F_4) for four-wise independent signs, is never more than twice the moment squared on any stream. The sampling estimator’s can be far larger, and the next plate says how much larger it can be.

The guarantee, and the stream that earns it

The published guarantee on one copy’s relative variance is kn11/kk \cdot n^{1-1/k}, where nn is the number of distinct keys. It follows from the inequality F1F2k1n11/kFk2F_1 F_{2k-1} \le n^{1-1/k} F_k^2, which is the frequency ratio in the formula above, bounded over all streams on nn keys. At 2,048 keys and k=3k = 3 the guarantee is 484: more than eighteen times the worst Zipf stream on the plate above. So the question is whether any stream comes near it.

One key seen about 1.7·n^(1/k) times among n − 1 keys seen once: at k = 3 and 16,384 keys its relative variance is 472, 0.24 of the boundThe published guarantee on the sampling estimator's relative variance, k·n^(1−1/k) with n the number of distinct keys, against the worst stream of one shape — one heavy key among keys seen once, with the heavy key's frequency chosen to make the variance largest — on logarithmic axes, at 64, 256, 1,024, 4,096, 16,384 keys. k = 2: worst 3.3, 6.7, 13.7, 27.5, 55.2 at heavy frequencies 15, 29, 57, 112, 223, against bounds 16.0, 32.0, 64.0, 128.0, 256.0. k = 3: worst 11.7, 29.5, 74.3, 187.2, 471.6 at heavy frequencies 7, 11, 17, 27, 43, against bounds 48.0, 121.0, 304.8, 768.0, 1935.2. k = 4: worst 23.6, 67.4, 192.6, 548.1, 1552.3 at heavy frequencies 5, 7, 9, 13, 18, against bounds 90.5, 256.0, 724.1, 2048.0, 5792.6. The worst stream grows exactly as the bound does, a steady fifth to a quarter of it, so the guarantee is tight in its shape and the n^(1−1/k) copies it asks for are needed.642561,0244,09616,3841010010³distinct keys in the streamvariance of one copy ÷ moment²bound, k = 2worst stream, k = 2bound, k = 3worst stream, k = 3bound, k = 4worst stream, k = 4one heavy key among singletons, worst frequencydashed: the guarantee
Fig. 4 The guarantee k·n^(1−1/k) against the worst stream of one shape — one heavy key among keys seen once, its frequency chosen to make the variance largest — at 64 to 16,384 keys, on logarithmic axes. At k = 3: 11.7, 29.5, 74.3, 187.2 and 471.6 against guarantees of 48, 121, 305, 768 and 1,935, with the heavy key seen 7, 11, 17, 27 and 43 times. The worst stream grows exactly as the guarantee does, at a steady fifth to a quarter of it.

It does. Take n1n - 1 keys seen once each and one key seen hh times. Search over hh, and the variance is largest when hh is about 1.7n1/k1.7\, n^{1/k} — 43 at 16,384 keys and k=3k = 3. At that hh the relative variance is 472, a quarter of the guarantee, and it keeps that quarter at every size on the plate. The slopes of the solid and dashed lines are identical.

So the guarantee’s shape is right, and its constant is loose by only a factor of four. The n11/kn^{1-1/k} copies the analysis asks for are genuinely needed on some streams. The stream that needs them is not exotic either: a stream of mostly distinct keys with one moderately repeated key is what an event log with one chatty source looks like. What makes it expensive is the size of the heavy key: frequent enough to dominate FkF_k, and rare enough that a random position almost never lands on its first occurrence.

Why that stream, and why a quarter

The heavy key’s frequency and the factor of four both come out of the formula for the relative variance, so they are predictions rather than fitted numbers.

On the stream of n1n - 1 singletons and one key seen hh times, F1nF_1 \approx n, F2k1h2k1F_{2k-1} \approx h^{2k-1} and Fkn+hkF_k \approx n + h^k. Write hk=cnh^k = c\,n, so that cc says how much of the moment the heavy key holds against the singletons. The frequency ratio becomes

F1F2k1Fk2c21/k(1+c)2  n11/k,\frac{F_1 F_{2k-1}}{F_k^2} \approx \frac{c^{\,2-1/k}}{(1+c)^2}\; n^{1-1/k},

which grows as n11/kn^{1-1/k} whatever cc is. That is the guarantee’s growth, and it is why the plate’s two sets of lines are parallel. Maximising over cc gives c=2k1c = 2k - 1: the worst heavy key holds 2k12k - 1 times as much of the moment as all the singletons together. At k=3k = 3 that is a frequency of (5n)1/31.71n1/3(5n)^{1/3} \approx 1.71\,n^{1/3}, and the search found 1.7.

Putting c=5c = 5 back in and multiplying by k2/(2k1)k^2/(2k-1) gives a relative variance of 0.73n2/30.73\,n^{2/3} at k=3k = 3, against the guarantee’s 3n2/33\,n^{2/3} — a ratio of 0.244. The plate measured 0.243 and 0.244. The factor of four between this stream and the guarantee is exact to the arithmetic, and it comes from the one inequality in the analysis that is not tight.

This is the gap that later algorithms closed. The best known space for FkF_k with k>2k > 2 grows as n12/kn^{1-2/k} rather than n11/kn^{1-1/k} — Indyk and Woodruff’s algorithm, 2005 — and a matching lower bound shows no algorithm can do much better. The sampling estimator is a factor of n1/kn^{1/k} off that. At k=3k = 3 on 2,048 keys that is the guarantee’s 48,381 copies against n1/3×1001,300n^{1/3} \times 100 \approx 1{,}300 for the better algorithms, before their constant factors and logarithmic terms, which this page does not measure.

What it spends instead of independence

The independence an estimator spends measured how much independence the sign estimator’s hash family must have. Its mean needs pairwise independence and its variance four-wise, and a family that falls short gives a biased or unstable answer on streams chosen against it.

The sampling estimator needs none of that. Its only randomness is the choice of position, which reservoir sampling makes with one random number per item it considers — the bits counting the coin flips charged it for. The unbiasedness above holds for any stream at all, including one chosen by an adversary who knows everything but the random choices. There is no hash to attack.

What it pays for that is the variance on the plates, and a structural limitation. A sign sketch is linear: its state is a sum of updates, it can be merged with another sketch by adding, and a deletion is an update with a minus sign. The sampling estimator’s state is a position and a count, so two copies cannot be merged into one, and a deletion of an item after its position was sampled has nowhere to go. The two estimators are not rivals on one scale. They differ in what they assume about the stream, and in what they do when the assumption fails.

Copies for ten per cent

Copies for a relative error of 10% on 2,048 keys: F3 needs 103 on a flat stream, 2,630 at s = 0.5, and 11,799 on the worst streamHow many independent copies of the sampling estimator a mean needs for its standard deviation to be a tenth of the moment, from the exact variance, on a logarithmic axis, for moments 2 to 6 on 2,048 keys. F2: flat 38, Zipf 1.1 304, Zipf 0.5 315, the worst stream of one heavy key among singletons 1,942, the guarantee 9,051; F3: flat 103, Zipf 1.1 710, Zipf 0.5 2,630, the worst stream of one heavy key among singletons 11,799, the guarantee 48,381; F4: flat 194, Zipf 1.1 1,096, Zipf 0.5 7,185, the worst stream of one heavy key among singletons 32,534, the guarantee 121,775; F5: flat 325, Zipf 1.1 1,451, Zipf 0.5 12,916, the worst stream of one heavy key among singletons 62,457, the guarantee 222,861; F6: flat 514, Zipf 1.1 1,781, Zipf 0.5 19,227, the worst stream of one heavy key among singletons 95,768, the guarantee 344,821. The guarantee is what a designer who does not know the stream must provision for.1001,00010,000100,000copies for ±10%F2F3F4F5F6flatZipf s = 1.1Zipf s = 0.5worst streamthe guarantee2,048 keys, exact variancecopies = relative variance ÷ 0.01
Fig. 5 Copies whose mean has a relative standard deviation of 10%, on 2,048 keys, for F2 to F6. F3: 103 on a flat stream, 710 on Zipf 1.1, 2,630 on Zipf 0.5, 11,799 on the worst stream of one heavy key among singletons, and 48,381 by the guarantee. F6: 514, 1,781, 19,227, 95,768 and 344,821. The rule is the relative variance divided by 0.01.

The plate is the practical content of everything above. Each copy holds one key and one counter, about 27 bits at this size. A thousand copies is a few kilobytes, and at that size F3F_3 comes out to ten per cent on the flat and Zipf 1.1 streams. On the moderately skewed stream it takes 2,630 copies, and to be safe on any stream a designer who knows nothing about it must provision the guarantee’s 48,381.

Two gaps on the plate have different meanings, and they should not be confused. The gap between the worst stream and the guarantee, a factor of four, is slack in the analysis. The gap between the Zipf streams and the worst stream, a factor of four to seventeen at k=3k = 3, is a property of the data. A system that knows its streams are Zipf-like can provision for that and save most of the memory; a system that promises a bound cannot.

The growth with kk is steep in the guarantee and in the worst stream, and mild on the Zipf streams. From F3F_3 to F6F_6 the guarantee rises sevenfold. The flat stream’s requirement rises fivefold, and the Zipf 1.1 stream’s only two and a half times, because on a stream whose heavy keys are very heavy, a higher moment is dominated by fewer keys and becomes easier to sample, not harder.

What drawn copies actually do

Everything so far has been computed. The last plate draws positions at random, as a stream processor would, and checks the computation against them.

400 means of 256 copies each for F3 at s = 0.5: they average 1.017 of the moment, and 54% of them are under itEach bar counts means of 256 independently drawn positions, on a 60,000-item Zipf stream with s = 0.5 over 2,048 keys, as a multiple of the true F3. The curve is a normal distribution with the exact standard deviation, 0.320. The draws average 1.017 and their median is 0.954: 54% of the means are below the truth, and the ones above it reach 2.14. Even a mean of 256 copies keeps the skew of the positions it averages.020400.50011.502mean of 256 copies, as a multiple of F3of 400 meansthe true momentmedian 0.954k = 3, s = 0.5, 256 copies a meancurve: normal at the exact spread
Fig. 6 Four hundred means of 256 randomly drawn positions each, for F3 on the Zipf 0.5 stream, as multiples of the true F3. The curve is a normal distribution with the exact standard deviation of such a mean, 0.320. The draws average 1.017 and their median is 0.954: 54% of the means fall below the truth, and the highest reaches 2.14.

The draws average within two per cent of the truth, as they must, and their standard deviation is 0.335 against the exact 0.320 — four hundred means estimate a spread to within about four per cent, and this one is within five.

What the normal curve does not match is the shape. Even a mean of 256 copies is skewed. Its median sits below the truth, 54% of the means are underestimates, and the right tail runs further than the curve’s. The central limit theorem is working, but slowly, because the positions it averages are themselves so skewed that a few heavy reports decide each mean. This is the case for a median of means rather than a plain mean, and it is the point the words “on average” are not a number made about quicksort. The plain mean is unbiased, but its typical value is low, and a system reading one mean will usually be told the stream is less concentrated than it is.

What is exact and what is not

The variances on every plate but the last are exact for the streams drawn: sums over the 60,000 positions, with no sampling. The estimator’s mean equals FkF_k to the precision of the arithmetic on every stream and every kk measured. The guarantee holds on every stream measured, and the heavy-among-singletons family comes within a factor of four of it at every size.

What is not measured: the space of the better algorithms is quoted, not built here, and so is the lower bound. The worst stream is the worst of one shape, searched over one parameter. A stream of a different shape could come closer to the guarantee, and the factor of four is a floor on the guarantee’s slack, not its exact value. And every stream is insertions only. The sampling estimator needs positions, and a stream with deletions has no positions to sample from, which is a limitation the sign estimator does not share, since it is linear.

Still open: the estimator that samples keys by their weight

The sampling estimator wastes its copies on light keys. On the Zipf 0.5 stream most positions report under a tenth of the moment, and each of those copies contributes almost nothing. The fix the better algorithms use is to find the heavy keys first — with a sketch of the kind a sketch that is allowed to be under measured — count them nearly exactly, and sample only the remainder, where no key is heavy enough to dominate.

The measurement that follows builds the simplest version. A Count-Sketch finds every key whose frequency exceeds a threshold, their contributions to FkF_k are computed from the sketch’s estimates, and the sampling estimator runs on the stream with those keys removed. It sweeps the threshold and asks how the total space — sketch plus copies — compares with the plain sampling estimator on the four streams here and on the worst stream. The prediction is that on the worst stream the heavy key is found and removed, leaving a stream of singletons whose moment the sampler gets almost exactly. The space should then fall from the guarantee’s n11/kn^{1-1/k} towards n12/kn^{1-2/k}, and the question is at what size of stream the sketch’s own cost stops being worth paying.

Named alongside this one

Essays reaching for the same objects. Nobody chose these; they are what the concept index makes visible.

The objects this essay names

Each one links to every other essay that touches it.

Honest limitMedian of meansRelative errorSamplingSecond frequency momentStreaming algorithmTug-of-warUnbiased estimatorVarianceWorst caseZipf distribution