Count-Min Sketch and HyperLogLog
A sketch is a small summary of a large collection, built in one pass, that answers some queries approximately. Sketches trade exactness for space that is independent of the data size (or logarithmic in it), and they can usually be merged: the sketch of a union is computed from the sketches of the parts, which is what makes them useful in distributed systems. This lesson presents two of the most used: the count-min sketch for frequencies and HyperLogLog for the number of distinct elements. Their theory, with lower bounds and many more sketches, is the subject of Streaming, Sketching & Sublinear Algorithms.
Count-min: frequencies with one-sided error
A stream of items defines a frequency vector , with the number of occurrences of , and the stream length. The count-min sketch (Cormode and Muthukrishnan, 2005) is a array of counters and hash functions into , drawn from a pairwise independent family.
- UPDATE: for every row , increment .
- ESTIMATE: .
Theorem. With and , for every item : always, and with probability at least . The space is counters, independent of the number of distinct items.
Proof. Each counter holds plus the counts of the other items hashed to the same cell, so it never underestimates. The excess has expectation by pairwise independence. By Markov's inequality, . The rows use independent hash functions, so all rows exceed with probability at most , and the minimum is then the only way to be wrong.
import math, random
from collections import Counter
P = (1 << 61) - 1 # Mersenne prime for pairwise independent hashing
class CountMin:
def __init__(self, eps, delta, rng):
self.w = math.ceil(math.e / eps) # counters per row
self.d = math.ceil(math.log(1 / delta)) # rows
self.ab = [(rng.randrange(1, P), rng.randrange(P)) for _ in range(self.d)]
self.C = [[0] * self.w for _ in range(self.d)]
def _h(self, j, x):
a, b = self.ab[j]
return ((a * x + b) % P) % self.w
def add(self, x, c=1):
for j in range(self.d): self.C[j][self._h(j, x)] += c
def estimate(self, x): # never below the true count
return min(self.C[j][self._h(j, x)] for j in range(self.d))
rng = random.Random(2005)
universe = 50000
weights = [1 / (i + 1) ** 1.1 for i in range(universe)] # a Zipf-like stream
stream = rng.choices(range(universe), weights=weights, k=100000)
true = Counter(stream)
eps, delta = 0.002, 0.01
cm = CountMin(eps, delta, rng)
for x in stream: cm.add(x)
L1 = len(stream)
errors = [cm.estimate(x) - true[x] for x in range(universe)]
assert min(errors) >= 0
bad = sum(e > eps * L1 for e in errors)
print(f"stream of {L1} items, {len(true)} distinct; sketch {cm.d} x {cm.w} = {cm.d * cm.w} counters")
print(f"bound: overestimate <= eps * L1 = {eps * L1:.0f} with probability >= {1 - delta}")
print(f"largest overestimate {max(errors)}, mean {sum(errors) / universe:.2f}; items above the bound: {bad} of {universe}")
for x in [0, 1, 9, 99, 999]:
print(f" item {x:3}: true {true[x]:5}, estimate {cm.estimate(x):5}")stream of 100000 items, 14346 distinct; sketch 5 x 1360 = 6800 counters
bound: overestimate <= eps * L1 = 200 with probability >= 0.99
largest overestimate 64, mean 16.03; items above the bound: 0 of 50000
item 0: true 13850, estimate 13864
item 1: true 6376, estimate 6386
item 9: true 1178, estimate 1192
item 99: true 94, estimate 113
item 999: true 9, estimate 23
No item exceeded the bound, and the largest overestimate was about a third of it. The estimates are excellent for heavy items (relative to their size) and poor for rare ones: an error of is tiny next to 13850 and huge next to 9. That is the intended use: finding heavy hitters (items with ) and answering frequency queries for popular items, in network monitoring, query logs and NLP counting. Count-min supports deletions too (decrement), and two sketches with the same hash functions merge by adding their arrays.
In C++
The same sketch with 128-bit products for the hashing, on a million-item stream in which item has probability about for small , mixed with uniform items.
#include <algorithm>
#include <bit>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <random>
#include <unordered_map>
#include <vector>
// Count-min sketch with d rows of w counters and hashes ((a x + b) mod p) mod w, p = 2^61 - 1.
class CountMin {
static constexpr std::uint64_t P = (1ULL << 61) - 1;
std::size_t w, d;
std::vector<std::uint64_t> a, b;
std::vector<std::vector<std::uint32_t>> C;
static std::uint64_t mulmod(std::uint64_t x, std::uint64_t y) {
unsigned __int128 z = static_cast<unsigned __int128>(x) * y;
std::uint64_t r = static_cast<std::uint64_t>(z & P) + static_cast<std::uint64_t>(z >> 61);
return r >= P ? r - P : r;
}
std::size_t h(std::size_t j, std::uint64_t x) const { return ((mulmod(a[j], x) + b[j]) % P) % w; }
public:
CountMin(double eps, double delta, std::mt19937_64& rng)
: w(static_cast<std::size_t>(std::ceil(std::exp(1.0) / eps))),
d(static_cast<std::size_t>(std::ceil(std::log(1 / delta)))), C(d, std::vector<std::uint32_t>(w)) {
for (std::size_t j = 0; j < d; ++j) { a.push_back(1 + rng() % (P - 1)); b.push_back(rng() % P); }
}
void add(std::uint64_t x) { for (std::size_t j = 0; j < d; ++j) ++C[j][h(j, x)]; }
std::uint32_t estimate(std::uint64_t x) const {
std::uint32_t best = UINT32_MAX;
for (std::size_t j = 0; j < d; ++j) best = std::min(best, C[j][h(j, x)]);
return best;
}
std::size_t counters() const { return w * d; }
};
int main() {
std::mt19937_64 rng(2005);
const double eps = 0.0005, delta = 0.01;
CountMin cm(eps, delta, rng);
std::unordered_map<std::uint64_t, std::uint32_t> exact;
const int N = 1000000;
for (int i = 0; i < N; ++i) { // skewed stream: item k with probability ~ 2^-k
std::uint64_t r = rng();
std::uint64_t x = r & 1 ? std::countr_zero(r >> 1) : (r >> 8) % 200000;
cm.add(x);
++exact[x];
}
std::uint32_t worst = 0;
int above = 0;
for (auto [x, c] : exact) {
std::uint32_t e = cm.estimate(x);
worst = std::max(worst, e - c);
above += e - c > eps * N;
}
std::printf("%d items, %zu distinct, %zu counters; bound eps*N = %.0f\n", N, exact.size(), cm.counters(), eps * N);
std::printf("largest overestimate %u, items above the bound %d\n", worst, above);
for (std::uint64_t x : {0, 1, 2, 5, 12345}) std::printf("item %5llu: true %6u, estimate %6u\n",
static_cast<unsigned long long>(x), exact[x], cm.estimate(x));
}1000000 items, 183593 distinct, 27185 counters; bound eps*N = 500
largest overestimate 103, items above the bound 0
item 0: true 250060, estimate 250141
item 1: true 124432, estimate 124506
item 2: true 62618, estimate 62701
item 5: true 7779, estimate 7865
item 12345: true 2, estimate 83
HyperLogLog: counting distinct elements
How many distinct items does a stream contain? Exactly, that needs space linear in the answer. HyperLogLog (Flajolet, Fusy, Gandouet and Meunier, 2007) estimates it with a relative standard error of about using registers of about 6 bits each: 1.5 KB for 2% error, for billions of items.
The idea. Hash each item to a uniform 64-bit value. Among distinct uniform values, the largest number of leading zeros seen is about : a value starting with zeros and then a 1 has probability . A single maximum is a very noisy estimate, so HyperLogLog splits the hash: the first bits choose one of registers, and the register keeps the maximum of the remaining bits. The registers are averaged with a harmonic mean, which resists outliers:
where corrects a multiplicative bias. For small counts () many registers are still 0, and linear counting, with the number of zero registers, is more accurate. The standard error is an asymptotic analysis result of the paper, assuming ideal hash functions; it is stated here, not proved.
The program implements HyperLogLog with the splitmix64 hash and five different salts (five independent runs), for and .
import math
MASK = (1 << 64) - 1
def mix64(x):
x = (x + 0x9E3779B97F4A7C15) & MASK
x = ((x ^ (x >> 30)) * 0xBF58476D1CE4E5B9) & MASK
x = ((x ^ (x >> 27)) * 0x94D049BB133111EB) & MASK
return x ^ (x >> 31)
class HyperLogLog:
def __init__(self, p, salt=0):
self.p, self.m, self.salt = p, 1 << p, salt
self.M = [0] * self.m # one small register per bucket
def add(self, x):
h = mix64(x ^ self.salt)
j = h >> (64 - self.p) # the top p bits choose the register
rest = h & ((1 << (64 - self.p)) - 1)
rank = (64 - self.p) - rest.bit_length() + 1 # position of the first 1 bit in the rest
if rank > self.M[j]: self.M[j] = rank
def estimate(self):
m = self.m
alpha = {16: 0.673, 32: 0.697, 64: 0.709}.get(m, 0.7213 / (1 + 1.079 / m)) # bias correction
E = alpha * m * m / sum(2.0 ** -r for r in self.M)
zeros = self.M.count(0)
if E <= 2.5 * m and zeros: # small range: linear counting
E = m * math.log(m / zeros)
return E
for p in [6, 10]:
m = 1 << p
print(f"m = {m} registers ({m * 6} bits); typical error 1.04/sqrt(m) = {1.04 / math.sqrt(m):.1%}")
for n in [100, 1000, 20000]:
errs = []
for salt in range(5): # five independent hash functions
h = HyperLogLog(p, salt * 0x9E3779B97F4A7C15 & MASK)
for x in range(n): h.add(x)
errs.append(h.estimate() / n - 1)
print(f" n = {n:6}: relative errors " + " ".join(f"{e:+6.1%}" for e in errs))m = 64 registers (384 bits); typical error 1.04/sqrt(m) = 13.0%
n = 100: relative errors -18.8% -2.7% +18.8% -15.2% +2.0%
n = 1000: relative errors -1.3% +12.1% +26.6% +14.7% +17.2%
n = 20000: relative errors -13.6% -8.6% +10.5% -0.5% +0.0%
m = 1024 registers (6144 bits); typical error 1.04/sqrt(m) = 3.2%
n = 100: relative errors -5.8% +3.0% +0.8% +3.0% +1.9%
n = 1000: relative errors -1.4% +1.5% +0.7% +2.3% +5.6%
n = 20000: relative errors +1.7% -3.4% +0.3% +0.1% +1.4%
With 64 registers the errors scatter around the predicted 13%; with 1024 they shrink to about 3%, a factor 4 for 16 times the registers, as predicts. The memory is the same for and , and would be for : a register needs only bits to hold a value around , which is where the name comes from (it improves on the earlier LogLog algorithm of Durand and Flajolet, 2003).
Two HyperLogLog sketches with the same hash merge by taking the register-wise maximum, giving the sketch of the union. Redis (PFADD, PFCOUNT) uses registers (12 KB, 0.81% standard error), and many analytics databases offer approximate distinct counts based on HyperLogLog.
Space lower bounds, briefly
Both sketches are close to optimal. For distinct counting with relative error , bits are necessary (Alon, Matias and Szegedy, 1996, for the term; Indyk and Woodruff, 2003, for the term), and Kane, Nelson and Woodruff (2010) gave an algorithm with optimal space bits. For point frequency queries with additive error , counters are necessary, which count-min achieves up to the factor for the failure probability.
| Sketch | Query | Error | Space |
|---|---|---|---|
| count-min | frequency of | with probability , never below | counters |
| HyperLogLog | number of distinct items | relative standard error | registers of bits |
| Bloom filter | is in the set? | false positives, rate | bits per element |
Test yourself
Why does the count-min sketch never underestimate a frequency (with only insertions)?
- Because it stores exact counts
- Because every counter that maps to holds plus non-negative contributions of colliding items, and the minimum of such values is still at least
- Because the hash functions are pairwise independent
- Because
With , what is the probability that one row of a count-min sketch overestimates by more than ?
- At most
- At most , by Markov's inequality, since the expected excess is at most
- At most
- At most
HyperLogLog with registers has a relative standard error of about . How many registers are needed for about 1% error?
- About 100
- About , since gives
- About
- It depends on