TExcelTAD

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:

Fk=∑i=1nfik,F∞=max⁡i∣fi∣.F_k = \sum_{i=1}^{n} f_i^k , \qquad F_\infty = \max_i \lvert f_i \rvert .

F0F_0 (with 00=00^0 = 0) is the number of distinct items, F1F_1 the stream length (in insertion-only streams), F2F_2 the repeat rate or self-join size, and F∞F_\infty 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 kk.

What the moments measure

  • F2/F12F_2 / F_1^2 is the probability that two independent uniformly random positions of the stream hold the same item. Databases use F2F_2 to estimate the size of a self-join, ∣{(s,t):as=at}∣=F2\lvert \{(s, t) : a_s = a_t\} \rvert = F_2, and more generally ∑ifigi\sum_i f_i g_i for the join of two relations.
  • F2F_2 also measures skew: by the Cauchy-Schwarz inequality F2≥F12/F0F_2 \ge F_1^2 / F_0, with equality when all items are equally frequent, and F∞2≤F2≤F∞F1F_\infty^2 \le F_2 \le F_\infty F_1.
  • In a turnstile stream, F2=∥f∥22F_2 = \lVert f \rVert_2^2 is the squared Euclidean distance between two streams when ff is their difference, and F1F_1 generalizes to the norm ∥f∥1\lVert f \rVert_1.
  • FkF_k for large kk is dominated by the largest frequencies and tends to F∞kF_\infty^k.
python · try it yourself
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 (1±ε)(1 \pm \varepsilon)-approximation with constant success probability, for constant ε\varepsilon unless stated (bounds in words of O(log⁡n+log⁡m)O(\log n + \log m) bits unless they say bits):

Moment Space Notes
F0F_0 Θ(ε−2+log⁡n)\Theta(\varepsilon^{-2} + \log n) bits Kane, Nelson and Woodruff (2010); HyperLogLog is close in practice
F1F_1, insertion-only O(log⁡log⁡m)O(\log \log m) bits approximate counting
FpF_p, 0<p≤20 < p \le 2, turnstile O(ε−2log⁡1δ)O(\varepsilon^{-2} \log \frac{1}{\delta}) words pp-stable distributions (Indyk, 2006); p=2p = 2 is the AMS sketch
FkF_k, k>2k > 2 Θ~(n1−2/k)\tilde{\Theta}(n^{1 - 2/k}) lower bound Bar-Yossef, Jayram, Kumar and Sivakumar (2004), Chakrabarti, Khot and Sun (2003); matching upper bound Indyk and Woodruff (2005)
F∞F_\infty Ω(n)\Omega(n) bits, even for a factor below 2 Alon, Matias and Szegedy (1996), via disjointness
exact F0F_0 or FkF_k, k≠1k \ne 1 Ω(n)\Omega(n) bits, even randomized same reduction

The sharp change at k=2k = 2 is the striking feature: below it polylogarithmic space suffices, above it polynomial space is necessary. The reason is that FkF_k for large kk 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 kk is simple. Pick a uniformly random position JJ of the stream (by reservoir sampling, since mm is not known), and count how many times the item aJa_J occurs from position JJ on, including JJ; call this count rr. Output

X=m(rk−(r−1)k).X = m \bigl( r^k - (r - 1)^k \bigr) .

Lemma (Alon, Matias and Szegedy, 1996). E[X]=Fk\mathbb{E}[X] = F_k, and Var⁡[X]≤k n1−1/kFk2\operatorname{Var}[X] \le k\, n^{1 - 1/k} F_k^2.

Proof of unbiasedness. Group the positions by item. If item ii occurs fif_i times, then over its occurrences, counted from the last to the first, rr takes the values 1,2,…,fi1, 2, \ldots, f_i. Each position has probability 1/m1/m, so

E[X]=1m∑i∑r=1fim(rk−(r−1)k)=∑ifik=Fk,\mathbb{E}[X] = \frac{1}{m} \sum_{i} \sum_{r=1}^{f_i} m\bigl(r^k - (r-1)^k\bigr) = \sum_i f_i^k = F_k ,

because the inner sum telescopes. The variance bound uses rk−(r−1)k≤krk−1r^k - (r-1)^k \le k r^{k-1} and the inequality F1F2k−1≤n1−1/kFk2F_1 F_{2k-1} \le n^{1 - 1/k} F_k^2 (a consequence of Hölder's inequality); the calculation is in the paper. □\square

The estimator is unbiased but has a huge variance. Averaging s1=O(kn1−1/k/ε2)s_1 = O(k n^{1-1/k}/\varepsilon^2) copies brings the relative error to ε\varepsilon with probability 78\frac{7}{8} by Chebyshev, and the median of s2=O(log⁡1δ)s_2 = O(\log \frac{1}{\delta}) such averages gives probability 1−δ1 - \delta. Each copy stores one item and one counter, so the total space is O(kn1−1/kε−2log⁡1δ)O(k n^{1-1/k} \varepsilon^{-2} \log \frac{1}{\delta}) words. For k=2k = 2 that is O(n)O(\sqrt{n}); the next lesson improves it to O(1)O(1) copies per unit of ε−2\varepsilon^{-2} with a sketch, and for k>2k > 2 the later algorithm of Indyk and Woodruff reaches the optimal O~(n1−2/k)\tilde O(n^{1-2/k}).

The program checks unbiasedness exactly (averaging XX over all mm positions) and then runs 600 independent copies, grouped into the median of 10 means of 60.

python · try it yourself
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 (ε,δ)(\varepsilon, \delta)-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 tt with probability exactly 1/t1/t, using Lemire's multiply-shift on a 64-bit random word.

cpp · try it yourself
#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 kn1−1/kFk2k n^{1-1/k} F_k^2 promises little here (for k=2k = 2 and n≈30 000n \approx 30\,000 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 F2F_2.

Test yourself

What does F2/F12F_2 / F_1^2 measure for an insertion-only stream?

  1. The fraction of distinct items
  2. The probability that two independent uniformly random positions hold the same item
  3. The relative frequency of the most common item
  4. The entropy of the stream

Why is the AMS sampling estimator m(rk−(r−1)k)m(r^k - (r-1)^k) unbiased?

  1. Because rr is uniform
  2. Because for each item the values r=1,…,fir = 1, \ldots, f_i each occur once, and the sum ∑r(rk−(r−1)k)\sum_{r} (r^k - (r-1)^k) telescopes to fikf_i^k
  3. Because of pairwise independence
  4. Because kk is even

Which moments can be approximated within 1±ε1 \pm \varepsilon in polylogarithmic space (for constant ε\varepsilon)?

  1. All FkF_k
  2. FkF_k for 0≤k≤20 \le k \le 2, but not for k>2k > 2, which needs n1−2/kn^{1 - 2/k} space up to polylogarithmic factors
  3. Only F1F_1
  4. Only F∞F_\infty