TExcelTAD

The AMS Sketch for F2

The AMS sampling estimator approximates F2F_2 with O(n)O(\sqrt{n}) stored items. Alon, Matias and Szegedy (1996) also gave a far better algorithm for F2F_2, often called the tug-of-war sketch: give every item a random sign, keep the signed sum of the stream, and square it. A handful of such counters estimate F2=∥f∥22F_2 = \lVert f \rVert_2^2 within 1±ε1 \pm \varepsilon, in space independent of nn and mm apart from the word size, and since the sketch is linear, it works in the general turnstile model. Its analysis is the cleanest example of the second-moment method in streaming, and it shows exactly why the signs must be 4-wise independent.

The estimator

Let s:[n]→{−1,+1}s : [n] \to \{-1, +1\} be drawn from a 4-wise independent family. Maintain one counter

Z=∑i=1ns(i)fi,Z = \sum_{i=1}^{n} s(i) f_i ,

which an update (i,Δ)(i, \Delta) changes by s(i)Δs(i)\Delta. Output Z2Z^2.

Theorem (Alon, Matias and Szegedy, 1996). E[Z2]=F2\mathbb{E}[Z^2] = F_2 and Var⁡[Z2]=2(F22−F4)≤2F22\operatorname{Var}[Z^2] = 2\bigl(F_2^2 - F_4\bigr) \le 2F_2^2.

Proof. Write si=s(i)s_i = s(i). Then si2=1s_i^2 = 1, and for distinct indices, 4-wise independence and E[si]=0\mathbb{E}[s_i] = 0 make every product of up to four ss's that contains some index an odd number of times have expectation 0. Expand:

E[Z2]=∑i,jfifj E[sisj]=∑ifi2=F2,\mathbb{E}[Z^2] = \sum_{i,j} f_i f_j\, \mathbb{E}[s_i s_j] = \sum_i f_i^2 = F_2 ,

since E[sisj]=0\mathbb{E}[s_i s_j] = 0 for i≠ji \ne j (pairwise independence would be enough for this). For the fourth moment,

E[Z4]=∑i,j,k,lfifjfkfl E[sisjsksl].\mathbb{E}[Z^4] = \sum_{i,j,k,l} f_i f_j f_k f_l\, \mathbb{E}[s_i s_j s_k s_l] .

A term survives only if every index appears an even number of times: either all four are equal (nn terms, giving F4F_4) or they form two distinct pairs. For a fixed unordered pair {i,j}\{i, j\} with i≠ji \ne j there are (42)=6\binom{4}{2} = 6 ways to place the two ii's among the four positions, so

E[Z4]=F4+6∑i<jfi2fj2=F4+3(F22−F4),\mathbb{E}[Z^4] = F_4 + 6\sum_{i < j} f_i^2 f_j^2 = F_4 + 3\bigl(F_2^2 - F_4\bigr) ,

using ∑i<jfi2fj2=12(F22−F4)\sum_{i < j} f_i^2 f_j^2 = \frac{1}{2}(F_2^2 - F_4). Hence Var⁡[Z2]=E[Z4]−F22=2F22−2F4\operatorname{Var}[Z^2] = \mathbb{E}[Z^4] - F_2^2 = 2F_2^2 - 2F_4. □\square

The terms E[sisjsksl]\mathbb{E}[s_i s_j s_k s_l] for four distinct indices are where 4-wise independence is used. With merely pairwise independent signs they need not vanish, and the variance can be larger than 2F222F_2^2.

Checking the variance exactly

The program builds two families of signs on the 15 non-zero elements xx of the field GF(24)\mathrm{GF}(2^4):

  • s(x)=(−1)b+⟨a1,x⟩+⟨a2,x3⟩s(x) = (-1)^{b + \langle a_1, x\rangle + \langle a_2, x^3 \rangle} (inner products of bit vectors, x3x^3 computed in the field), 512 functions. The vectors (1,x,x3)(1, x, x^3) are those of the parity-check matrix of a BCH code, any four of them are linearly independent, and therefore the signs are 4-wise independent.
  • s(x)=(−1)b+⟨a,x⟩s(x) = (-1)^{b + \langle a, x \rangle}, 32 functions. These are pairwise independent but linear: for x1⊕x2⊕x3⊕x4=0x_1 \oplus x_2 \oplus x_3 \oplus x_4 = 0 the product of the four signs is always +1+1.

For two frequency vectors it averages Z2Z^2 and Z4Z^4 over every function of each family, so the numbers are exact expectations, not estimates.

python · try it yourself
from fractions import Fraction
from itertools import product

def gf16_mul(a, b):                       # GF(2^4) with modulus x^4 + x + 1
    r = 0
    for _ in range(4):
        if b & 1:
            r ^= a
        b >>= 1
        a <<= 1
        if a & 16:
            a ^= 0b10011
    return r

def parity(v):
    return bin(v).count("1") & 1

items = list(range(1, 16))                # the 15 non-zero field elements
cube = {x: gf16_mul(x, gf16_mul(x, x)) for x in items}

def family_4wise():                       # s(x) = (-1)^(b + <a1, x> + <a2, x^3>): 512 functions
    for b, a1, a2 in product(range(2), range(16), range(16)):
        yield {x: -1 if (b ^ parity(a1 & x) ^ parity(a2 & cube[x])) else 1 for x in items}

def family_2wise():                       # s(x) = (-1)^(b + <a, x>): 32 functions, only pairwise independent
    for b, a in product(range(2), range(16)):
        yield {x: -1 if (b ^ parity(a & x)) else 1 for x in items}

def exact_moments(f, family):
    vals = [sum(s[x] * fx for x, fx in f.items()) ** 2 for s in family]
    mean = Fraction(sum(vals), len(vals))
    var = Fraction(sum(v * v for v in vals), len(vals)) - mean ** 2
    return mean, var

for name, f in [("f = 10 on {1, 2, 4, 7}", {1: 10, 2: 10, 4: 10, 7: 10}),
                ("f = 1..15 (each item x has f_x = x)", {x: x for x in items})]:
    F2 = sum(v * v for v in f.values())
    F4 = sum(v ** 4 for v in f.values())
    print(f"{name}: F2 = {F2}, theory for 4-wise signs: Var[Z^2] = 2(F2^2 - F4) = {2 * (F2 ** 2 - F4)}")
    for fam_name, fam in [("4-wise", family_4wise), ("2-wise", family_2wise)]:
        mean, var = exact_moments(f, list(fam()))
        print(f"   {fam_name} signs: E[Z^2] = {mean}, Var[Z^2] = {var}")
f = 10 on {1, 2, 4, 7}: F2 = 400, theory for 4-wise signs: Var[Z^2] = 2(F2^2 - F4) = 240000
   4-wise signs: E[Z^2] = 400, Var[Z^2] = 240000
   2-wise signs: E[Z^2] = 400, Var[Z^2] = 480000
f = 1..15 (each item x has f_x = x): F2 = 1240, theory for 4-wise signs: Var[Z^2] = 2(F2^2 - F4) = 2718576
   4-wise signs: E[Z^2] = 1240, Var[Z^2] = 2718576
   2-wise signs: E[Z^2] = 1240, Var[Z^2] = 12540864

The 4-wise family matches the formula 2(F22−F4)2(F_2^2 - F_4) exactly. The linear family is still unbiased, but on a support closed under XOR, {1,2,4,7}\{1, 2, 4, 7\} with 1⊕2⊕4=71 \oplus 2 \oplus 4 = 7, its variance doubles, and on the full universe it is more than four times larger.

From one counter to an (ε,δ)(\varepsilon, \delta)-approximation

The relative standard deviation of one Z2Z^2 is up to 2\sqrt{2}, useless on its own. The median of means fixes it:

  1. Average k=⌈6/ε2⌉k = \lceil 6/\varepsilon^2 \rceil independent copies: the variance becomes at most 2F22/k=ε2F22/32F_2^2/k = \varepsilon^2 F_2^2 / 3, and by Chebyshev the mean is within εF2\varepsilon F_2 of F2F_2 with probability at least 23\frac{2}{3}.
  2. Take the median of t=O(log⁡1δ)t = O(\log \frac{1}{\delta}) such means.

Corollary. In the general turnstile model, F2F_2 can be (ε,δ)(\varepsilon, \delta)-approximated with O(ε−2log⁡1δ)O(\varepsilon^{-2} \log \frac{1}{\delta}) counters of O(log⁡(nm))O(\log(nm)) bits, plus O(log⁡n)O(\log n) bits per sign function (four coefficients of a cubic polynomial), with update time O(ε−2log⁡1δ)O(\varepsilon^{-2}\log\frac{1}{\delta}).

The update time can be cut to O(log⁡1δ)O(\log \frac{1}{\delta}) by hashing each item into one of the kk counters of a group instead of adding it to all of them: that is exactly a Count-Sketch row, and ∑cC[c]2\sum_c C[c]^2 of a Count-Sketch row is also an unbiased estimator of F2F_2 with variance O(F22/k)O(F_2^2/k) (Thorup and Zhang, 2004). The program sketches the difference of two streams, a turnstile vector with positive and negative entries, using 128 counters with signs from random cubic polynomials modulo 231−12^{31} - 1.

python · try it yourself
import math, random, statistics
from collections import Counter

P = (1 << 31) - 1
def four_wise_sign(rng):
    a, b, c, d = (rng.randrange(P) for _ in range(4))
    return lambda x: 1 if ((((a * x + b) * x + c) * x + d) % P) & 1 else -1   # cubic polynomial: 4-wise

rng = random.Random(4)
U = 3000
today = Counter(rng.randrange(U) for _ in range(30000))
yesterday = Counter(rng.randrange(U) for _ in range(30000))
for x in range(0, U, 300):
    today[x] += 60                                  # ten items grew by 60
f = {x: today[x] - yesterday[x] for x in range(U) if today[x] != yesterday[x]}
F2 = sum(v * v for v in f.values())
F4 = sum(v ** 4 for v in f.values())

copies = 128
Z = [0] * copies
signs = [four_wise_sign(rng) for _ in range(copies)]
for x, fx in f.items():                             # the sketch is linear, so feeding f gives the same Z
    for j, s in enumerate(signs):
        Z[j] += s(x) * fx
X = [z * z for z in Z]                              # basic estimators of F2
print(f"turnstile difference of two streams: F2 = {F2}")
print(f"basic estimators Z^2: mean {statistics.fmean(X):.0f}, relative std {statistics.pstdev(X) / F2:.2f} "
      f"(theory sqrt(2(F2^2 - F4))/F2 = {math.sqrt(2 * (F2 * F2 - F4)) / F2:.2f})")
for k in [8, 32, 128]:
    means = [statistics.fmean(X[i:i + k]) for i in range(0, copies, k)]
    print(f"mean of {k:3} copies: relative errors " + " ".join(f"{m / F2 - 1:+.3f}" for m in means[:4])
          + f"   (theory std sqrt(2/k) = {math.sqrt(2 / k):.3f})")
groups = [statistics.fmean(X[i:i + 16]) for i in range(0, copies, 16)]
print(f"median of 8 means of 16: {statistics.median(groups):.0f} ({statistics.median(groups) / F2 - 1:+.3f})")
turnstile difference of two streams: F2 = 95758
basic estimators Z^2: mean 97595, relative std 1.42 (theory sqrt(2(F2^2 - F4))/F2 = 1.40)
mean of   8 copies: relative errors -0.090 -0.634 +0.149 +0.235   (theory std sqrt(2/k) = 0.500)
mean of  32 copies: relative errors -0.085 -0.345 +0.520 -0.014   (theory std sqrt(2/k) = 0.250)
mean of 128 copies: relative errors +0.019   (theory std sqrt(2/k) = 0.125)
median of 8 means of 16: 89081 (-0.070)

The spread of a single Z2Z^2 matches the theory, and averaging shrinks the error like 2/k\sqrt{2/k}; the means of 32 copies scatter by about ±0.3\pm 0.3, the mean of 128 copies is within 2%. The median of 8 means of 16 is within 7%.

A random projection

The sketch is a matrix AA with ±1\pm 1 entries, kk rows and nn columns, applied to ff, and 1k∥Af∥22\frac{1}{k}\lVert Af \rVert_2^2 estimates ∥f∥22\lVert f \rVert_2^2. This is a Johnson-Lindenstrauss projection with 4-wise independent rows: lengths, and therefore distances ∥f−g∥2\lVert f - g \rVert_2 between streams, are preserved up to 1±ε1 \pm \varepsilon. Inner products follow by polarization: ⟨f,g⟩=14(∥f+g∥22−∥f−g∥22)\langle f, g \rangle = \frac{1}{4}(\lVert f + g \rVert_2^2 - \lVert f - g \rVert_2^2), so two AMS sketches with the same signs estimate a join size ∑ifigi\sum_i f_i g_i within ε∥f∥2∥g∥2\varepsilon \lVert f \rVert_2 \lVert g \rVert_2, often much better than count-min's ε∥f∥1∥g∥1\varepsilon \lVert f \rVert_1 \lVert g \rVert_1.

In C++

The sketch with 7 groups of 50 counters and degree-3 polynomial signs modulo 261−12^{61} - 1, on a stream with insertions and deletions.

cpp · try it yourself
#include <algorithm>
#include <cstdint>
#include <cstdio>
#include <random>
#include <unordered_map>
#include <vector>

// AMS sketch for F2: t groups of k counters Z_j = sum_i s_j(i) f_i, with 4-wise independent signs
// from cubic polynomials modulo p = 2^61 - 1. Estimate: median over groups of the mean of Z_j^2.
class AMS {
    static constexpr std::uint64_t P = (1ULL << 61) - 1;
    std::size_t t, k;
    std::vector<std::uint64_t> coef;                       // 4 coefficients per counter
    std::vector<std::int64_t> Z;
    static std::uint64_t mulmod(std::uint64_t a, std::uint64_t b) { return (std::uint64_t)((unsigned __int128)a * b % P); }
    int sign(std::size_t j, std::uint64_t x) const {
        const std::uint64_t* c = &coef[4 * j];
        std::uint64_t v = c[0];
        for (int i = 1; i < 4; ++i) v = (mulmod(v, x) + c[i]) % P;   // Horner, degree 3
        return (v & 1) ? 1 : -1;
    }
public:
    AMS(std::size_t t, std::size_t k, std::mt19937_64& rng) : t(t), k(k), coef(4 * t * k), Z(t * k) {
        for (auto& c : coef) c = rng() % P;
    }
    void update(std::uint64_t x, std::int64_t delta) {
        for (std::size_t j = 0; j < Z.size(); ++j) Z[j] += sign(j, x) * delta;
    }
    double estimate() const {
        std::vector<double> means;
        for (std::size_t g = 0; g < t; ++g) {
            double s = 0;
            for (std::size_t j = g * k; j < (g + 1) * k; ++j) s += double(Z[j]) * double(Z[j]);
            means.push_back(s / k);
        }
        std::nth_element(means.begin(), means.begin() + t / 2, means.end());
        return means[t / 2];
    }
};

int main() {
    std::mt19937_64 rng(1996), gen(3);
    AMS sketch(7, 50, rng);                                  // 350 counters: eps about sqrt(2/50) = 0.2 per mean
    std::unordered_map<std::uint64_t, std::int64_t> f;
    for (int i = 0; i < 100000; ++i) {                       // insertions with a few heavy items
        std::uint64_t r = gen();
        std::uint64_t x = (r & 7) == 0 ? (r >> 32) % 10 : (r >> 32) % 50000;
        sketch.update(x, +1); ++f[x];
    }
    for (int i = 0; i < 50000; ++i) {                        // then deletions of random items present
        std::uint64_t x = (gen() >> 32) % 50000;
        if (f[x] > 0) { sketch.update(x, -1); --f[x]; }
    }
    double F2 = 0;
    for (auto& [x, v] : f) F2 += double(v) * double(v);
    double e = sketch.estimate();
    std::printf("F2 = %.0f, AMS estimate %.0f (%+.1f%%) from 350 counters\n", F2, e, 100 * (e / F2 - 1));
}
F2 = 16253126, AMS estimate 17260686 (+6.2%) from 350 counters

Test yourself

Which independence of the signs does the proof of E[Z2]=F2\mathbb{E}[Z^2] = F_2 need?

  1. None
  2. Pairwise independence (and mean zero)
  3. 4-wise independence
  4. Full independence

What is Var⁡[Z2]\operatorname{Var}[Z^2] for the tug-of-war sketch with 4-wise independent signs?

  1. F22F_2^2
  2. 2(F22−F4)2(F_2^2 - F_4)
  3. F4F_4
  4. 3F223F_2^2

How many independent copies must be averaged so that Chebyshev gives error at most εF2\varepsilon F_2 with probability 2/32/3?

  1. O(1/ε)O(1/\varepsilon)
  2. About 6/ε26/\varepsilon^2
  3. O(log⁡n)O(\log n)
  4. O(n)O(\sqrt{n})

Why do pairwise independent but linear signs, such as (−1)⟨a,x⟩(-1)^{\langle a, x \rangle}, give a larger variance on some inputs?

  1. They are biased
  2. For four items whose XOR is zero, the product of their signs is always +1+1, so the four-index terms of E[Z4]\mathbb{E}[Z^4] do not vanish
  3. They take values other than ±1\pm 1
  4. They are not pairwise independent