Frequency Moments
The frequency moments of a stream, introduced as a streaming problem by Alon, Matias and Szegedy (1996), are a family of statistics that contains most of the questions asked of streams:
(with ) is the number of distinct items, the stream length (in insertion-only streams), the repeat rate or self-join size, and the frequency of the most common item. The paper that defined them won the Gödel Prize in 2005, because it showed both sides of the subject at once: surprisingly small-space algorithms for some moments, and matching lower bounds for others. This lesson surveys the landscape, and proves the first general upper bound: the AMS sampling estimator, which works for every .
What the moments measure
- is the probability that two independent uniformly random positions of the stream hold the same item. Databases use to estimate the size of a self-join, , and more generally for the join of two relations.
- also measures skew: by the Cauchy-Schwarz inequality , with equality when all items are equally frequent, and .
- In a turnstile stream, is the squared Euclidean distance between two streams when is their difference, and generalizes to the norm .
- for large is dominated by the largest frequencies and tends to .
import random
from collections import Counter
rng = random.Random(1996)
U = 1000
cum, s = [], 0.0
for i in range(U):
s += 1 / (i + 1) ** 0.9
cum.append(s)
stream = rng.choices(range(U), cum_weights=cum, k=5000)
f = Counter(stream)
m = len(stream)
F = {k: sum(v ** k for v in f.values()) for k in [0, 1, 2, 3]}
Finf = max(f.values())
for k in [0, 1, 2, 3]:
print(f"F_{k} = {F[k]}")
print(f"F_inf = {Finf}")
pairs = sum(stream[rng.randrange(m)] == stream[rng.randrange(m)] for _ in range(100000))
print(f"F_2 / m^2 = {F[2] / m ** 2:.5f}; measured collision rate of random position pairs {pairs / 100000:.5f}")
print(f"Cauchy-Schwarz: F_2 = {F[2]} >= F_1^2 / F_0 = {F[1] ** 2 / F[0]:.0f}")
print(f"F_inf^2 = {Finf ** 2} <= F_2 <= F_inf * F_1 = {Finf * F[1]}")
print(f"(F_3)^(1/3) = {F[3] ** (1 / 3):.0f}, already close to F_inf")F_0 = 817
F_1 = 5000
F_2 = 447300
F_3 = 144687752
F_inf = 477
F_2 / m^2 = 0.01789; measured collision rate of random position pairs 0.01816
Cauchy-Schwarz: F_2 = 447300 >= F_1^2 / F_0 = 30600
F_inf^2 = 227529 <= F_2 <= F_inf * F_1 = 2385000
(F_3)^(1/3) = 525, already close to F_inf
The landscape
The space needed for a -approximation with constant success probability, for constant unless stated (bounds in words of bits unless they say bits):
| Moment | Space | Notes |
|---|---|---|
| bits | Kane, Nelson and Woodruff (2010); HyperLogLog is close in practice | |
| , insertion-only | bits | approximate counting |
| , , turnstile | words | -stable distributions (Indyk, 2006); is the AMS sketch |
| , | lower bound Bar-Yossef, Jayram, Kumar and Sivakumar (2004), Chakrabarti, Khot and Sun (2003); matching upper bound Indyk and Woodruff (2005) | |
| bits, even for a factor below 2 | Alon, Matias and Szegedy (1996), via disjointness | |
| exact or , | bits, even randomized | same reduction |
The sharp change at is the striking feature: below it polylogarithmic space suffices, above it polynomial space is necessary. The reason is that for large is dominated by a single large frequency, and finding a single item with a slightly larger count is as hard as set disjointness.
The AMS sampling estimator
The first algorithm for all is simple. Pick a uniformly random position of the stream (by reservoir sampling, since is not known), and count how many times the item occurs from position on, including ; call this count . Output
Lemma (Alon, Matias and Szegedy, 1996). , and .
Proof of unbiasedness. Group the positions by item. If item occurs times, then over its occurrences, counted from the last to the first, takes the values . Each position has probability , so
because the inner sum telescopes. The variance bound uses and the inequality (a consequence of Hölder's inequality); the calculation is in the paper.
The estimator is unbiased but has a huge variance. Averaging copies brings the relative error to with probability by Chebyshev, and the median of such averages gives probability . Each copy stores one item and one counter, so the total space is words. For that is ; the next lesson improves it to copies per unit of with a sketch, and for the later algorithm of Indyk and Woodruff reaches the optimal .
The program checks unbiasedness exactly (averaging over all positions) and then runs 600 independent copies, grouped into the median of 10 means of 60.
import random, statistics
from collections import Counter
def ams_basic(stream, k, rng):
"""One AMS estimator: a uniformly random position J (reservoir of size 1) and the count r of its item from J on."""
item, r = None, 0
for t, x in enumerate(stream, 1):
if rng.randrange(t) == 0: # with probability 1/t, restart at position t
item, r = x, 0
if x == item:
r += 1
return len(stream) * (r ** k - (r - 1) ** k)
rng = random.Random(1999)
stream = [rng.choice("aaaaabbbcd") for _ in range(400)]
f = Counter(stream)
m = len(stream)
for k in [2, 3]:
Fk = sum(v ** k for v in f.values())
exact_mean = 0 # exact expectation: average over all m starting positions
for J in range(m):
r = stream[J:].count(stream[J])
exact_mean += m * (r ** k - (r - 1) ** k)
exact_mean /= m
est = [ams_basic(stream, k, rng) for _ in range(600)]
groups = [sum(est[i:i + 60]) / 60 for i in range(0, 600, 60)] # 10 means of 60, then the median
print(f"F_{k} = {Fk}: E[estimator] over all positions = {exact_mean:.0f}; "
f"one estimator ranges {min(est)}..{max(est)}; median of 10 means of 60 = {statistics.median(groups):.0f}")F_2 = 56810: E[estimator] over all positions = 56810; one estimator ranges 400..154000; median of 10 means of 60 = 58133
F_3 = 9441520: E[estimator] over all positions = 9441520; one estimator ranges 400..44930800; median of 10 means of 60 = 9756080
A single estimator ranges over more than two orders of magnitude, yet the median of means lands within a few per cent. This median of means pattern is the general recipe for turning any unbiased estimator with bounded relative variance into an -approximation.
In C++
Nine hundred copies run side by side in one pass over 100 000 items (three quarters of them from 300 popular values, the rest from 30 000), grouped as the median of 9 means of 100. A copy restarts at position with probability exactly , using Lemire's multiply-shift on a 64-bit random word.
#include <algorithm>
#include <cstdint>
#include <cstdio>
#include <random>
#include <unordered_map>
#include <vector>
// s independent AMS basic estimators for F_k, all run in the same pass.
struct AMSSampler {
struct Copy { std::uint32_t item = 0; std::uint64_t r = 0; };
std::vector<Copy> copies;
std::uint64_t t = 0;
std::mt19937_64 rng;
AMSSampler(std::size_t s, std::uint64_t seed) : copies(s), rng(seed) {}
void add(std::uint32_t x) {
++t;
for (auto& c : copies) {
if ((unsigned __int128)rng() * t >> 64 == 0) { c.item = x; c.r = 0; } // probability 1/t
if (c.item == x) ++c.r;
}
}
double estimate(int k, std::size_t groups) const { // median of `groups` means
auto pw = [](double v, int k) { double p = 1; while (k--) p *= v; return p; };
std::vector<double> means;
std::size_t g = copies.size() / groups;
for (std::size_t i = 0; i < groups; ++i) {
double s = 0;
for (std::size_t j = i * g; j < (i + 1) * g; ++j)
s += double(t) * (pw(double(copies[j].r), k) - pw(double(copies[j].r) - 1, k));
means.push_back(s / g);
}
std::nth_element(means.begin(), means.begin() + groups / 2, means.end());
return means[groups / 2];
}
};
int main() {
std::mt19937_64 gen(1996);
AMSSampler ams(900, 7);
std::unordered_map<std::uint32_t, std::uint64_t> f;
for (int i = 0; i < 100000; ++i) {
std::uint64_t r = gen();
std::uint32_t x = (r & 3) ? std::uint32_t(r >> 40) % 300 : std::uint32_t(r >> 40) % 30000;
ams.add(x);
++f[x];
}
for (int k : {2, 3}) {
double Fk = 0;
for (auto [x, c] : f) { double p = 1; for (int i = 0; i < k; ++i) p *= double(c); Fk += p; }
double e = ams.estimate(k, 9);
std::printf("F_%d = %.4g, estimate %.4g (%+.1f%%)\n", k, Fk, e, 100 * (e / Fk - 1));
}
}F_2 = 1.886e+07, estimate 1.8e+07 (-4.5%)
F_3 = 4.738e+09, estimate 4.381e+09 (-7.5%)
The worst-case variance bound promises little here (for and it allows a relative standard deviation near 2 for a mean of 100 copies), yet on this skewed input both estimates are within 8 per cent. Nine hundred stored items for that accuracy is still a lot, which is exactly what the next lesson fixes for .
Test yourself
What does measure for an insertion-only stream?
- The fraction of distinct items
- The probability that two independent uniformly random positions hold the same item
- The relative frequency of the most common item
- The entropy of the stream
Why is the AMS sampling estimator unbiased?
- Because is uniform
- Because for each item the values each occur once, and the sum telescopes to
- Because of pairwise independence
- Because is even
Which moments can be approximated within in polylogarithmic space (for constant )?
- All
- for , but not for , which needs space up to polylogarithmic factors
- Only
- Only