TExcelTAD
Home › Advanced & Succinct Data Structures › Count-Min Sketch and HyperLogLog

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 x1,x2,…x_1, x_2, \ldots defines a frequency vector ff, with fxf_x the number of occurrences of xx, and ∥f∥1=N\lVert f \rVert_1 = N the stream length. The count-min sketch (Cormode and Muthukrishnan, 2005) is a d×wd \times w array of counters and dd hash functions h1,…,hdh_1, \ldots, h_d into {0,…,w−1}\{0, \ldots, w - 1\}, drawn from a pairwise independent family.

  • UPDATE(x)(x): for every row jj, increment C[j][hj(x)]C[j][h_j(x)].
  • ESTIMATE(x)(x): f^x=min⁡jC[j][hj(x)]\hat{f}_x = \min_j C[j][h_j(x)].

Theorem. With w=⌈e/ε⌉w = \lceil e / \varepsilon \rceil and d=⌈ln⁡(1/δ)⌉d = \lceil \ln(1/\delta) \rceil, for every item xx: f^x≥fx\hat{f}_x \ge f_x always, and f^x≤fx+εN\hat{f}_x \le f_x + \varepsilon N with probability at least 1−δ1 - \delta. The space is O(1εlg⁡1δ)O(\frac{1}{\varepsilon} \lg \frac{1}{\delta}) counters, independent of the number of distinct items.

Proof. Each counter C[j][hj(x)]C[j][h_j(x)] holds fxf_x plus the counts of the other items hashed to the same cell, so it never underestimates. The excess XjX_j has expectation ∑y≠xfyPr⁡[hj(y)=hj(x)]≤N/w≤εN/e\sum_{y \ne x} f_y \Pr[h_j(y) = h_j(x)] \le N / w \le \varepsilon N / e by pairwise independence. By Markov's inequality, Pr⁡[Xj>εN]≤1/e\Pr[X_j > \varepsilon N] \le 1/e. The rows use independent hash functions, so all dd rows exceed εN\varepsilon N with probability at most e−d≤δe^{-d} \le \delta, and the minimum is then the only way to be wrong.

python · try it yourself
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 εN\varepsilon N is tiny next to 13850 and huge next to 9. That is the intended use: finding heavy hitters (items with fx≥ϕNf_x \ge \phi N) 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  mod (261−1)\bmod (2^{61} - 1) hashing, on a million-item stream in which item kk has probability about 2−(k+2)2^{-(k+2)} for small kk, mixed with uniform items.

cpp · try it yourself
#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 1.04/m1.04 / \sqrt{m} using mm 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 nn distinct uniform values, the largest number of leading zeros seen is about lg⁡n\lg n: a value starting with ρ−1\rho - 1 zeros and then a 1 has probability 2−ρ2^{-\rho}. A single maximum is a very noisy estimate, so HyperLogLog splits the hash: the first pp bits choose one of m=2pm = 2^p registers, and the register keeps the maximum ρ\rho of the remaining bits. The registers are averaged with a harmonic mean, which resists outliers:

E=αm m2(∑j=1m2−Mj)−1,αm≈0.7213/(1+1.079/m)E = \alpha_m \, m^2 \left( \sum_{j=1}^{m} 2^{-M_j} \right)^{-1}, \qquad \alpha_m \approx 0.7213 / (1 + 1.079/m)

where αm\alpha_m corrects a multiplicative bias. For small counts (E≤52mE \le \frac{5}{2} m) many registers are still 0, and linear counting, mln⁡(m/V)m \ln(m / V) with VV the number of zero registers, is more accurate. The standard error 1.04/m1.04/\sqrt{m} is an asymptotic analysis result of the paper, assuming ideal hash functions; it is stated here, not proved.

32 registers (largest rank seen per register)88119911567121157681011559811675678975602000300002000true distinct countestimatedotted line: exact count

The program implements HyperLogLog with the splitmix64 hash and five different salts (five independent runs), for m=64m = 64 and m=1024m = 1024.

python · try it yourself
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 1/m1/\sqrt{m} predicts. The memory is the same for n=100n = 100 and n=20000n = 20000, and would be for n=1010n = 10^{10}: a register needs only lg⁡lg⁡n\lg \lg n bits to hold a value around lg⁡n\lg n, 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 m=214m = 2^{14} 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 ε\varepsilon, Ω(1/ε2+lg⁡n)\Omega(1/\varepsilon^2 + \lg n) bits are necessary (Alon, Matias and Szegedy, 1996, for the lg⁡n\lg n term; Indyk and Woodruff, 2003, for the 1/ε21/\varepsilon^2 term), and Kane, Nelson and Woodruff (2010) gave an algorithm with optimal space O(1/ε2+lg⁡n)O(1/\varepsilon^2 + \lg n) bits. For point frequency queries with additive error εN\varepsilon N, Ω(1/ε)\Omega(1/\varepsilon) counters are necessary, which count-min achieves up to the lg⁡(1/δ)\lg(1/\delta) factor for the failure probability.

Sketch Query Error Space
count-min frequency of xx +εN+\varepsilon N with probability 1−δ1 - \delta, never below O(1εlg⁡1δ)O(\frac{1}{\varepsilon} \lg \frac{1}{\delta}) counters
HyperLogLog number of distinct items relative standard error ≈1.04/m\approx 1.04/\sqrt{m} mm registers of O(lg⁡lg⁡n)O(\lg \lg n) bits
Bloom filter is xx in the set? false positives, rate ε\varepsilon 1.44lg⁡(1/ε)1.44 \lg(1/\varepsilon) bits per element

Test yourself

Why does the count-min sketch never underestimate a frequency (with only insertions)?

  1. Because it stores exact counts
  2. Because every counter that xx maps to holds fxf_x plus non-negative contributions of colliding items, and the minimum of such values is still at least fxf_x
  3. Because the hash functions are pairwise independent
  4. Because d≥1d \ge 1

With w=⌈e/ε⌉w = \lceil e/\varepsilon \rceil, what is the probability that one row of a count-min sketch overestimates by more than εN\varepsilon N?

  1. At most ε\varepsilon
  2. At most 1/e1/e, by Markov's inequality, since the expected excess is at most N/wN/w
  3. At most δ\delta
  4. At most 1/21/2

HyperLogLog with mm registers has a relative standard error of about 1.04/m1.04/\sqrt{m}. How many registers are needed for about 1% error?

  1. About 100
  2. About 10410^4, since 1.04/m=0.011.04/\sqrt{m} = 0.01 gives m≈10816m \approx 10816
  3. About 10610^6
  4. It depends on nn