HyperLogLog: Analysis and Bias Corrections
Count-Min Sketch and HyperLogLog introduced HyperLogLog (Flajolet, Fusy, Gandouet and Meunier, 2007) as a data structure: registers, each holding the largest "rank" (position of the first 1 bit) among the hashes routed to it, combined by a harmonic mean, with linear counting for small cardinalities. This lesson explains where its constants come from. The two numbers to understand are the bias constant and the standard error ; both drop out of the distribution of a single register. Then come the bias corrections that practical implementations add, and the place of HyperLogLog among the distinct-count sketches.
The estimator, once more
With index bits and registers, an item's 64-bit hash sends it to register (the top bits) and gives it the rank , one plus the number of leading zeros of the remaining bits. Register keeps the maximum rank seen. The estimate is
Each is a rough estimate of the number of distinct items routed to register , about . The harmonic mean of these rough estimates, times , estimates , and removes a multiplicative bias. Its predecessor, LogLog (Durand and Flajolet, 2003), used the geometric mean instead, . The harmonic mean is less sensitive to the occasional register with a very large value, which is why HyperLogLog's error constant is rather than LogLog's .
The analysis, sketched
The full analysis (Flajolet et al., 2007) uses Mellin transforms and is long; its core is easy to reproduce. Two simplifications make each register tractable.
- Ideal hashing. Ranks are independent with .
- Poissonization. Pretend the number of items in each register is Poisson with mean , independently across registers (the real counts are multinomial; for large the difference vanishes, which the paper proves).
Under these assumptions a register is at most exactly when none of its items has rank above , and items with rank above arrive as a Poisson process of rate , so
From this law, two quantities decide everything. If , then and the estimate is unbiased for . The relative variance of is , and to first order the reciprocal has the same relative error. The program computes both from the register law.
import math
def register_law(lam, kmax=90):
"""Poissonized register: lam items on average; P[M <= k] = exp(-lam * 2^-k)."""
probs, prev = [], 0.0
for k in range(kmax):
cur = math.exp(-lam * 2.0 ** -k)
probs.append(cur - prev)
prev = cur
return probs
print(" lam = n/m lam * E[2^-M] Var[2^-M]/E[2^-M]^2 E[M] - log2(lam)")
for lam in [10, 100, 1000, 10**4, 10**5]:
P = register_law(lam)
E1 = sum(p * 2.0 ** -k for k, p in enumerate(P))
E2 = sum(p * 4.0 ** -k for k, p in enumerate(P))
EM = sum(p * k for k, p in enumerate(P))
print(f"{lam:11} {lam * E1:13.5f} {E2 / E1 ** 2 - 1:19.5f} {EM - math.log2(lam):16.5f}")
print(f"limits: 1/(2 ln 2) = {1 / (2 * math.log(2)):.5f}, 3 ln 2 - 1 = {3 * math.log(2) - 1:.5f}, "
f"sqrt(3 ln 2 - 1) = {math.sqrt(3 * math.log(2) - 1):.4f}") lam = n/m lam * E[2^-M] Var[2^-M]/E[2^-M]^2 E[M] - log2(lam)
10 0.72134 1.07951 1.33275
100 0.72135 1.07925 1.33274
1000 0.72135 1.07954 1.33275
10000 0.72134 1.07954 1.33275
100000 0.72135 1.07926 1.33274
limits: 1/(2 ln 2) = 0.72135, 3 ln 2 - 1 = 1.07944, sqrt(3 ln 2 - 1) = 1.0390
So , which is , and the relative variance of tends to , which gives the standard error
(The tiny wobble in the fifth digit is real: these quantities oscillate with with an amplitude of about , a famous feature of the analysis that is far below the statistical error.) The last column gives LogLog's constant the same way: , so the geometric-mean estimator needs . The finite- correction accounts for the bias of taking a reciprocal of a random sum and is fitted in the paper.
Theorem (Flajolet, Fusy, Gandouet and Meunier, 2007; stated). Under the ideal-hash assumption, for the estimate is asymptotically unbiased as , apart from the oscillation mentioned, and its relative standard error is with .
The program measures both estimators at with 20 different hash functions.
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)
n, runs = 20000, 20
err = {(name, p): [] for name in ["LogLog", "HyperLogLog"] for p in [6, 8]}
for s in range(runs):
hashes = [mix64(x ^ (s * 0x9E3779B97F4A7C15 & MASK)) for x in range(n)]
for p in [6, 8]:
m = 1 << p
M = [0] * m
for h in hashes:
j, rest = h >> (64 - p), h & ((1 << (64 - p)) - 1)
r = 64 - p - rest.bit_length() + 1
if r > M[j]:
M[j] = r
loglog = 0.39701 * m * 2 ** (sum(M) / m) # geometric mean (Durand-Flajolet)
hyper = 0.7213 / (1 + 1.079 / m) * m * m / sum(2.0 ** -r for r in M) # harmonic mean
err[("LogLog", p)].append(loglog / n - 1)
err[("HyperLogLog", p)].append(hyper / n - 1)
for (name, p), e in err.items():
m = 1 << p
c = 1.30 if name == "LogLog" else 1.04
rms = math.sqrt(sum(v * v for v in e) / len(e))
print(f"{name:11} m = {m:3}: rms error {rms:.3f} theory {c:.2f}/sqrt(m) = {c / math.sqrt(m):.3f}")LogLog m = 64: rms error 0.216 theory 1.30/sqrt(m) = 0.163
LogLog m = 256: rms error 0.075 theory 1.30/sqrt(m) = 0.081
HyperLogLog m = 64: rms error 0.133 theory 1.04/sqrt(m) = 0.130
HyperLogLog m = 256: rms error 0.066 theory 1.04/sqrt(m) = 0.065
Small cardinalities and the bias corrections
The asymptotic analysis says nothing about small . When is not much larger than , many registers are still 0, each contributes to the sum, and the raw estimate is far too large: with it is , not 0. The original paper therefore switches to linear counting (Whang, Vander-Zanden and Taylor, 1990) when : with empty registers out of , the estimate comes from , the fraction of empty bins after random balls. The program measures the bias and error of both for over a range of .
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)
def registers(n, p, salt):
M = [0] * (1 << p)
for x in range(n):
h = mix64(x ^ salt)
j, rest = h >> (64 - p), h & ((1 << (64 - p)) - 1)
r = 64 - p - rest.bit_length() + 1
if r > M[j]:
M[j] = r
return M
def raw_hll(M):
m = len(M)
return 0.7213 / (1 + 1.079 / m) * m * m / sum(2.0 ** -r for r in M)
def hll(M):
m, E = len(M), raw_hll(M)
zeros = M.count(0)
return m * math.log(m / zeros) if E <= 2.5 * m and zeros else E
p, runs = 8, 25
m = 1 << p
print(f"m = {m} registers, {runs} runs per n; mean relative error (bias) and rms error")
print(" n raw bias raw rms corrected bias corrected rms")
for n in [50, 200, 400, 640, 800, 1500, 4000, 6000]:
raw, cor = [], []
for s in range(runs):
M = registers(n, p, s * 0x9E3779B97F4A7C15 & MASK)
raw.append(raw_hll(M) / n - 1)
cor.append(hll(M) / n - 1)
rms = lambda e: math.sqrt(sum(v * v for v in e) / len(e))
print(f"{n:6} {sum(raw) / runs:+8.3f} {rms(raw):7.3f} {sum(cor) / runs:+14.3f} {rms(cor):13.3f}")
print(f"switch to linear counting while E <= 2.5 m = {2.5 * m:.0f}; theory rms 1.04/sqrt(m) = {1.04 / math.sqrt(m):.3f}")m = 256 registers, 25 runs per n; mean relative error (bias) and rms error
n raw bias raw rms corrected bias corrected rms
50 +3.178 3.178 +0.006 0.043
200 +0.480 0.481 -0.003 0.058
400 +0.121 0.128 +0.019 0.057
640 +0.038 0.065 +0.040 0.068
800 +0.009 0.061 +0.009 0.061
1500 +0.012 0.063 +0.012 0.063
4000 +0.014 0.073 +0.014 0.073
6000 -0.006 0.076 -0.006 0.076
switch to linear counting while E <= 2.5 m = 640; theory rms 1.04/sqrt(m) = 0.065
The raw estimate is useless below a few times (a bias of +318% at ), linear counting is excellent there, and above the switch the two coincide. Right at the switch, around , a small bias remains (+4% here), because neither estimator is accurate in the transition. Practical implementations go further:
- HyperLogLog++ (Heule, Nunkesser and Hall, 2013, at Google) uses a 64-bit hash, which removes the original paper's large-range correction for 32-bit hashes, subtracts an empirically measured bias for (tables interpolated by nearest neighbours), chooses between linear counting and the corrected estimate by a per-precision threshold, and stores registers sparsely (a list of (index, rank) pairs) while few are non-zero, so a sketch of a small set costs little memory.
- Improved estimators (Ertl, 2017) derive an estimator from the register histogram that is accurate over the whole range without empirical tables, and maximum-likelihood estimators reach slightly lower variance.
Space
Each register holds a rank of at most , so it needs bits, 6 bits for any realistic : hence the name. For relative error the total is bits. The optimal bound is bits, reached by Kane, Nelson and Woodruff (2010) with a more complex algorithm; HyperLogLog's extra factor is the price of its simplicity, and nobody pays it reluctantly: registers, 12 KiB, give 0.81% error for any up to .
In C++
HyperLogLog with (4096 one-byte registers), std::countl_zero for the rank, linear counting for small sets, and the register-wise maximum to merge two sites' sketches.
#include <algorithm>
#include <bit>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <vector>
std::uint64_t mix64(std::uint64_t x) {
x += 0x9E3779B97F4A7C15ULL;
x = (x ^ (x >> 30)) * 0xBF58476D1CE4E5B9ULL;
x = (x ^ (x >> 27)) * 0x94D049BB133111EBULL;
return x ^ (x >> 31);
}
class HyperLogLog {
int p;
std::vector<std::uint8_t> M; // one byte per register (6 bits would do)
public:
explicit HyperLogLog(int p) : p(p), M(std::size_t(1) << p, 0) {}
void add(std::uint64_t x) {
std::uint64_t h = mix64(x);
std::size_t j = h >> (64 - p); // top p bits pick the register
std::uint64_t rest = h << p; // the other 64 - p bits, left-aligned
int rank = rest ? std::countl_zero(rest) + 1 : 64 - p + 1;
M[j] = std::max<std::uint8_t>(M[j], rank);
}
void merge(const HyperLogLog& o) { for (std::size_t j = 0; j < M.size(); ++j) M[j] = std::max(M[j], o.M[j]); }
double estimate() const {
double m = double(M.size()), sum = 0;
int zeros = 0;
for (auto r : M) { sum += std::ldexp(1.0, -r); zeros += r == 0; }
double E = 0.7213 / (1 + 1.079 / m) * m * m / sum;
if (E <= 2.5 * m && zeros) E = m * std::log(m / zeros); // linear counting for small n
return E;
}
};
int main() {
HyperLogLog a(12), b(12); // 4096 registers: 1.04/64 = 1.6%
for (std::uint64_t x = 0; x < 600000; ++x) a.add(x); // site A: users 0 .. 599 999
for (std::uint64_t x = 400000; x < 1000000; ++x) b.add(x); // site B: users 400 000 .. 999 999
std::printf("A: %.0f (true 600000)\nB: %.0f (true 600000)\n", a.estimate(), b.estimate());
a.merge(b);
std::printf("A or B after merging: %.0f (true 1000000)\n", a.estimate());
HyperLogLog tiny(12);
for (std::uint64_t x = 0; x < 1000; ++x) tiny.add(x);
std::printf("1000 items, linear counting range: %.0f\n", tiny.estimate());
}A: 617902 (true 600000)
B: 602165 (true 600000)
A or B after merging: 1020719 (true 1000000)
1000 items, linear counting range: 997
The merged sketch estimates the union of the two sites without double counting the 200 000 shared users, which is the property that makes HyperLogLog the default distinct counter of distributed analytics systems.
Test yourself
Where does the constant come from?
- It is fitted to experiments only
- From the register law : , so it makes the harmonic-mean estimator unbiased for large
- From the number of bits per register
- From linear counting
What does the constant in HyperLogLog's standard error come from?
- , the limiting relative standard deviation of for one register
- The ratio of harmonic to geometric mean
- It is the LogLog constant
Why is the raw HyperLogLog estimate badly biased for small ?
- Because the hash function collides
- Because empty registers each contribute to the sum, so the estimate stays near even for tiny ; linear counting on the number of empty registers is used instead
- Because is too large
- Because registers overflow
How many bits does a HyperLogLog register need for streams of up to distinct items?
- 64
- 6, since the rank is at most about 65
- 1