Estimate Jaccard similarity between documents with MinHash signatures

Why it matters MinHash with locality sensitive hashing is the standard near-duplicate filter for LLM pretraining corpora.

Deduplicating a web-scale training corpus needs a cheap way to tell if two documents share most of their shingles. MinHash compresses each shingle set into K numbers whose agreement rate estimates Jaccard similarity.

Write minhash(sets, a, b, p). sets is a list of N lists of non-negative int shingle ids (a list may be empty). a and b are int arrays of length K and p is a prime larger than every shingle id; hash function k is h_k(x) = (a[k] * x + b[k]) mod p. The signature of a set is, for each k, the MIN of h_k over the set's elements; for an empty set every entry is p.

Return (sig, est): sig is an (N, K) int array, and est is the (N, N) float array where est[i, j] is the fraction of the K positions where sig[i] and sig[j] are equal.

Signaturedef minhash(sets, a, b, p)

Example

minhash([[1, 2], [2, 3]], [1, 3], [0, 1], 7) gives sig [[1, 0], [2, 0]] and est [[1.0, 0.5], [0.5, 1.0]].

Understand the idea

MinHash turns a set into a short signature. Pick a random hash function, hash every element, and keep the smallest hash. Two sets get the same smallest hash exactly when the element that comes first in the union (under that hash) is in both sets. That chance equals the Jaccard similarity |A and B| / |A or B|. Repeat with K hash functions and count matches.

Worked example: A = {1, 2}, B = {2, 3}, p = 7. Hash 1 is x mod 7: A gives min(1, 2) = 1 and B gives min(2, 3) = 2, so they differ. Hash 2 is (3x + 1) mod 7: h(1) = 4, h(2) = 0, h(3) = 3, so both sets have min 0 (from the shared element 2) and they agree. The estimate is 1 match out of 2 = 0.5; the true Jaccard is 1 / 3, and more hash functions bring the estimate closer.

Rule: sig_k(S) = min over x in S of ((a_k x + b_k) mod p). est = fraction of k with equal entries.

Pretraining data pipelines bucket MinHash signatures with LSH to find near-duplicate pages.

Shapes and data flow

sets: N lists -> h (K, |set|) -> sig (N, K) -> est (N, N)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: exampleminhash([[1, 2], [2, 3]], [1, 3], [0, 1], 7)
  • Sample 2: near duplicatesminhash([[3, 5, 8, 13, 21], [3, 5, 8, 13, 34], [40, 41]], _a, _b, 97)