Count-Min in Depth
The count-min sketch (Cormode and Muthukrishnan, 2005) was introduced in Count-Min Sketch and HyperLogLog: rows of 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 be the frequency vector at query time and the counters. Row estimates by , where is the collision noise.
Theorem (Cormode and Muthukrishnan, 2005). Let , , and let be drawn independently from a pairwise independent family. In the strict turnstile model ( at query time, which includes insertion-only streams), for every fixed item :
The space is counters plus words for the hash functions; an update and a query cost .
The proof: because ; by pairwise independence; Markov gives ; the rows are independent, so all of them fail with probability at most .
Three remarks on the conditions:
- The guarantee is per query. For a statement about all items at once, use in place of (a union bound), which costs 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 . 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 and on one large value. The noise is a sum over many colliding items, usually concentrated around its mean, so the measured failure rate of one row is far below . The program builds sketches with rows on a mildly skewed stream and counts the items whose error exceeds .
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 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 , because the few heavy items rarely collide with the query item, and the noise comes from the light tail. Write for with its largest entries set to zero.
Theorem (stated; Cormode and Muthukrishnan, 2005, and later refinements). With columns and rows, every point estimate satisfies (up to a constant factor) with probability , in the strict turnstile model.
Idea. With , a row avoids all heavy items (other than ) with probability at least , and then its noise has expectation at most . Markov and independence of rows finish the argument.
For Zipf-distributed data with parameter the residual is a vanishing fraction of , 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:
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 , so ), 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 .
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 rather than , falling by a factor of five from to , 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- with 128-bit products.
#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 may be negative (the difference of two streams, say), the noise 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 with probability at least when (Markov on , whose expectation is at most ), and the median is wrong only if at least half of the rows are, which a Chernoff bound makes exponentially unlikely in . So with :
The program sketches the difference between today's and yesterday's counts, in which one item really changed by , and compares both estimators.
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 instead of .
Other queries
- Inner products. With the same hash functions for two streams, estimates (a join size in databases) within with probability , for non-negative .
- 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 as they arrive. Every true -heavy hitter is in the heap; items below are excluded with probability each.
Test yourself
In the count-min analysis, where is pairwise independence of the hash functions used?
- To make the rows independent
- To bound the expected collision noise in a row by
- To make the estimate unbiased
- Nowhere
Why does conservative update keep the guarantee ?
- It does not
- Every counter stays an upper bound on the true count of each item hashed to it, since the new value is at least the item's new true count
- Because it uses more rows
- Because it is linear
In the general turnstile model, which count-min estimator should be used?
- The minimum over rows
- The median over rows, giving error in both directions
- The maximum over rows
- The mean over rows
For a Zipf stream with parameter , why is count-min far more accurate than ?
- Because the stream is short
- Because the noise mostly comes from the light tail, and the residual is a small fraction of
- Because the hash functions are better
- Because conservative update is used