Sub topic 9
Building a HyperLogLog Sketch in Python
This chapter assumes you know basic Python, bitwise operations on integers, what a hash function does, and the earlier chapters' ideas: rank, registers, the harmonic mean and linear counting. Here you assemble those pieces into one working class.
The plan for the class
The sketch needs three operations and one array:
add(item)hashes the item and updates one register.estimate()turns the registers into a count.merge(other)combines two sketches.registersis a list ofm = 2**psmall integers, each starting at 0.
The full class
import hashlib
import math
class HyperLogLog:
def __init__(self, p=12):
if not 4 <= p <= 16:
raise ValueError("p must be between 4 and 16")
self.p = p
self.m = 1 << p
self.registers = [0] * self.m
if self.m == 16:
self.alpha = 0.673
elif self.m == 32:
self.alpha = 0.697
elif self.m == 64:
self.alpha = 0.709
else:
self.alpha = 0.7213 / (1 + 1.079 / self.m)
@staticmethod
def _hash64(item):
digest = hashlib.sha1(item.encode("utf-8")).digest()
return int.from_bytes(digest[:8], "big")
def add(self, item):
x = self._hash64(item)
bits = 64 - self.p
index = x >> bits # first p bits choose the register
rest = x & ((1 << bits) - 1) # remaining bits give the rank
rank = bits - rest.bit_length() + 1 # position of the first 1-bit
if rank > self.registers[index]:
self.registers[index] = rank
def estimate(self):
raw = self.alpha * self.m * self.m / sum(2.0 ** -r for r in self.registers)
zeros = self.registers.count(0)
if raw <= 2.5 * self.m and zeros:
return self.m * math.log(self.m / zeros) # linear counting
return raw
def merge(self, other):
if self.p != other.p:
raise ValueError("precision must match")
self.registers = [max(a, b) for a, b in zip(self.registers, other.registers)]How each part works
Hashing
_hash64 uses SHA-1 and keeps the first 8 bytes as a 64-bit integer. The hash must be deterministic and well mixed. Python's built-in hash() is a poor choice, because string hashes change between runs, so a saved sketch would be meaningless in a new process.
Splitting the hash
With p = 12, the top 12 bits of the hash select one of 4096 registers. The remaining 52 bits supply the rank. Shifting right by 64 - p leaves only the top bits. Masking with (1 << bits) - 1 keeps only the low bits.
Computing the rank
The rank is the position of the first 1-bit, counted from the left of the 52-bit remainder. bit_length() gives the position of the highest set bit counted from the right, so bits - bit_length() + 1 converts it. If rest is 0, the rank is bits + 1, the largest possible value.
Estimating
The raw estimate is alpha * m * m / sum(2 ** -r). Each register contributes 2 ** -r, which is the harmonic mean at work. If the raw value is at most 2.5 * m and some registers are still zero, the code uses linear counting, m * ln(m / zeros). Without that fallback, small counts would be overestimated.
Merging
Taking the maximum per register gives the same registers you would get by feeding both streams into one sketch. That is why merging counts the union and why overlapping items are not double-counted.
Trying it
import math
a = HyperLogLog(p=12)
b = HyperLogLog(p=12)
for i in range(100_000):
a.add(f"user-{i}")
for i in range(50_000, 150_000):
b.add(f"user-{i}")
print(round(a.estimate())) # close to 100000
print(round(b.estimate())) # close to 100000
a.merge(b)
print(round(a.estimate())) # close to 150000, the size of the union
print(f"standard error: {1.04 / math.sqrt(a.m):.2%}") # about 1.63% for p=12Run this snippet after the class definition. Each estimate typically lands within a few percent of the true value. The 1.63% figure is a standard error, so an occasional result a little further off is normal.
Common errors
- Forgetting the
+ 1in the rank. Ranks then start at 0 for a leading 1-bit, which breaks the estimator. - Taking the index from the low bits and the rank from the high bits. This works only if both parts are independent. Keep the split consistent and never reuse bits.
- Merging sketches with different
p. The registers have different meanings, so the class raises an error. - Merging sketches built with different hash functions. The code cannot detect this. The result is silently wrong.
- Expecting exact small counts. A sketch with a handful of items is approximate. Use a plain
setwhen the count is small enough to store exactly.
Exercise
A sketch with p = 10 receives 5,000 distinct items. What is m, what is the standard error, and which estimator branch is likely used?
Show answer
m = 2*10 = 1024. The standard error is 1.04 / sqrt(1024) = 1.04 / 32 = 3.25%. The branch threshold is 2.5 1024 = 2560. With 5,000 items, the raw estimate is about 5,000, which is above 2560, so the raw harmonic-mean estimate is used and linear counting is skipped.
Exercise
Why does merge use max instead of adding the registers?
Show answer
A register stores the largest rank seen, not a count. The union of two streams has a largest rank equal to the larger of the two, so max reproduces what one sketch would hold after seeing both streams. Addition would give ranks that no item produced.