Sub topic 8
Choosing Hash Functions: Pairwise Independence
Prerequisites
This chapter assumes you know the following:
- How the count-min sketch works:
drows,wcolumns, and the minimum across rows as the estimate. - Basic probability, including expected value and linearity of expectation.
- Modular arithmetic.
The Markov-inequality proof comes in the next chapter. Here we only establish what the hashes must guarantee so that proof works.
What the sketch needs from its hashes
The error guarantee depends on one property. For two different items x and y, the chance that a row's hash sends both to the same column must be at most 1/w. Each row also needs its own hash function, drawn independently of the other rows.
The sketch does not need a hash that looks random on every input. It needs a random choice of function from a family, so that no fixed pair of items is systematically unlucky.
A fixed function breaks this. Take h(x) = x mod w with w = 10. Items 5 and 15 collide in every row, on every run. The guarantee is a statement about the random choice of function, and a fixed function gives it nothing to work with.
Pairwise independence
Let H be a family of functions from items to columns {0, ..., w-1}. Pick h from H uniformly at random. The family is pairwise independent (also called strongly 2-universal) if, for any two distinct items x and y and any columns i and j:
Pr[h(x) = i and h(y) = j] = 1/w²
Each item alone is uniform over the columns. Knowing where x landed tells you nothing about where y landed. Summing over i = j gives Pr[h(x) = h(y)] = 1/w.
The analysis needs only the collision bound. A family with Pr[h(x) = h(y)] ≤ 1/w for all x ≠ y is called universal. Pairwise independence is stronger than required, but it is the standard name for the property and the standard family achieves it nearly exactly.
The Carter-Wegman family
The sketch from earlier chapters uses this family:
h_{a,b}(x) = ((a·x + b) mod p) mod w
Here p is a prime larger than any item value, a is drawn from 1..p-1, and b is drawn from 0..p-1.
The reason it works has two steps:
- For
x ≠ y(both belowp) anda ≠ 0, the map from(a, b)to(ax+b mod p, ay+b mod p)is a bijection onto all ordered pairs of distinct values in0..p-1. So the two intermediate values are uniform over distinct pairs. - Reducing mod
wmakes two distinct values collide only if they are congruent modw. For each first value, at most(p-1)/wother values are congruent to it. So the collision probability is at most((p-1)/w) / (p-1) = 1/w.
Because p is usually not a multiple of w, the final mod w is very slightly non-uniform. The family is therefore universal, and its joint probabilities are only close to 1/w². The collision bound is what the proof uses, so this does not matter.
Two details deserve care:
a = 0is excluded. It would make every item map to columnb mod w.- The prime
pmust exceed every pre-hashed item value. A Mersenne prime such as2^61 - 1is convenient, andwitself need not be prime.
From items to integers
The family hashes integers, but real items are strings, tuples, or records. You need a pre-hash that turns an item into an integer below p. If two distinct items get the same pre-hash value, they collide in every row, and no choice of (a, b) can separate them.
Python's built-in hash() has two problems here:
- For strings, it is salted per process (see
PYTHONHASHSEED), so two processes disagree on the same string. Sketches built in different processes cannot then be merged or saved and reloaded. - Small integers hash to themselves, which is fine, but you should not rely on this behavior for other types.
A 64-bit digest from hashlib is stable across machines and runs. With 64 bits, the chance of any pre-hash collision among a million distinct items is around 3 × 10⁻⁸.
Checking the properties empirically
The following script estimates the collision rates for two fixed items over many random draws of the hash parameters. It compares independent rows against rows that wrongly share one (a, b) pair.
import hashlib
import random
P = (1 << 61) - 1 # Mersenne prime, larger than every pre-hash value
def stable_int(item):
data = repr(item).encode("utf-8")
digest = hashlib.blake2b(data, digest_size=8).digest()
return int.from_bytes(digest, "big") % P
def draw_params(rng, d):
return [(rng.randrange(1, P), rng.randrange(0, P)) for _ in range(d)]
def cols(params, w, x):
return [((a * x + b) % P) % w for a, b in params]
def collides_in_all_rows(params, w, x, y):
return all(cx == cy for cx, cy in zip(cols(params, w, x), cols(params, w, y)))
def collision_rates(w, d, trials, seed=1):
rng = random.Random(seed)
x, y = stable_int("apple"), stable_int("banana")
one_row = all_rows = shared_rows = 0
for _ in range(trials):
params = draw_params(rng, d)
one_row += collides_in_all_rows(params[:1], w, x, y)
all_rows += collides_in_all_rows(params, w, x, y)
shared_rows += collides_in_all_rows([params[0]] * d, w, x, y)
return one_row / trials, all_rows / trials, shared_rows / trials
one, indep, shared = collision_rates(w=10, d=3, trials=100_000)
print("single row: ", one) # close to 1/10 = 0.1
print("3 independent rows: ", indep) # close to (1/10)**3 = 0.001
print("3 rows, shared (a,b):", shared) # close to 0.1, no better than one rowThe expected output is about 0.1, about 0.001, and about 0.1. Exact digits vary with the seed.
The independent-rows result shows why d rows help. The probability that two items collide in all rows falls as (1/w)^d. With shared parameters, all rows are the same row, and the minimum across rows is no better than a single row.
Why pairwise is enough
The overcount for an item x in one row is the total frequency of every other item that lands in x's column:
overcount = sum over y ≠ x of f_y · [h(y) = h(x)]
Take the expectation. By linearity of expectation, it equals sum f_y · Pr[h(y) = h(x)]. Each term involves only the pair (x, y), so only the pairwise collision probability matters. The behavior of three or more items together never enters. With Pr ≤ 1/w, the expected overcount is at most N/w, where N is the total stream length. The next chapter turns this bound into a probability statement with Markov's inequality.
This is why a cheap two-parameter family is adequate. Fully random hash functions would need far more storage and would not improve the guarantee.
Practical options
| Option | Guarantee | Cost | Main concern |
|---|---|---|---|
| Carter-Wegman on a stable pre-hash | Universal, proof applies | One multiply, add, and two mods per row | Needs integer pre-hash |
| Built-in `hash()` as pre-hash | Proof applies per process | Cheapest | Unstable across processes, so merging breaks |
| One fast seeded hash (such as murmur or xxhash) with a different seed per row | No formal pairwise guarantee, works well in practice | Fast | Seeds must be stored and shared |
| Double hashing: `h1(x) + i·h2(x)` for row `i` | Rows are not independent, so the proof needs separate analysis | Two hash calls total | Slightly weaker error behavior |
| Cryptographic hash per row | Strong in practice | Slowest | Overkill for most uses |
For a first implementation, use Carter-Wegman on a stable pre-hash. It matches the analysis and is easy to reason about.
Failure modes
- Unstable pre-hash. A sketch saved with salted
hash()values returns wrong estimates after a restart, because the same item now maps to different columns. - Mismatched parameters on merge. Two sketches combine correctly only if they share
w,d,p, and every(a, b)pair. Store the seed or parameters with the sketch. - Predictable parameters. If an adversary knows
(a, b), they can craft items that collide in every row and inflate a target's estimate. For untrusted input, draw parameters from a secret seed. - Items beyond
p. If the pre-hash can exceedp, take it modpfirst. Otherwise two items that agree modpbecome indistinguishable.
Exercises
Exercise
A developer replaces the hash family with the fixed function h(x) = x mod w for every row. Why does adding rows no longer reduce the chance that items x and x + w are confused?
Show answer
The function is the same in every row and has no randomness, so x and x + w always land in the same column in every row. The minimum across rows sees the same inflated counter each time. The (1/w)^d argument needs rows to be independent random draws from a family with collision probability at most 1/w.
Exercise
In the Carter-Wegman family, what goes wrong if a is allowed to be 0?
Show answer
With a = 0, h(x) = (b mod p) mod w for every x. All items map to the same column, so every pair collides with probability 1 instead of at most 1/w.
Exercise
Two servers each build a sketch from their own traffic using Python's built-in hash() on strings, with the same seed for (a, b). Why can't the sketches be merged correctly?
Show answer
String hash() is salted per process, so the two servers compute different integers for the same string. The same item then lands in different columns in each table, and adding the tables cell by cell mixes unrelated counters. A stable pre-hash such as a blake2b digest fixes this.