Sub topic 2
Hashing and collisions refresher
This chapter reviews the hashing ideas that the count-min sketch builds on. It covers what a hash function does, why collisions cannot be avoided, how often they happen, and how to get a hash function that behaves the same in every process. The sketch itself comes in the next chapter.
I assume you know basic Python, have seen hash tables, and can compute an expected value. If "the expected number of heads in 10 fair flips is 5" is clear to you, the probability here will be too.
What a hash function does
A hash function maps an input of any size, such as a string, a number, or a tuple, to a fixed-size integer. Three properties matter for sketches.
- Deterministic. The same input always gives the same output. A sketch relies on this because it must find the same counters when it adds an item and later when it asks about that item.
- Spread out. Different inputs should produce outputs that look random and cover the range evenly.
- Cheap. Every item in the stream is hashed several times, so the function must be fast.
To use a hash as a counter position, you shrink it into a range of w slots with the modulo operator:
column = hash_value % wThe result is an integer from 0 to w - 1. The sketch will use w as its number of columns. Here w is simply the number of slots, which we also call buckets.
Collisions are unavoidable
A collision happens when two different items map to the same bucket. If you have more possible items than buckets, collisions must happen, by the pigeonhole principle. A stream of search queries can contain billions of distinct strings. A sketch might have a few thousand columns. Many items will share each column.
In an ordinary hash table, collisions are handled by storing the colliding items together, for example in a linked list or by probing for another slot, so you can still tell them apart. A sketch does not store items at all. It stores only counters. When two items share a counter, the counter holds the sum of their counts, and nothing records which part belongs to which item. This is the source of the sketch's error, and the rest of the tutorial is about controlling it.
How likely is a collision?
Assume the hash spreads items uniformly, so each item lands in each of the w buckets with probability 1/w, independently of other items. Then a collision with a specific item is rare, but a collision somewhere is common.
Take one particular item x and n - 1 other distinct items. Each other item lands in x's bucket with probability 1/w. By linearity of expectation, the expected number of other items sharing x's bucket is:
(n - 1) / wThis number is the core of the later error analysis. It grows with the number of items and shrinks as you add buckets. Doubling w halves the expected crowding.
The chance that any two items collide is much larger than people expect. This is the birthday problem. The probability that n items all land in different buckets is the product of (w - i) / w for i from 0 to n - 1.
def collision_probability(n, w):
"""Probability that at least two of n items share a bucket."""
p_none = 1.0
for i in range(n):
p_none *= (w - i) / w
return 1 - p_none
for n in [5, 10, 23, 40]:
print(n, round(collision_probability(n, 365), 3))This prints 0.027, 0.117, 0.507, and 0.891. With only 23 items in 365 buckets, a collision is more likely than not. The number of colliding pairs grows roughly with n², and each pair collides with probability 1/w, so the expected number of colliding pairs is n(n - 1) / (2w).
Load: how items spread over buckets
If n items go into w buckets, the average load is n / w items per bucket. Real loads vary around that average, and the fullest bucket holds noticeably more than the average. You can check this with a simulation. First we need a hash function that gives the same answer every time.
A stable hash function
Python's built-in hash() is convenient, but it has two properties that matter here.
- For strings and bytes, the value is randomized per process unless the environment variable
PYTHONHASHSEEDis fixed. The same string hashes differently in two runs. - For integers,
hash(n)is justnreduced modulo 2^61 - 1 (for non-negative values), so it adds no mixing.
Within one process, built-in hash() is fine. If sketches are saved to disk, sent to another machine, or merged later, you need a hash that does not change between processes. A cryptographic digest from hashlib works, at some cost in speed.
import hashlib
def stable_hash(item):
"""A 64-bit hash that is the same in every process and on every machine."""
data = str(item).encode("utf-8")
return int.from_bytes(hashlib.sha256(data).digest()[:8], "big")
for word in ["apple", "banana", "cherry"]:
print(word, stable_hash(word) % 10)Run this twice, or on two computers, and you get the same buckets each time. Run the same loop with hash(word) % 10 and the buckets will change between runs.
Measuring the spread
This simulation hashes 1,000 distinct keys into 100 buckets and reports the load.
import hashlib
from collections import Counter
def stable_hash(item):
data = str(item).encode("utf-8")
return int.from_bytes(hashlib.sha256(data).digest()[:8], "big")
def bucket_loads(items, w):
loads = Counter()
for item in items:
loads[stable_hash(item) % w] += 1
return loads
w = 100
n = 1000
loads = bucket_loads((f"user-{i}" for i in range(n)), w)
print("average load:", n / w)
print("max load:", max(loads.values()))
print("empty buckets:", w - len(loads))The average load prints as 10.0. The maximum load is clearly higher than 10, while a few buckets may be much emptier than average. The exact numbers depend on the keys, but the pattern is stable: a good hash makes the loads cluster around the average, with natural random variation.
A note on the modulo step. If the hash range is not an exact multiple of w, some buckets receive slightly more hash values than others. With a 64-bit hash and a small w, the bias is far too small to matter.
Hash families: one function per row
The sketch needs several different hash functions, one for each row of counters. You get them from a hash family, which is a set of functions indexed by random parameters. A standard choice is:
h(x) = ((a * x + b) mod p) mod wHere p is a prime larger than any input, a is chosen at random from 1 to p - 1, and b from 0 to p - 1. Each (a, b) pair gives a different function. The next chapters use p = 2^61 - 1. The later chapter on pairwise independence explains why this family has good guarantees. For now, treat it as a way to produce many unrelated-looking functions from one stable hash.
The key effect is that two items that collide under one function usually do not collide under another. This experiment measures it with two rows:
import random
p = (1 << 61) - 1
w = 10
rng = random.Random(42)
rows = [(rng.randrange(1, p), rng.randrange(0, p)) for _ in range(2)]
def h(params, x):
a, b = params
return ((a * x + b) % p) % w
trials = 20000
one_row = 0
both_rows = 0
for _ in range(trials):
x = rng.randrange(p)
y = rng.randrange(p)
if x == y:
continue
hits = [h(params, x) == h(params, y) for params in rows]
one_row += hits[0]
both_rows += all(hits)
print("collide in row 0:", one_row / trials) # close to 1/w = 0.1
print("collide in both rows:", both_rows / trials) # close to 0.01A pair collides in one row about 10% of the time, which is 1/w. It collides in both rows about 1% of the time, which is (1/w)². Each extra row cuts the chance of an unlucky pair by another factor of w. This is the reason the sketch uses several rows.
To hash a string with this family, first convert it to an integer with a stable hash, then reduce it with x = stable_hash(item) % p before applying h.
What a good hash needs for a sketch
| Property | Why the sketch needs it | What goes wrong without it |
|---|---|---|
| Deterministic | Add and query must reach the same counters | Estimates lose all meaning |
| Stable across processes | Saved or merged sketches must agree | Merged tables mix unrelated counters |
| Uniform spread | Keeps expected crowding near `n / w` | Some columns overflow with counts |
| Different function per row | Lets rows disagree about collisions | All rows repeat the same error |
| Fast | Runs `d` times per stream item | Throughput drops |
What to carry forward
- A collision means two different items share a counter. In a sketch the counter holds only their sum, so the colliding counts cannot be separated.
- With uniform hashing, the expected number of other items in a given item's bucket is
(n - 1) / w. - Collisions are common even when
nis much smaller thanw. - Use a stable hash if a sketch ever leaves its process.
- Rows use independent functions from a family such as
((a * x + b) mod p) mod w, so a pair that collides in one row rarely collides in all of them.
Exercise
You hash 2,001 distinct items uniformly into w = 500 buckets. (a) What is the expected number of other items that share bucket with one particular item? (b) Your colleague builds a sketch in one process using Python's built-in hash() on strings and sends its table to a second process to merge. What goes wrong, and what is a fix?
Show answer
(a) (n - 1) / w = 2000 / 500 = 4 other items on average. (b) Built-in hash() on strings is randomized per process, so the two processes place the same string in different columns. Adding the tables cell by cell then mixes counts of unrelated items. Fix it by using a stable hash such as a hashlib digest, or by setting PYTHONHASHSEED identically in both processes.
Exercise
Two items collide under a random hash function from a family with w = 20 columns with probability 1/20 in a single row. If the sketch has 3 rows that use independent functions, what is the probability that the two items collide in all 3 rows?
Show answer
Independence lets you multiply: (1/20)^3 = 1/8000, or 0.000125.