Count-Sketch and the l2 Guarantee
Count-min adds every colliding item's count to the query item's counter, so its noise is always positive and grows with . Count-Sketch (Charikar, Chen and Farach-Colton, 2002) adds one idea: each item also gets a random sign, and colliding items cancel each other on average. A row then becomes an unbiased estimator whose variance is governed by , and the median of a few rows gives error . Since , and often , this is a much stronger guarantee for skewed data, paid for with instead of columns.
The sketch
Each of the rows has a bucket hash and a sign hash , both from pairwise independent families, all drawn independently.
Count-Sketch: d rows of w counters
1 update (x, Δ): for each row r: C[r][h_r(x)] ← C[r][h_r(x)] + s_r(x) · Δ
2 query x: return median over r of s_r(x) · C[r][h_r(x)]It is a linear sketch, so it works in the general turnstile model, merges by addition and handles differences of streams.
One row: unbiased, with variance
Fix an item and a row, and drop the index . The row's estimate is
Lemma. and .
Proof. For , pairwise independence of gives , and is independent of , so every noise term has expectation 0. For the variance, write the noise as with . A cross term has
because and by pairwise independence. So .
Notice what pairwise independence of the signs buys: the cross terms vanish, so the variance involves squares of frequencies only. The program checks the lemma for a fixed vector by drawing 1500 independent rows, and compares with one count-min row.
import random
P = (1 << 61) - 1
rng = random.Random(2002)
n, w = 400, 20
f = [int(1000 / (i + 1)) for i in range(n)] # a fixed frequency vector
x = 5
L2sq = sum(v * v for v in f)
cs, cm = [], []
for trial in range(1500): # fresh hash functions for every row
a, b, c, d = (rng.randrange(1, P) for _ in range(4))
h = lambda y: ((a * y + b) % P) % w
s = lambda y: 1 if ((c * y + d) % P) & 1 else -1
row_cs, row_cm = [0] * w, [0] * w
for y in range(n):
row_cs[h(y)] += s(y) * f[y]
row_cm[h(y)] += f[y]
cs.append(s(x) * row_cs[h(x)])
cm.append(row_cm[h(x)])
mean = sum(cs) / len(cs)
var = sum((e - mean) ** 2 for e in cs) / len(cs)
print(f"f_x = {f[x]}; one row, averaged over 1500 random hash functions:")
print(f" Count-Sketch: mean estimate {mean:.1f}, variance {var:.0f}; bound (||f||_2^2 - f_x^2)/w = {(L2sq - f[x] ** 2) / w:.0f}")
print(f" count-min: mean estimate {sum(cm) / len(cm):.1f}; bias about (||f||_1 - f_x)/w = {(sum(f) - f[x]) / w:.1f}")f_x = 166; one row, averaged over 1500 random hash functions:
Count-Sketch: mean estimate 157.1, variance 79317; bound (||f||_2^2 - f_x^2)/w = 80532
count-min: mean estimate 478.8; bias about (||f||_1 - f_x)/w = 310.1
The median of rows
By Chebyshev's inequality, one row with satisfies
The median of independent rows is off by more than only if at least rows are, and by a Chernoff bound that has probability .
Theorem (Charikar, Chen and Farach-Colton, 2002). With , and pairwise independent hash and sign functions, for every fixed item , in the general turnstile model,
The space is counters.
The analysis also gives a tail version, as for count-min: if the largest frequencies are removed, the error is at most for , because with large enough a row avoids the heavy items with constant probability, and the median ignores the rows that do not.
or ?
Compare the two sketches at equal space on a Zipf stream. The worst-case scales are for count-min and for one Count-Sketch row, and here the second is even larger. But the medians and minima discard rows that collide with heavy items, so what really matters are the tails, and the tail of a skewed vector is much smaller than its tail.
import math, random, statistics
from collections import Counter
P = (1 << 61) - 1
class Sketch:
"""d rows of w counters; signed=True gives Count-Sketch, False gives count-min."""
def __init__(self, w, d, signed, rng):
self.w, self.signed = w, signed
self.hs = [tuple(rng.randrange(1, P) for _ in range(4)) for _ in range(d)]
self.C = [[0] * w for _ in range(d)]
def _cells(self, x):
for row, (a, b, c, e) in zip(self.C, self.hs):
sign = (1 if ((c * x + e) % P) & 1 else -1) if self.signed else 1
yield row, ((a * x + b) % P) % self.w, sign
def add(self, x, delta=1):
for row, j, sg in self._cells(x):
row[j] += sg * delta
def estimate(self, x):
vals = [sg * row[j] for row, j, sg in self._cells(x)]
return statistics.median(vals) if self.signed else min(vals)
rng = random.Random(2004)
U, m = 20000, 50000
cum, s = [], 0.0
for i in range(U):
s += 1 / (i + 1) ** 1.0
cum.append(s)
f = Counter(rng.choices(range(U), cum_weights=cum, k=m))
L1 = sum(f.values())
L2 = math.sqrt(sum(v * v for v in f.values()))
print(f"Zipf stream: m = {m}, ||f||_1 = {L1}, ||f||_2 = {L2:.0f}; both sketches use 5 x 200 counters")
for name, signed in [("count-min", False), ("Count-Sketch", True)]:
sk = Sketch(200, 5, signed, rng)
for x, c in f.items():
sk.add(x, c)
top = [x for x, _ in f.most_common(20)]
err_top = max(abs(sk.estimate(x) - f[x]) for x in top)
err_all = statistics.median(abs(sk.estimate(x) - f[x]) for x in range(U))
print(f" {name:12}: largest error on the top 20 items {err_top:6.1f}, median error over all items {err_all:5.1f}")
print(f" scales: ||f||_1 / w = {L1 / 200:.1f}, ||f||_2 / sqrt(w) = {L2 / math.sqrt(200):.1f}")
res2 = math.sqrt(sum(v * v for _, v in f.most_common()[20:]))
res1 = sum(v for _, v in f.most_common()[20:])
print(f" without the top 20: ||f_res||_1 / w = {res1 / 200:.1f}, ||f_res||_2 / sqrt(w) = {res2 / math.sqrt(200):.1f}")Zipf stream: m = 50000, ||f||_1 = 50000, ||f||_2 = 6097; both sketches use 5 x 200 counters
count-min : largest error on the top 20 items 133.0, median error over all items 118.0
Count-Sketch: largest error on the top 20 items 78.0, median error over all items 34.0
scales: ||f||_1 / w = 250.0, ||f||_2 / sqrt(w) = 431.2
without the top 20: ||f_res||_1 / w = 164.9, ||f_res||_2 / sqrt(w) = 76.0
Count-Sketch's typical error is a third of count-min's at the same space, in line with the tail scales. Rules of thumb:
| count-min | Count-Sketch | |
|---|---|---|
| error | , one-sided if | , two-sided |
| columns | ||
| negative frequencies | median variant, | native |
| best for | small space, insertion-only, never underestimating | skewed or signed data, -heavy hitters |
Neither guarantee dominates the other for all inputs: count-min's error shrinks like and Count-Sketch's like , but against different norms, so the right choice depends on how skewed the data is and on whether the frequencies can be negative.
-heavy hitters
An item is a -heavy hitter in if . This is a weaker requirement than -heaviness: in a stream where the top item occurs times and every other item once, the top item is not -heavy for any constant (its share vanishes), but it is -heavy with . Count-Sketch with estimates every such item within , enough to separate it from items with . Finding the candidates without querying all of is the subject of Heavy Hitters in Turnstile Streams. The guarantee is essentially the best possible for sublinear space: finding -heavy hitters for requires polynomial space.
In C++
A Count-Sketch class with templated row count; the sign is the top bit of a second multiply-mod hash. It sketches the difference of two million-item streams that differ in the counts of a few items, and recovers those differences.
#include <algorithm>
#include <array>
#include <cstdint>
#include <cstdio>
#include <random>
#include <vector>
template <std::size_t D>
class CountSketch {
static constexpr std::uint64_t P = (1ULL << 61) - 1;
std::size_t w;
std::array<std::uint64_t, 4 * D> k; // a, b (bucket) and c, e (sign) per row
std::vector<std::int64_t> C;
static std::uint64_t hash(std::uint64_t a, std::uint64_t b, std::uint64_t x) {
return (std::uint64_t)(((unsigned __int128)a * x + b) % P);
}
public:
CountSketch(std::size_t w, std::mt19937_64& rng) : w(w), C(D * w) {
for (auto& v : k) v = 1 + rng() % (P - 1);
}
void update(std::uint64_t x, std::int64_t delta) {
for (std::size_t r = 0; r < D; ++r) {
std::int64_t s = (hash(k[4 * r + 2], k[4 * r + 3], x) >> 60) & 1 ? 1 : -1;
C[r * w + hash(k[4 * r], k[4 * r + 1], x) % w] += s * delta;
}
}
std::int64_t estimate(std::uint64_t x) const {
std::array<std::int64_t, D> v;
for (std::size_t r = 0; r < D; ++r) {
std::int64_t s = (hash(k[4 * r + 2], k[4 * r + 3], x) >> 60) & 1 ? 1 : -1;
v[r] = s * C[r * w + hash(k[4 * r], k[4 * r + 1], x) % w];
}
std::nth_element(v.begin(), v.begin() + D / 2, v.end());
return v[D / 2]; // median (D odd)
}
};
int main() {
std::mt19937_64 rng(2002), gen(5);
CountSketch<7> cs(1000, rng);
// stream A minus stream B: a million random items each, plus planted differences
for (int t = 0; t < 1000000; ++t) cs.update(gen() % 100000, +1);
for (int t = 0; t < 1000000; ++t) cs.update(gen() % 100000, -1);
const std::uint64_t planted[] = {42, 4242, 77777};
const std::int64_t diff[] = {+900, -600, +350};
for (int i = 0; i < 3; ++i) cs.update(planted[i], diff[i]);
for (int i = 0; i < 3; ++i)
std::printf("item %5llu: planted difference %+5lld, estimate %+5lld\n",
(unsigned long long)planted[i], (long long)diff[i], (long long)cs.estimate(planted[i]));
std::printf("an unchanged item, 12345: estimate %+lld (its true difference is small)\n",
(long long)cs.estimate(12345));
}item 42: planted difference +900, estimate +867
item 4242: planted difference -600, estimate -635
item 77777: planted difference +350, estimate +329
an unchanged item, 12345: estimate +7 (its true difference is small)
The background differences come from random fluctuation (each item's count differs by about between the two streams), so is about and the expected error per row about : the planted differences stand out clearly.
Test yourself
Why is a single Count-Sketch row an unbiased estimator of ?
- Because the bucket hash is uniform
- Because each colliding item contributes , whose expectation is 0 by pairwise independence of the signs
- Because the counters are non-negative
- Because the median is taken
What is the variance of one Count-Sketch row's estimate?
- At most
- At most
- At most
- Exactly
How many columns does Count-Sketch need for error with constant probability per row?
A stream has one item with occurrences and all other items once. Which statement is right?
- The item is an -heavy hitter for
- The item is an -heavy hitter for a constant , but not an -heavy hitter for any constant
- The item is neither
- Both notions coincide here