TExcelTAD

Count-Min in Depth

The count-min sketch (Cormode and Muthukrishnan, 2005) was introduced in Count-Min Sketch and HyperLogLog: dd rows of ww counters, one pairwise independent hash function per row, an update adds to one counter per row, and a point query takes the minimum over the rows. That lesson proved the basic guarantee. This one looks at it more closely: how loose the analysis is and why, what happens with skewed data, how a small change to the update rule (conservative update) reduces the error, and what must change when frequencies can be negative.

The guarantee, restated with its conditions

Let ff be the frequency vector at query time and C[r][c]C[r][c] the counters. Row rr estimates fxf_x by C[r][hr(x)]=fx+XrC[r][h_r(x)] = f_x + X_r, where Xr=∑y≠x, hr(y)=hr(x)fyX_r = \sum_{y \ne x,\ h_r(y) = h_r(x)} f_y is the collision noise.

Theorem (Cormode and Muthukrishnan, 2005). Let w=⌈e/ε⌉w = \lceil e/\varepsilon \rceil, d=⌈ln⁡(1/δ)⌉d = \lceil \ln(1/\delta) \rceil, and let h1,…,hdh_1, \ldots, h_d be drawn independently from a pairwise independent family. In the strict turnstile model (f≥0f \ge 0 at query time, which includes insertion-only streams), for every fixed item xx:

fx  ≤  f^x=min⁡rC[r][hr(x)]  ≤  fx+ε∥f∥1with probability at least 1−δ.f_x \;\le\; \hat f_x = \min_r C[r][h_r(x)] \;\le\; f_x + \varepsilon \lVert f \rVert_1 \quad \text{with probability at least } 1 - \delta .

The space is wd=O(ε−1log⁡δ−1)wd = O(\varepsilon^{-1} \log \delta^{-1}) counters plus 2d2d words for the hash functions; an update and a query cost O(log⁡δ−1)O(\log \delta^{-1}).

The proof: Xr≥0X_r \ge 0 because f≥0f \ge 0; E[Xr]≤∥f∥1/w≤ε∥f∥1/e\mathbb{E}[X_r] \le \lVert f \rVert_1 / w \le \varepsilon \lVert f \rVert_1 / e by pairwise independence; Markov gives Pr⁡[Xr>ε∥f∥1]≤1/e\Pr[X_r > \varepsilon \lVert f \rVert_1] \le 1/e; the rows are independent, so all of them fail with probability at most e−d≤δe^{-d} \le \delta.

Three remarks on the conditions:

  • The guarantee is per query. For a statement about all nn items at once, use δ/n\delta/n in place of δ\delta (a union bound), which costs d=⌈ln⁡(n/δ)⌉d = \lceil \ln(n/\delta) \rceil rows.
  • The query item must not depend on the hash functions. An adversary who sees the sketch can choose an item that collides everywhere.
  • Pairwise independence is used only for E[Xr]\mathbb{E}[X_r]. Nothing stronger is needed, which is why the sketch is cheap to implement.

How loose is Markov's inequality here?

Markov's inequality is tight only for distributions that put their mass on 00 and on one large value. The noise XrX_r is a sum over many colliding items, usually concentrated around its mean, so the measured failure rate of one row is far below 1/e1/e. The program builds sketches with d=1,…,5d = 1, \ldots, 5 rows on a mildly skewed stream and counts the items whose error exceeds ε∥f∥1\varepsilon \lVert f \rVert_1.

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

P = (1 << 61) - 1
class CountMin:
    def __init__(self, w, d, rng):
        self.w, self.d = w, d
        self.ab = [(rng.randrange(1, P), rng.randrange(P)) for _ in range(d)]
        self.C = [[0] * w for _ in range(d)]
    def cells(self, x):
        return [((a * x + b) % P) % self.w for a, b in self.ab]
    def add(self, x, c=1):
        for row, j in zip(self.C, self.cells(x)):
            row[j] += c
    def estimate(self, x):
        return min(row[j] for row, j in zip(self.C, self.cells(x)))

rng = random.Random(9)
U = 10000
cum, s = [], 0.0
for i in range(U):
    s += 1 / (i + 1) ** 0.8
    cum.append(s)
stream = rng.choices(range(U), cum_weights=cum, k=30000)
true = Counter(stream)
m = len(stream)
eps = 0.01
w = math.ceil(math.e / eps)
print(f"m = {m}, eps = {eps}, w = ceil(e/eps) = {w}, mean noise per row about m/w = {m / w:.0f}")
print(f"fraction of the {U} items with error > eps*m = {eps * m:.0f}:")
print("   d   measured   bound e^-d")
for d in [1, 2, 3, 4, 5]:
    cm = CountMin(w, d, rng)
    for x, c in true.items():           # adding each count at once gives the same sketch as the stream
        cm.add(x, c)
    bad = sum(cm.estimate(x) - true[x] > eps * m for x in range(U))
    print(f"   {d}   {bad / U:8.4f}   {math.exp(-d):10.4f}")
m = 30000, eps = 0.01, w = ceil(e/eps) = 272, mean noise per row about m/w = 110
fraction of the 10000 items with error > eps*m = 300:
   d   measured   bound e^-d
   1     0.0256       0.3679
   2     0.0013       0.1353
   3     0.0000       0.0498
   4     0.0000       0.0183
   5     0.0000       0.0067

The bound is valid but pessimistic by an order of magnitude per row. That is typical: the theorem must hold for every input, including one where the whole mass ∥f∥1\lVert f \rVert_1 sits on a single other item, and there Markov is nearly tight (the noise is either 0 or huge).

Skew helps: the residual bound

For skewed data the error is much smaller than ε∥f∥1\varepsilon \lVert f \rVert_1, because the few heavy items rarely collide with the query item, and the noise comes from the light tail. Write fres(k)f^{\text{res}(k)} for ff with its kk largest entries set to zero.

Theorem (stated; Cormode and Muthukrishnan, 2005, and later refinements). With w=O(k)w = O(k) columns and d=O(log⁡(1/δ))d = O(\log(1/\delta)) rows, every point estimate satisfies f^x−fx≤∥fres(k)∥1/k\hat f_x - f_x \le \lVert f^{\text{res}(k)} \rVert_1 / k (up to a constant factor) with probability 1−δ1 - \delta, in the strict turnstile model.

Idea. With w≥3kw \ge 3k, a row avoids all kk heavy items (other than xx) with probability at least 2/32/3, and then its noise has expectation at most ∥fres(k)∥1/w\lVert f^{\text{res}(k)}\rVert_1 / w. Markov and independence of rows finish the argument.

For Zipf-distributed data with parameter z>1z > 1 the residual ∥fres(k)∥1\lVert f^{\text{res}(k)} \rVert_1 is a vanishing fraction of ∥f∥1\lVert f \rVert_1, so the same sketch is far more accurate than the worst-case bound. The next program shows the effect, together with the second improvement.

Conservative update

In an insertion-only stream, Estan and Varghese (2002) proposed to increment a counter only if it is needed:

text
Conservative update of item x
1  v ← min_r C[r][h_r(x)] + 1          (the new estimate of f_x)
2  for each row r: C[r][h_r(x)] ← max(C[r][h_r(x)], v)

Every counter still upper-bounds the true count of every item hashed to it (by induction: the minimum was at least fxf_x, so v≥fx+1v \ge f_x + 1), so estimates still never fall below the truth, and counters grow less, so the error can only shrink. The price: the sketch is no longer linear, so it supports neither deletions nor merging by addition. The program compares the standard and conservative update with the same hash functions on streams of increasing skew, next to the residual bound for k=10k = 10.

python · try it yourself
import random
from collections import Counter

P = (1 << 61) - 1
def make_hashes(d, w, rng):
    ab = [(rng.randrange(1, P), rng.randrange(P)) for _ in range(d)]
    return lambda x: [((a * x + b) % P) % w for a, b in ab]

def run(stream, d, w, rng, conservative):
    cells = make_hashes(d, w, rng)
    C = [[0] * w for _ in range(d)]
    for x in stream:
        js = cells(x)
        if conservative:                       # raise only the counters that are below the new estimate
            new = min(C[r][j] for r, j in enumerate(js)) + 1
            for r, j in enumerate(js):
                if C[r][j] < new:
                    C[r][j] = new
        else:
            for r, j in enumerate(js):
                C[r][j] += 1
    return lambda x: min(C[r][j] for r, j in enumerate(cells(x)))

rng = random.Random(2002)
U, m, d, w = 5000, 30000, 3, 100
print(f"m = {m}, d = {d}, w = {w}: mean overestimate over all {U} items (eps*m with eps = e/w is {2.718 / w * m:.0f})")
print("  skew z   standard   conservative   tail ||f - top 10||_1 / w")
for z in [0.6, 1.0, 1.4]:
    cum, s = [], 0.0
    for i in range(U):
        s += 1 / (i + 1) ** z
        cum.append(s)
    stream = rng.choices(range(U), cum_weights=cum, k=m)
    true = Counter(stream)
    tail = m - sum(c for _, c in true.most_common(10))
    res = []
    for cons in [False, True]:
        est = run(stream, d, w, random.Random(7), cons)      # same hash functions for both
        res.append(sum(est(x) - true[x] for x in range(U)) / U)
    print(f"  {z:6}   {res[0]:8.1f}   {res[1]:12.1f}   {tail / w:9.1f}")
m = 30000, d = 3, w = 100: mean overestimate over all 5000 items (eps*m with eps = e/w is 815)
  skew z   standard   conservative   tail ||f - top 10||_1 / w
     0.6      254.2          144.0       282.0
     1.0      155.1           97.2       204.0
     1.4       48.1           33.1        87.5

The mean error follows the tail ∥fres(10)∥1/w\lVert f^{\text{res}(10)} \rVert_1 / w rather than ∥f∥1\lVert f \rVert_1, falling by a factor of five from z=0.6z = 0.6 to z=1.4z = 1.4, and conservative update removes another 30 to 45 per cent of it. In the C++ run below, with a million items, it halves the error.

In C++

A count-min sketch with both update rules behind one flag, on a million-item stream; the hash is multiply-mod-(261−1)(2^{61} - 1) with 128-bit products.

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

class CountMin {
    static constexpr std::uint64_t P = (1ULL << 61) - 1;
    std::size_t w, d;
    bool conservative;
    std::vector<std::uint64_t> a, b;
    std::vector<std::uint32_t> C;                          // d rows of w counters, row-major
    std::size_t cell(std::size_t r, std::uint64_t x) const {
        unsigned __int128 z = (unsigned __int128)a[r] * x + b[r];
        return (std::size_t)((std::uint64_t)(z % P) % w);
    }
public:
    CountMin(std::size_t w, std::size_t d, bool cons, std::mt19937_64& rng) : w(w), d(d), conservative(cons), C(w * d) {
        for (std::size_t r = 0; r < d; ++r) { a.push_back(1 + rng() % (P - 1)); b.push_back(rng() % P); }
    }
    std::uint32_t estimate(std::uint64_t x) const {
        std::uint32_t best = UINT32_MAX;
        for (std::size_t r = 0; r < d; ++r) best = std::min(best, C[r * w + cell(r, x)]);
        return best;
    }
    void add(std::uint64_t x) {
        if (!conservative) { for (std::size_t r = 0; r < d; ++r) ++C[r * w + cell(r, x)]; return; }
        std::uint32_t v = estimate(x) + 1;
        for (std::size_t r = 0; r < d; ++r) { auto& c = C[r * w + cell(r, x)]; c = std::max(c, v); }
    }
};

int main() {
    const std::size_t w = 272, d = 4, m = 1000000;          // eps = e/w = 0.01, delta = e^-4
    std::mt19937_64 seed(2005), gen(77);
    CountMin plain(w, d, false, seed);
    std::mt19937_64 seed2(2005);
    CountMin cons(w, d, true, seed2);                        // same hash functions
    std::unordered_map<std::uint64_t, std::uint32_t> exact;
    for (std::size_t t = 0; t < m; ++t) {
        std::uint64_t r = gen();
        std::uint64_t x = (r & 1) ? std::countr_zero(r >> 1) : (r >> 8) % 100000;
        plain.add(x); cons.add(x); ++exact[x];
    }
    double s1 = 0, s2 = 0;
    std::uint32_t w1 = 0, w2 = 0;
    for (auto [x, f] : exact) {
        s1 += plain.estimate(x) - f; s2 += cons.estimate(x) - f;
        w1 = std::max(w1, plain.estimate(x) - f); w2 = std::max(w2, cons.estimate(x) - f);
    }
    std::printf("%zu distinct items; bound eps*m = %.0f\n", exact.size(), 0.01 * m);
    std::printf("standard:     mean overestimate %7.1f, largest %u\n", s1 / exact.size(), w1);
    std::printf("conservative: mean overestimate %7.1f, largest %u\n", s2 / exact.size(), w2);
}
99290 distinct items; bound eps*m = 10000
standard:     mean overestimate  1790.4, largest 1924
conservative: mean overestimate   841.2, largest 847

General turnstile: the median

If ff may be negative (the difference of two streams, say), the noise XrX_r can be negative too, the minimum is biased downwards, and the one-sided guarantee is gone. The fix is to take the median of the rows: each row is within 3ε∥f∥13\varepsilon\lVert f \rVert_1 with probability at least 23\frac{2}{3} when w=⌈e/ε⌉w = \lceil e/\varepsilon \rceil (Markov on ∣Xr∣\lvert X_r \rvert, whose expectation is at most ∥f∥1/w\lVert f \rVert_1/w), and the median is wrong only if at least half of the rows are, which a Chernoff bound makes exponentially unlikely in dd. So with d=O(log⁡(1/δ))d = O(\log(1/\delta)):

∣f^x−fx∣≤3ε∥f∥1with probability at least 1−δ(general turnstile, median estimator).\lvert \hat f_x - f_x \rvert \le 3\varepsilon \lVert f \rVert_1 \quad \text{with probability at least } 1 - \delta \qquad \text{(general turnstile, median estimator)} .

The program sketches the difference between today's and yesterday's counts, in which one item really changed by +300+300, and compares both estimators.

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

P = (1 << 61) - 1
rng = random.Random(11)
U, d, w = 2000, 7, 200
ab = [(rng.randrange(1, P), rng.randrange(P)) for _ in range(d)]
C = [[0] * w for _ in range(d)]
def cells(x):
    return [((a * x + b) % P) % w for a, b in ab]

# general turnstile: yesterday's counts are subtracted from today's, so f may be negative
today = Counter(rng.randrange(U) for _ in range(40000))
yesterday = Counter(rng.randrange(U) for _ in range(40000))
today[17] += 300                               # one item really changed
f = {x: today[x] - yesterday[x] for x in range(U)}
for x, c in today.items():
    for r, j in enumerate(cells(x)):
        C[r][j] += c
for x, c in yesterday.items():
    for r, j in enumerate(cells(x)):
        C[r][j] -= c
L1 = sum(abs(v) for v in f.values())
mins = {x: min(C[r][j] for r, j in enumerate(cells(x))) for x in range(U)}
meds = {x: statistics.median(C[r][j] for r, j in enumerate(cells(x))) for x in range(U)}
for name, est in [("minimum of rows", mins), ("median of rows", meds)]:
    errs = sorted(abs(est[x] - f[x]) for x in range(U))
    print(f"{name:16} median error {errs[U // 2]:6.1f}  max error {errs[-1]:6.1f}  "
          f"estimate for item 17: {est[17]:7.1f} (true {f[17]})")
print(f"||f||_1 = {L1}, ||f||_1 / w = {L1 / w:.1f}")
minimum of rows  median error   24.0  max error   74.0  estimate for item 17:   275.0 (true 297)
median of rows   median error    6.0  max error   30.0  estimate for item 17:   292.0 (true 297)
||f||_1 = 10212, ||f||_1 / w = 51.1

The minimum is now systematically too low, while the median is centred on the truth. For signed data the Count-Sketch, with random signs, is usually the better tool, and its error scales with ∥f∥2\lVert f \rVert_2 instead of ∥f∥1\lVert f \rVert_1.

Other queries

  • Inner products. With the same hash functions for two streams, min⁡r∑cCf[r][c] Cg[r][c]\min_r \sum_c C_f[r][c] \, C_g[r][c] estimates ⟨f,g⟩\langle f, g \rangle (a join size in databases) within ε∥f∥1∥g∥1\varepsilon \lVert f \rVert_1 \lVert g \rVert_1 with probability 1−δ1 - \delta, for non-negative f,gf, g.
  • Range queries and quantiles use one sketch per level of a dyadic decomposition of the universe; the same structure finds heavy hitters in turnstile streams (Heavy Hitters in Turnstile Streams).
  • Heavy hitters in insertion-only streams: keep a heap of the items whose estimate exceeds ϕm\phi m as they arrive. Every true ϕ\phi-heavy hitter is in the heap; items below (ϕ−ε)m(\phi - \varepsilon) m are excluded with probability 1−δ1 - \delta each.

Test yourself

In the count-min analysis, where is pairwise independence of the hash functions used?

  1. To make the rows independent
  2. To bound the expected collision noise in a row by ∥f∥1/w\lVert f \rVert_1 / w
  3. To make the estimate unbiased
  4. Nowhere

Why does conservative update keep the guarantee f^x≥fx\hat f_x \ge f_x?

  1. It does not
  2. Every counter stays an upper bound on the true count of each item hashed to it, since the new value min⁡+1\min + 1 is at least the item's new true count
  3. Because it uses more rows
  4. Because it is linear

In the general turnstile model, which count-min estimator should be used?

  1. The minimum over rows
  2. The median over rows, giving error O(ε∥f∥1)O(\varepsilon \lVert f \rVert_1) in both directions
  3. The maximum over rows
  4. The mean over rows

For a Zipf stream with parameter z=1.4z = 1.4, why is count-min far more accurate than ε∥f∥1\varepsilon \lVert f \rVert_1?

  1. Because the stream is short
  2. Because the noise mostly comes from the light tail, and the residual ∥fres(k)∥1\lVert f^{\text{res}(k)} \rVert_1 is a small fraction of ∥f∥1\lVert f \rVert_1
  3. Because the hash functions are better
  4. Because conservative update is used