Data II: Filtering & Deduplication

C4 holds one 61-word ad 61,036 times. Change one word of a copy and an exact hash no longer sees it. MinHash with FineWeb's 14 bands of 8 hashes still flags that copy 98% of the time, and lets 95% of page pairs at Jaccard 0.5 pass.

Change words in the copy. Switch between an exact hash and MinHash bands, and draw new hash functions. Then we build each tool from zero: quality rules, perplexity, classifiers, importance resampling, Bloom filters, MinHash and LSH.

You need a probability and the idea of a hash: a function that turns any text into a number. We build the rest from zero.

Lecture 14 of Stanford CS336, Language Modeling from Scratch (Spring 2025, Percy Liang and Tatsunori Hashimoto). Previous: Lecture 13, Data I. Next: Lecture 15, Alignment I.

Catch an edited copy

1 of 61

The ad is the 61-word sentence Lee et al. (2022) found 61,036 times in C4; we made up the edits. Live: five-word shingles, 112 seeded MurmurHash3 functions, 14 bands of 8 (FineWeb's setting, Penedo et al. 2024). The curve is 1 − (1 − s8)14.

Chapter 0

Junk and Copies at Web Scale

See why a raw crawl needs filtering and deduplication, and why both must run in linear time

Lecture 13 ended with raw text pulled out of Common Crawl. Most of it should not reach the model. Some pages are junk: keyword lists, cookie banners, a word repeated sixty times. Many are copies: mirror sites, template pages, one licence pasted onto thousands of sites.

The worst copy Lee et al. (2022) found in C4 is a 61-word ad for wedding decorations. It appears 61,036 times in the training set and 61 times in the validation set. A model trained on C4 reads that ad more often than almost any sentence.

Copies cost twice. They waste compute, and they teach the model to recite. Lee et al. sampled 100,000 texts from a 1.5-billion-parameter model trained on C4. Of the tokens it wrote, 1.93% sat inside 50-token spans copied from its training data. Trained on deduplicated C4, the same model copied 0.19%.

The lecture frames filtering as one task. You have a little target data, T: text you want the model to sound like. You have a lot of raw data, R. Find the part of R that resembles T. The filter must generalize beyond T, and it must be fast, because it runs on all of R.

Deduplication is harder, because it compares pages with pages. Count the work:

Count the work

Each bar is the work for one method, on a log scale. Grow the crawl and read the time.

1B

Illustrative rate: one billion operations per second on one machine. The counts are exact: N pages, N(N − 1)/2 pairs.

Worked number: a billion pages make N(N − 1)/2 = 5.0 × 1017 pairs. At a billion comparisons a second, that is 5 × 108 seconds, or 15.8 years. Hashing each page once takes one second. Every tool in this lesson touches each page a fixed number of times.

Symptom: the model recites an ad, a licence or a forum signature word for word.

Measure: the share of generated tokens inside 50-token spans found in the training data (1.93% for the C4 model).

Fix: deduplicate before training. Lee et al.'s near-duplicate removal cut the rate to 0.19%.

The road

  1. Rules: counts against fixed limits, no model.
  2. Perplexity: a counting model trained on target text.
  3. Classifiers: target versus raw, and how to keep by score.
  4. Resampling: draw raw pages by importance weight.
  5. Other targets: language, toxicity and personal data.
  6. Bloom filters: exact copies in a few bits each.
  7. MinHash: near copies by set overlap.
  8. LSH bands: a sharp cut without comparing pairs.
  9. Showcase: clean a small crawl and judge each removal.
  10. Field guide: the table, the code and the habits.
You have 10 billion pages. Why not find duplicates by comparing every pair?

Chapter 1

Rules Before Models

Check simple counts against fixed limits, and see which junk each rule catches

The cheapest filter uses no model. It counts. The lecture lists C4, Gopher, RefinedWeb, FineWeb and Dolma as pipelines that chose not to use a model-based quality filter.

Gopher's rules (Rae et al., 2021) are the standard set. A page needs 50 to 100,000 words and a mean word length of 3 to 10 characters. It needs at least two of eight stop words, the glue words of English: the, be, to, of, and, that, have, with. At least 80% of its words must contain a letter. At most 30% of its lines may end in an ellipsis, and at most 90% may start with a bullet.

A second group catches repetition. One rule asks how much of the page sits inside its most common pair of adjacent words. Call the letters in all words of the page L. Call the letters in the words that belong to an occurrence of the most common pair Ltop. Their ratio is the top-pair fraction f2:

Say it aloud

f-two equals L-top over L.

f2
f-two the top-pair fraction, from 0 to 1. Gopher drops the page if it is above 0.20.
Ltop
L-top the letters in every word that is part of an occurrence of the most common word pair.
L
L the letters in all the words of the page.
In plain words

Find the pair of adjacent words that occurs most often. Mark every word inside one of its occurrences. Add up the letters of the marked words to get L-top, and divide by L.

With numbers

The keyword-spam page in the device: "cheap flights" occurs 7 times, so L-top = 84 letters of L = 322. f-two = 0.26, above 0.20, so the page fails. The word "the" written 60 times: every word is marked, f-two = 180 / 180 = 1.0.

Run Gopher's rules on a page

Each row is one rule: the bar is the page's value, the yellow mark is the limit. Pick a page and see which rules fire.

Rules and limits from Rae et al. 2021, Appendix A.1.1 and Table A1 (two of its thirteen repetition measures). Pages written for this lesson; word and letter counting simplified.

Gopher chose rules on purpose. They are easy to understand. Its authors also noted that text a model finds likely is not always good text: repetitive text is likely too. The next chapter shows that trap.

Symptom: whole kinds of good text vanish: poems with trailing ellipses, tables, code, short replies.

Measure: read a random sample of the pages each rule removes, rule by rule.

Fix: loosen that rule, or apply it only to the page types it fits.

A page is the word "the" repeated 60 times. Which Gopher rules catch it?

Chapter 2

Score Pages With an n-gram Model

Train a counting model on target text, and keep the pages it finds least surprising

To prefer pages that read like Wikipedia, train a model on Wikipedia and measure its surprise at each page. The lecture's tool is an n-gram model: it predicts each word from the n − 1 words before it, by counting. With n = 3, p(in | the cat) = count(the cat in) / count(the cat).

Most long word runs never occur, so many counts are zero. Kneser-Ney smoothing fixes this by mixing in shorter contexts: p(in | the cat) also uses p(in | cat). KenLM is a fast implementation. CCNet (Wenzek et al., 2020) trained a 5-gram KenLM model on Wikipedia and scored every paragraph of Common Crawl. It split each language into three equal parts by score: head, middle and tail. The lecture notes that LLaMA used CCNet's output.

Name the score. A page has N words, w1 to wN. The target model gives word i a probability from the word before it: pT(wi | wi−1) in our toy, a bigram model. The perplexity PPL is the average surprise, turned back into a count:

Say it aloud

P-P-L equals e to the minus one over N, times the sum over i of the log of p-T of w-i given w-i-minus-one.

PPL
P-P-L perplexity: how many equally likely words the model is choosing between, on average. Low means the page reads like the target.
exp
e to the undoes the log, so the answer is a count, not nats.
1/N
one over N divide by the number of words, so long pages are not penalized for length.
Σi
the sum over i one term per word, i = 1 to N.
ln
the log the natural log; minus it is the surprise of one word.
pT(wi | wi−1)
p-T of w-i given w-i-minus-one the target model's probability of word i after the word before it.
In plain words

For each word w-i, look up the probability p-T gives it after the previous word. Take the log, flip the sign, and average over the N words. Raise e to that average: that is PPL.

With numbers

From the device: the castle sentence has N = 20 words with an average surprise of 3.32 nats, so PPL = e3.32 = 27.6. The word "the" written 16 times averages 3.07 nats: PPL = 21.6, lower.

Rank pages by surprise

Top: each word of the chosen page, with a pink bar for its surprise. Bottom: four pages by perplexity. Move the yellow cut and see what a perplexity filter keeps.

32

Illustrative: a bigram model trained on 13 made-up sentences in an encyclopedia style. It mixes 0.7 of the pair count with 0.3 of the word count, so unseen pairs keep some probability. CCNet uses a 5-gram Kneser-Ney model trained on Wikipedia.

The toy mixes counts, with v the previous word: pT(w | v) = 0.7 × count(v w) / count(v) + 0.3 × p(w). "the the" never occurs in the target, so each repeat falls back to 0.3 × p(the) = 0.039, more than most words get. The lecture shows the same trap with KenLM.

Symptom: the kept set fills with boilerplate and repeated phrases.

Measure: run Gopher's repetition rules on a sample of the kept pages.

Fix: run the repetition rules beside the perplexity filter, as most pipelines do.

A perplexity filter uses a model trained on Wikipedia. Which page is it most likely to keep?

Chapter 3

A Classifier for "Looks Like the Target"

Train a fast linear model on target pages against raw pages, then choose how to keep by its score

Instead of modelling the target, train a classifier to tell target pages from raw ones. Its score is the probability that a page belongs to the target, p(T | x). The lecture's tool is fastText (Joulin et al., 2017): embed each word, average the embeddings, and apply one linear layer.

Count the weights. With a vocabulary of V words, a hidden width H and K classes, a plain bag of words has V × K weights. fastText has H × (V + K). Word pairs help, but they have no fixed count, so fastText hashes each pair into a fixed table of bins: 10 million in practice, the lecture says. For quality filtering K = 2, so the model is a linear classifier.

DCLM (Li et al., 2024) compared quality filters by training models on what each kept. At the 1B scale, a fastText filter scored 30.2 on their CORE average; perplexity filtering scored 29.0. The best positives were instruction data: OpenHermes 2.5 plus top-voted answers from r/ExplainLikeImFive. Keeping the top 10% scored 41.0 at the 7B scale, against 35.7 with Wikipedia as positives.

Then choose how to keep. DCLM keeps the top 10%. GPT-3 (Brown et al., 2020) kept a page if np.random.pareto(9) > 1 − score. Name the score s. NumPy's pareto draws a number X with P(X > x) = (1 + x)−9, so GPT-3's chance to keep a page is:

Say it aloud

P of keep given s equals two minus s, to the minus nine.

P(keep | s)
P of keep given s the chance GPT-3's rule keeps a page whose classifier score is s.
2 − s
two minus s one plus the bar the random draw must clear, 1 − s. s runs from 0 to 1.
−9
to the minus nine the Pareto shape α = 9. A larger α keeps fewer low scores.
In plain words

Subtract the score s from 2. Raise the result to the power minus 9. That is the chance the page stays.

With numbers

s = 0.9: 1.1−9 = 0.424. s = 0.5: 1.5−9 = 0.026. s = 0: 2−9 = 0.002. A top page stays less than half the time, and a bottom page still gets in about 1 time in 500.

Choose a keep rule

Teal: classifier scores of 10,000 raw pages. Pink: the chance the rule keeps each score. The filled part is what survives. Switch rules and change GPT-3's α.

9

Illustrative scores: a simulated raw pool, 80% unlike the target and 20% like it. The keep rules are exact: DCLM's top 10%, GPT-3's Pareto draw, and a fixed cut.

The soft rule is deliberate. GPT-3's authors chose α = 9 "to take mostly documents the classifier scored highly, but still include some documents that were out of distribution."

Symptom: the kept pages all sound alike, in the style of the positives.

Measure: compare the topics or word statistics of the kept pages with the raw pool.

Fix: keep some low scorers (a soft rule), or match the whole target distribution (next chapter).

Under GPT-3's rule, what is the chance to keep a page with score 0.5?

Chapter 4

Resample the Raw Pool to Match the Target

Weight each raw page by how much more the target favours it, then draw pages by weight

A classifier asks whether a page looks like the target. DSIR (Xie et al., 2023) asks for a sample of the raw pool that is distributed like the target. Its tool is importance resampling. Fit a model p to the target data and a model q to the raw data. Give each raw page x an importance weight w(x):

Say it aloud

w of x equals p of x over q of x.

w(x)
w of x the importance weight of raw page x. Above 1 means the target favours it more than the raw pool does.
p(x)
p of x the probability of page x under the model fitted to the target data.
q(x)
q of x the probability of page x under the model fitted to the raw data.
In plain words

Score page x under the target model p and under the raw model q. Divide to get w. Then draw pages from the raw pool with chance in proportion to w.

With numbers

The lecture's toy has four tokens. The target p is 0.1, 0.2, 0.3, 0.4; the raw q is 0.4, 0.3, 0.2, 0.1. The weights are 0.25, 0.67, 1.5 and 4. Token 3 is rare in the raw pool (0.1), but q × w = 0.4 after normalizing: exactly its target share.

The target set is small, so DSIR uses a simple model of a page: hashed n-grams. Each unigram and bigram goes into one of 10,000 buckets. p and q are bucket frequencies, and a page's probability is the product over its n-grams. With bj the bucket of the j-th n-gram:

ln w(x) = Σj [ ln p(bj) − ln q(bj) ]

Resample, or take the top

Teal: shares in the raw pool. Yellow marks: the target. Pink: the shares in the selected quarter of the pool. Switch methods and grow the pool.

400

The lecture's toy distributions; draws are seeded and redrawn on demand. Both methods select a quarter of the pool; resampling draws with replacement, as the lecture's code does.

DSIR selected 100 million documents from the Pile in 4.5 hours. With Wikipedia and books as the target, BERT-style models trained on its picks averaged 82.3 on GLUE, against 80.3 for random selection and 79.9 for a classifier filter. Taking the top weights instead of resampling scored 81.4.

Symptom: a handful of pages take most of the weight, and the sample repeats them.

Measure: the share of total weight held by the top 1% of pages.

Fix: use coarser features or smoothed bucket counts, so q never comes near 0.

In the lecture's toy, why does "top weights" fail to match the target?

Chapter 5

Same Machinery, Other Targets

Point a classifier at language or toxicity, and pick a threshold knowing what it removes

One toolkit serves many targets. Language identification comes first. fastText's lid.176 model knows 176 languages; it was trained on Wikipedia, Tatoeba and SETimes. Dolma keeps pages with p(English) ≥ 0.5, a step that removed 61.7% of its web data by bytes. FineWeb keeps a score of 0.65 or more.

Language ID fails in known ways, the lecture says: short texts, low-resource languages, dialects of English, close languages such as Malay and Indonesian, and pages that mix languages. Why filter at all? Curating good data in every language is hard. With fixed compute, each extra language gets fewer tokens: BLOOM was only 30% English, and its English suffered.

Toxicity filtering. Dolma trained two fastText classifiers on Jigsaw Toxic Comments: Wikipedia talk-page comments labelled toxic, severe_toxic, obscene, threat, insult or identity_hate. The "hate" detector takes unlabelled and obscene-only comments as negatives and all other comments as positives. The "NSFW" detector takes obscene comments as positives.

Set the toxicity threshold

Each dot is one sentence at its score: toxic sentences on top, benign ones below. The filter removes sentences right of the yellow line. Green is a right call, red a wrong one.

0.4

Illustrative sentences and scores, written for this lesson. The two thresholds and their removal rates are Dolma's (Soldaini et al., 2024).

The threshold is a policy choice. Dolma compared τ = 0.4, which removed 5.5% to 7.3% of the data, with τ = 0.0004, which removed 29.1% to 34.9%. The strict cut gave better downstream scores. Dolma kept 0.4 anyway, to reach its minimum token count. Gopher used Google SafeSearch instead of word lists, because word lists remove inoffensive text about minority groups more often.

Personal data. Dolma finds email addresses, phone numbers and IP addresses with regular expressions. A page with 5 or fewer such spans gets them replaced by tokens such as |||EMAIL_ADDRESS|||. Dolma removes a page with 6 or more.

Worked number: a crawl with 100 TB of text keeps 38.3 TB after Dolma's English step, which removed 61.7% by bytes. The language filter is the biggest single cut in that pipeline.

Symptom: text about hard topics disappears: news about violence, research on hate speech.

Measure: run the classifier on labelled benign text about those topics and count the removals.

Fix: raise τ, or tag such text instead of deleting it.

Dolma lowered the toxicity threshold from 0.4 to 0.0004 in a test. What happened?

Chapter 6

Exact Copies: Hash, Group, and a Bloom Filter

Hash each item once, keep one per hash, and test "seen before?" in a few bits per item

Deduplication has three choices, the lecture says: what an item is (a sentence, paragraph or page), how items match (exactly, or by shared parts), and what to do (remove all copies, or all but one). Exact matching is simplest: hash every item, group by hash, keep one per group. It hashes each item once, so it is linear and splits across machines.

A hash function maps an item to a short number. SHA-256 resists collisions but is slow; MurmurHash is fast and makes no such promise, so dedup uses it. CCNet found that duplicate paragraphs make up 70% of Common Crawl's text. C4 removes repeated three-sentence spans, which can leave a page that reads badly.

To ask "seen before?" over billions of items, keep bits, not hashes. A Bloom filter is an array of m bits, all 0. Inserting an item sets the bits its k hashes point to. A query checks those k bits: any 0 means "definitely new", all 1s mean "probably seen". It never gives a false negative, and it cannot delete.

After n inserts, the filter has set kn bits at random. One bit stays 0 with chance (1 − 1/m)kn ≈ e−kn/m. A new item is a false positive when all its k bits happen to be 1. Call that rate f:

Say it aloud

f equals one minus e to the minus k-n over m, all to the power k.

f
f the false-positive rate: the chance a never-inserted item looks "seen".
e−kn/m
e to the minus k-n over m the chance one bit is still 0 after n items of k hashes each, in m bits.
k
to the power k all k bits of the new item must be 1.
In plain words

Multiply k by n and divide by m. Raise e to minus that: the chance a bit is still 0. One minus it is the chance a bit is 1. Raise that to the k: the chance all k bits are 1.

With numbers

The lecture's example: m = 1,000, n = 100, k = 10. kn/m = 1, so 1 − e−1 = 0.632, and f = 0.63210 = 0.0102.

More hashes help until the array fills. The best count k* leaves half the bits set:

Say it aloud

k-star equals m over n, times the log of 2.

k*
k-star the number of hashes that makes f smallest. Then f = 0.5k*.
m/n
m over n bits of memory per item.
ln 2
the log of 2 0.693.
In plain words

Divide the bits m by the items n and multiply by 0.693. Then f halves for every 1.44 more bits per item.

With numbers

10 bits per item: k* = 6.93 and f = 0.0082. Dolma's f = 10−15 (from the lecture) needs 49.8 hashes and 71.9 bits per paragraph. DCLM's 1012 tokens at f = 10−12 need 57.5 bits each: 6.5 TiB, the "6.5TB of RAM" its paper quotes.

Fill a Bloom filter

Top: the bit array, blue where a bit is 1. Bottom: the false-positive rate against k, formula in pink, measured as a dot. Change the bits, the items and the hashes.

1,000
100
10

Live: real MurmurHash3 with k seeds over made-up item names. The curve is the formula; the dot is measured on 2,000 items never inserted.

Dolma also seeds a Bloom filter with test examples, to flag test text in the training data (Lecture 12 covers contamination).

Symptom: unique paragraphs get deleted as "seen".

Measure: compute f at the final n; the array fills as you insert.

Fix: size m for the final n. DCLM removes a paragraph only when a set fraction of its n-grams hit, so one false positive rarely deletes it.

A Bloom filter answers "not present" for a paragraph. What do you know?

Chapter 7

Near Copies: Jaccard and MinHash

Turn each page into a set of word runs, and estimate their overlap from one minimum per hash

One changed word gives a new exact hash. Near copies are common, the lecture says: licences, template pages, copy-paste with small format changes. We need a similarity that falls gently with each edit, and a hash that collides more for more similar pages.

Turn a page into a set of shingles: every run of n consecutive words. FineWeb uses 5-word shingles; Gopher used 13. For two pages with shingle sets A and B, the Jaccard similarity is:

Say it aloud

J of A and B equals the size of A intersect B, over the size of A union B.

J(A, B)
J of A and B the Jaccard similarity, from 0 to 1.
|A ∩ B|
the size of A intersect B the number of shingles in both pages.
|A ∪ B|
the size of A union B the number of shingles in either page.
In plain words

Count the shingles the two pages share. Count the shingles in either page. Divide the first count by the second.

With numbers

The hero's ad has 61 words, so 57 five-word shingles. One changed word in the middle changes 5 of them: 52 shared, 62 in either. J = 52 / 62 = 0.84. Two changed words: J = 47 / 67 = 0.70.

MinHash (Broder, 1997) makes a hash that collides with chance J. Draw a random hash function. Hash every shingle of a page and keep only the smallest value: minA for page A, minB for page B.

Say it aloud

The probability that min-A equals min-B equals J of A and B.

P
the probability that over random hash functions.
minA
min-A the smallest hash value over page A's shingles.
minB
min-B the same for page B, with the same hash function.
J(A, B)
J of A and B the Jaccard similarity.
In plain words

The hash puts the shingles of A ∪ B in a random order. Each is equally likely to come first. The minimums match exactly when the first one is in both sets: |A ∩ B| chances in |A ∪ B|, which is J.

With numbers

The lecture's sets: A = {1, 2, 3, 4} and B = {1, 2, 3, 5}. A ∪ B has 5 items. The first is 1, 2 or 3 with chance 3/5, so the minimums match with chance 0.6 = J.

One hash gives one match or miss. Use n hash functions and count the matches; their fraction is the estimate Ĵ. Each match is a coin flip with chance J, so its typical error is:

Say it aloud

S-D of J-hat equals the square root of J times one minus J, over n.

SD(Ĵ)
S-D of J-hat the standard deviation: how far a typical estimate lands from J.
√
the square root of so 4 times the hashes only halves the error.
J (1 − J)
J times one minus J the variance of one match; largest at J = 0.5.
n
n the number of hash functions, the signature length.
In plain words

Multiply J by one minus J. Divide by n, the number of hashes. Take the square root.

With numbers

J = 0.6, n = 100: √(0.24 / 100) = 0.049. The lecture's seeds 0 to 99 land exactly on 0.6. Over 200 other blocks of 100 seeds, the estimates spread with SD 0.047; only 5.5% landed within 0.01.

Estimate Jaccard from minimums

Top: 20 shingles, filled where both pages have them. Middle: one signature, pink where the minimums match. Bottom: 500 estimates against the yellow true value. Change the overlap and the hashes.

12 of 20
100

Live: each trial draws n fresh seeded hash functions (a MurmurHash3-style mix) over 20 made-up shingles.

Symptom: a pair near the threshold is flagged in one run and missed in another.

Measure: SD = √(J(1 − J)/n): 0.038 at J = 0.8 with FineWeb's 112 hashes.

Fix: more hashes, or an exact check of candidate pairs.

A = {a, b, c, d} and B = {b, c, d, e, f}. What is the chance their minimums match under a random hash?

Chapter 8

LSH: Turn a Slope Into a Step

Split the signature into bands, call a pair a candidate if any band matches, and tune the S-curve

One MinHash collides with chance J, so pages at J = 0.3 collide 30% of the time. We want a sharp cut: almost always a candidate at J = 0.8, almost never at J = 0.5. And we want it without comparing pairs.

Locality-sensitive hashing (LSH) splits the n hashes into b bands of r rows, so n = b × r. Each band's r values go into a bucket as one key. Two pages become a candidate pair if they share a bucket in at least one band. Pages meet only inside buckets, so the work stays close to linear.

Why the step? One row matches with chance s, the Jaccard. A band needs all r rows: sr, an AND. The pair is a candidate if any of b bands matches, an OR:

Say it aloud

P of s equals one minus, one minus s to the r, all to the b.

P(s)
P of s the chance that two pages with Jaccard s become a candidate pair.
sr
s to the r the chance all r rows of one band match.
b
to the b all b bands must miss for the pair to stay apart.
In plain words

Raise s to the r: one band matches. Subtract it from 1 and raise to the b: every band misses. Subtract that from 1: some band matches.

With numbers

FineWeb: 112 hashes as 14 bands of 8 rows. At s = 0.8: 0.88 = 0.168, (1 − 0.168)14 = 0.076, so P = 0.924. At s = 0.5, P = 0.053.

Where is the step? Set P(s) = 0.5 and solve for the Jaccard s*:

Say it aloud

s-star equals one minus a half to the one over b, all to the one over r.

s*
s-star the Jaccard at which a pair becomes a candidate half the time: the middle of the step.
0.51/b
a half to the one over b the b-th root of 0.5: the miss chance each band must have.
1/r
to the one over r the r-th root turns a band's chance back into a row's chance.
In plain words

Take the b-th root of 0.5 and subtract it from 1. Take the r-th root of the result. That is s-star.

With numbers

14 bands of 8: s* = 0.685; FineWeb says it targets pages "at least 75% similar". The lecture's rule of thumb, (1/b)1/r = 0.719, marks where P ≈ 0.63. More rows move the step right and sharpen it; more bands move it left.

Shape the S-curve

Pink: the chance of becoming a candidate against Jaccard. Grey dashes: one MinHash alone. Yellow: the half point. Pick a published setting, then move bands and rows.

14
8

The curve is exact. Dots: 400 simulated pairs at each Jaccard, each band matching with chance sr, seeded. Cost assumes 4 bytes per hash.

Lee et al. used 9,000 hashes and wrote the formula as 1 − (1 − sb)r with b = 20, r = 450. In this lesson's letters that is 450 bands of 20 rows. The step sits at 0.723, and pairs at J = 0.8 become candidates 99.5% of the time: the "high probability" they asked for. The lecture's notes read it as 20 bands of 450 rows, which moves the step to 0.993. Lee et al. kept a candidate only if its true Jaccard and edit similarity both topped 0.8.

Symptom: FineWeb deduplicated all 96 snapshots against each other, and its models barely improved.

Measure: an old snapshot kept 10% of its data. A model trained on that 10% did worse than one trained on the removed 90%.

Fix: deduplicate each snapshot on its own. FineWeb shipped that.

With b = 10 bands, you raise the rows from r = 10 to r = 20. What happens to the step?

Chapter 9

Showcase: Clean a Small Crawl

Run rules, exact hashing and MinHash bands over 42 pages, then judge every removal

A toy crawl of 42 pages of 60 words. Five families each hold a page, an exact copy, two copies with 1 word changed (J ≈ 0.84), one with 2 changed (J ≈ 0.70) and one with 4 changed (J ≈ 0.47). Six pages are unique, and six are junk. Call a pair a near-duplicate when J ≥ 0.8, the threshold Gopher and Lee et al. used. A perfect run keeps 21 pages.

Clean the crawl

Rows are families; the last two rows are unique and junk pages. Step through the stages, pick a band setting, and turn on the exact check of candidates.

Stage
Bands × rows

Illustrative toy corpus, generated from a seed. The pipeline is real: two Gopher rules, an exact hash of the normalized text, five-word shingles, seeded MurmurHash3 MinHash, LSH buckets, then clusters that keep their first page.

Things to try. At "+ Rules", the six junk pages go: keyword spam has no stop words, and a repeated phrase fills its top word pair. At "+ Exact", the five exact copies go. At "+ Near-dup" with 14 × 8, the 2-word copies (J ≈ 0.70) sometimes merge with their family: the step sits at 0.685. Switch to 28 × 4 (step at 0.40) and the 4-word copies merge too. Turn on the exact check and every wrong merge disappears.

Then try 10 × 10 and press "New hash functions" a few times. With its step at 0.763, a 1-word copy at J = 0.84 sometimes survives. The exact check cannot fix that: it only removes candidates, it never adds them.

Check yourself. Which setting can miss a true copy? Which one merges pages that are not copies? Which control fixes only one of the two?

Chapter 10

Field Guide

Keep the table, the code, and the questions to ask of any data pipeline

Filtering keeps the part of a raw crawl that resembles a target. Rules check form; an n-gram model, a classifier or importance resampling compares each page with the target. Deduplication finds copies in linear time: exact hashes and Bloom filters for exact copies, MinHash and LSH bands for near copies. Every threshold trades what you keep against what you lose.

ToolFormula or numberMain caveat
Gopher rulesf2 = Ltop/L ≤ 0.20; 50 to 100,000 words; 2 of 8 stop wordsthey check form, not truth
Perplexity filterPPL = exp(−(1/N) Σ ln pT); toy: 27.6 for prose, 21.6 for "the" × 16rewards repetition; pair with rules
Classifier, GPT-3 keepP(keep | s) = (2 − s)−9; s = 0.9 gives 0.42copies the style of the positives
DSIRw = p/q; toy weights 0.25, 0.67, 1.5, 4resample, do not take the top
Bloom filterf = (1 − e−kn/m)k; k* = (m/n) ln 2; 10 bits per item gives 0.82%size it for the final n
MinHashP(match) = J; SD = √(J(1−J)/n): 0.049 at J = 0.6, n = 100all pairs is still N²/2
LSH bandsP = 1 − (1 − sr)b; 14 × 8: step at 0.685, P(0.8) = 0.924candidates need checking

The core, as Python we ran:

python
import math, mmh3
import numpy as np

def gpt3_keep_prob(score, alpha=9):           # P(pareto(alpha) > 1 - score)
    return (2 - score) ** -alpha

def dsir_resample(pool, p, q, k, rng):            # pool: token ids drawn from q
    w = np.array([p[x] / q[x] for x in pool])
    return rng.choice(pool, size=k, p=w / w.sum())

def bloom_fp(m, n, k):
    return (1 - math.exp(-k * n / m)) ** k

def shingles(text, n=5):
    w = text.lower().split()
    return {" ".join(w[i:i + n]) for i in range(len(w) - n + 1)}

def signature(S, num_hashes):                    # MinHash: one minimum per seed
    return [min(mmh3.hash(s, seed, signed=False) for s in S) for seed in range(num_hashes)]

def lsh_buckets(sigs, b, r):                     # sigs: {doc_id: signature of b*r}
    buckets = {}
    for doc, sig in sigs.items():
        for band in range(b):
            key = (band, tuple(sig[band * r:(band + 1) * r]))
            buckets.setdefault(key, []).append(doc)
    return [g for g in buckets.values() if len(g) > 1]   # candidate groups

def lsh_prob(s, b, r):
    return 1 - (1 - s ** r) ** b

gpt3_keep_prob(0.9)                      # 0.424
bloom_fp(1000, 100, 10)                   # 0.0102
lsh_prob(0.8, 14, 8), lsh_prob(0.8, 450, 20)  # 0.924, 0.995
(1 - 0.5 ** (1 / 14)) ** (1 / 8)             # 0.685, the step for 14 x 8

The lecture's summary: the tools are n-gram models, classifiers and importance resampling; the targets are language, quality and toxicity; hashing makes fuzzy deduplication scale. Its last line: "Now you have the tools (mechanics), just have to spend time with data (intuitions)."

Keep going

Read next

The habit. For any data pipeline, ask four things: what is the target, what does each threshold remove, what counts as a copy, and did anyone read a sample of what was thrown away.
You must deduplicate 5 billion web pages and catch pairs above Jaccard 0.8 almost always. Which plan fits?

Now teach it: press Present or Teach. Explain why one changed word defeats an exact hash, and how bands turn MinHash's slope into a step. Then go back to the ad and its copy, set two words changed, and predict how often 14 bands of 8 flag it before you draw new hash functions.

Data II: Filtering & Deduplication · Stanford CS336, Lecture 14
Previous: Data I · Next: Alignment I · Course site · Back to Gleams