TExcelTAD
Home › Streaming, Sketching & Sublinear Algorithms › Count-Sketch and the l2 Guarantee

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 ∥f∥1\lVert f \rVert_1. 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 ∥f∥22\lVert f \rVert_2^2, and the median of a few rows gives error ε∥f∥2\varepsilon \lVert f \rVert_2. Since ∥f∥2≤∥f∥1\lVert f \rVert_2 \le \lVert f \rVert_1, and often ∥f∥2≪∥f∥1\lVert f \rVert_2 \ll \lVert f \rVert_1, this is a much stronger guarantee for skewed data, paid for with 1/ε21/\varepsilon^2 instead of 1/ε1/\varepsilon columns.

The sketch

Each of the dd rows has a bucket hash hr:[n]→[w]h_r : [n] \to [w] and a sign hash sr:[n]→{−1,+1}s_r : [n] \to \{-1, +1\}, both from pairwise independent families, all drawn independently.

text
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 ∥f∥22/w\lVert f \rVert_2^2 / w

Fix an item xx and a row, and drop the index rr. The row's estimate is

Y=s(x) C[h(x)]=s(x)∑ys(y)fy[h(y)=h(x)]=fx+∑y≠xs(x)s(y)fy [h(y)=h(x)].Y = s(x)\, C[h(x)] = s(x) \sum_{y} s(y) f_y [h(y) = h(x)] = f_x + \sum_{y \ne x} s(x)s(y) f_y \, [h(y) = h(x)] .

Lemma. E[Y]=fx\mathbb{E}[Y] = f_x and Var⁡[Y]≤1w∑y≠xfy2≤∥f∥22w\operatorname{Var}[Y] \le \frac{1}{w} \sum_{y \ne x} f_y^2 \le \frac{\lVert f \rVert_2^2}{w}.

Proof. For y≠xy \ne x, pairwise independence of ss gives E[s(x)s(y)]=E[s(x)] E[s(y)]=0\mathbb{E}[s(x)s(y)] = \mathbb{E}[s(x)]\,\mathbb{E}[s(y)] = 0, and ss is independent of hh, so every noise term has expectation 0. For the variance, write the noise as Z=∑y≠xZyZ = \sum_{y \ne x} Z_y with Zy=s(x)s(y)fy[h(y)=h(x)]Z_y = s(x)s(y) f_y [h(y) = h(x)]. A cross term has

E[ZyZy′]=fyfy′ E[s(y)s(y′)] E[[h(y)=h(x)][h(y′)=h(x)]]=0(y≠y′),\mathbb{E}[Z_y Z_{y'}] = f_y f_{y'}\, \mathbb{E}\bigl[s(y)s(y')\bigr]\, \mathbb{E}\bigl[[h(y) = h(x)][h(y') = h(x)]\bigr] = 0 \qquad (y \ne y') ,

because s(x)2=1s(x)^2 = 1 and E[s(y)s(y′)]=0\mathbb{E}[s(y)s(y')] = 0 by pairwise independence. So Var⁡[Z]=∑y≠xE[Zy2]=∑y≠xfy2Pr⁡[h(y)=h(x)]≤1w∑y≠xfy2\operatorname{Var}[Z] = \sum_{y \ne x} \mathbb{E}[Z_y^2] = \sum_{y \ne x} f_y^2 \Pr[h(y) = h(x)] \le \frac{1}{w}\sum_{y \ne x} f_y^2. □\square

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 ff by drawing 1500 independent rows, and compares with one count-min row.

python · try it yourself
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 w=⌈3/ε2⌉w = \lceil 3/\varepsilon^2 \rceil satisfies

Pr⁡[∣Y−fx∣>ε∥f∥2]≤∥f∥22/wε2∥f∥22≤13.\Pr\bigl[\lvert Y - f_x \rvert > \varepsilon \lVert f \rVert_2\bigr] \le \frac{\lVert f \rVert_2^2 / w}{\varepsilon^2 \lVert f \rVert_2^2} \le \frac{1}{3} .

The median of dd independent rows is off by more than ε∥f∥2\varepsilon\lVert f\rVert_2 only if at least d/2d/2 rows are, and by a Chernoff bound that has probability e−Ω(d)e^{-\Omega(d)}.

Theorem (Charikar, Chen and Farach-Colton, 2002). With w=O(1/ε2)w = O(1/\varepsilon^2), d=O(log⁡(1/δ))d = O(\log(1/\delta)) and pairwise independent hash and sign functions, for every fixed item xx, in the general turnstile model,

Pr⁡[∣f^x−fx∣≤ε∥f∥2]≥1−δ.\Pr\Bigl[\lvert \hat f_x - f_x \rvert \le \varepsilon \lVert f \rVert_2\Bigr] \ge 1 - \delta .

The space is O(ε−2log⁡δ−1)O(\varepsilon^{-2} \log \delta^{-1}) counters.

The analysis also gives a tail version, as for count-min: if the kk largest frequencies are removed, the error is at most ε∥fres(k)∥2\varepsilon \lVert f^{\text{res}(k)} \rVert_2 for k=O(1/ε2)k = O(1/\varepsilon^2), because with ww large enough a row avoids the heavy items with constant probability, and the median ignores the rows that do not.

ℓ1\ell_1 or ℓ2\ell_2?

Compare the two sketches at equal space on a Zipf stream. The worst-case scales are ∥f∥1/w\lVert f \rVert_1 / w for count-min and ∥f∥2/w\lVert f \rVert_2 / \sqrt{w} 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 ℓ2\ell_2 tail of a skewed vector is much smaller than its ℓ1\ell_1 tail.

python · try it yourself
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 ε∥f∥1\varepsilon \lVert f \rVert_1, one-sided if f≥0f \ge 0 ε∥f∥2\varepsilon \lVert f \rVert_2, two-sided
columns O(1/ε)O(1/\varepsilon) O(1/ε2)O(1/\varepsilon^2)
negative frequencies median variant, 3ε∥f∥13\varepsilon\lVert f \rVert_1 native
best for small space, insertion-only, never underestimating skewed or signed data, ℓ2\ell_2-heavy hitters

Neither guarantee dominates the other for all inputs: count-min's error shrinks like 1/w1/w and Count-Sketch's like 1/w1/\sqrt{w}, but against different norms, so the right choice depends on how skewed the data is and on whether the frequencies can be negative.

ℓ2\ell_2-heavy hitters

An item is a ϕ\phi-heavy hitter in ℓ2\ell_2 if fx2≥ϕ∥f∥22f_x^2 \ge \phi \lVert f \rVert_2^2. This is a weaker requirement than ℓ1\ell_1-heaviness: in a stream where the top item occurs m\sqrt{m} times and every other item once, the top item is not ℓ1\ell_1-heavy for any constant ϕ\phi (its share 1/m1/\sqrt{m} vanishes), but it is ℓ2\ell_2-heavy with ϕ≈12\phi \approx \frac{1}{2}. Count-Sketch with ε2=ϕ/4\varepsilon^2 = \phi/4 estimates every such item within 12ϕ∥f∥2\frac{1}{2}\sqrt{\phi}\lVert f \rVert_2, enough to separate it from items with fx2<ϕ∥f∥22/16f_x^2 < \phi\lVert f\rVert_2^2/16. Finding the candidates without querying all of [n][n] is the subject of Heavy Hitters in Turnstile Streams. The ℓ2\ell_2 guarantee is essentially the best possible for sublinear space: finding ℓp\ell_p-heavy hitters for p>2p > 2 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.

cpp · try it yourself
#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 ±4\pm 4 between the two streams), so ∥f∥2\lVert f \rVert_2 is about 14001400 and the expected error per row about ∥f∥2/w≈45\lVert f \rVert_2/\sqrt{w} \approx 45: the planted differences stand out clearly.

Test yourself

Why is a single Count-Sketch row an unbiased estimator of fxf_x?

  1. Because the bucket hash is uniform
  2. Because each colliding item contributes s(x)s(y)fys(x)s(y)f_y, whose expectation is 0 by pairwise independence of the signs
  3. Because the counters are non-negative
  4. Because the median is taken

What is the variance of one Count-Sketch row's estimate?

  1. At most ∥f∥1/w\lVert f \rVert_1 / w
  2. At most ∥f∥22/w\lVert f \rVert_2^2 / w
  3. At most ∥f∥2/w\lVert f \rVert_2 / w
  4. Exactly fx2f_x^2

How many columns does Count-Sketch need for error ε∥f∥2\varepsilon \lVert f \rVert_2 with constant probability per row?

  1. O(1/ε)O(1/\varepsilon)
  2. O(1/ε2)O(1/\varepsilon^2)
  3. O(log⁡n)O(\log n)
  4. O(nε)O(n\varepsilon)

A stream has one item with m\sqrt{m} occurrences and all other items once. Which statement is right?

  1. The item is an ℓ1\ell_1-heavy hitter for ϕ=1/2\phi = 1/2
  2. The item is an ℓ2\ell_2-heavy hitter for a constant ϕ\phi, but not an ℓ1\ell_1-heavy hitter for any constant ϕ\phi
  3. The item is neither
  4. Both notions coincide here