The AMS Sketch for F2
The AMS sampling estimator approximates with stored items. Alon, Matias and Szegedy (1996) also gave a far better algorithm for , 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 within , in space independent of and 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 be drawn from a 4-wise independent family. Maintain one counter
which an update changes by . Output .
Theorem (Alon, Matias and Szegedy, 1996). and .
Proof. Write . Then , and for distinct indices, 4-wise independence and make every product of up to four 's that contains some index an odd number of times have expectation 0. Expand:
since for (pairwise independence would be enough for this). For the fourth moment,
A term survives only if every index appears an even number of times: either all four are equal ( terms, giving ) or they form two distinct pairs. For a fixed unordered pair with there are ways to place the two 's among the four positions, so
using . Hence .
The terms 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 .
Checking the variance exactly
The program builds two families of signs on the 15 non-zero elements of the field :
- (inner products of bit vectors, computed in the field), 512 functions. The vectors 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.
- , 32 functions. These are pairwise independent but linear: for the product of the four signs is always .
For two frequency vectors it averages and over every function of each family, so the numbers are exact expectations, not estimates.
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 exactly. The linear family is still unbiased, but on a support closed under XOR, with , its variance doubles, and on the full universe it is more than four times larger.
From one counter to an -approximation
The relative standard deviation of one is up to , useless on its own. The median of means fixes it:
- Average independent copies: the variance becomes at most , and by Chebyshev the mean is within of with probability at least .
- Take the median of such means.
Corollary. In the general turnstile model, can be -approximated with counters of bits, plus bits per sign function (four coefficients of a cubic polynomial), with update time .
The update time can be cut to by hashing each item into one of the counters of a group instead of adding it to all of them: that is exactly a Count-Sketch row, and of a Count-Sketch row is also an unbiased estimator of with variance (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 .
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 matches the theory, and averaging shrinks the error like ; the means of 32 copies scatter by about , 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 with entries, rows and columns, applied to , and estimates . This is a Johnson-Lindenstrauss projection with 4-wise independent rows: lengths, and therefore distances between streams, are preserved up to . Inner products follow by polarization: , so two AMS sketches with the same signs estimate a join size within , often much better than count-min's .
In C++
The sketch with 7 groups of 50 counters and degree-3 polynomial signs modulo , on a stream with insertions and deletions.
#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 need?
- None
- Pairwise independence (and mean zero)
- 4-wise independence
- Full independence
What is for the tug-of-war sketch with 4-wise independent signs?
How many independent copies must be averaged so that Chebyshev gives error at most with probability ?
- About
Why do pairwise independent but linear signs, such as , give a larger variance on some inputs?
- They are biased
- For four items whose XOR is zero, the product of their signs is always , so the four-index terms of do not vanish
- They take values other than
- They are not pairwise independent