Skip to content
Data for AI Advanced 31 min read

Quality filtering and deduplication

Most of the web is not worth training on, and much of what is worth training on appears many times. This page is the engineering and the mathematics of throwing data away well: cascades of cheap tests, MinHash and locality-sensitive hashing for near-duplicates, suffix arrays and Bloom filters for exact ones, and quality classifiers understood for what they really are, density-ratio estimators that pull the corpus towards a reference distribution.

10,000 ft

At fixed compute, a model trained on less but better data beats one trained on more raw data: FineWeb, DCLM and RefinedWeb all showed double-digit benchmark swings from filtering and deduplication choices alone, with no change to the model. Filtering is therefore not cleaning in the janitorial sense; it is the most leveraged modelling decision in pre-training, and it is made with statistics, hashing and small classifiers rather than gradient descent. The pipeline as a whole is walked through in pre-training data; this page goes underneath it, deriving why each tool works, what it costs and how it fails. Its neighbours are collection (what comes in), contamination (what must stay out) and scaling laws (why the trade-off between quality and quantity depends on your compute budget).

2,000 ft

Every document faces three questions: is it usable text (extraction, language, rules), is it new (deduplication at several granularities), and is it good (a quality model). Ask them in order of cost, so the expensive tests only see what the cheap ones let through.

A filtering cascade: cheapest tests first
A filtering cascade: cheapest tests first. Raw crawl (every document), URL blocklist + URL dedup ~free, Extract text from HTML, Language ID fastText, Heuristic rules length, symbols, repetition, Exact dedup hash / Bloom filter, Near-dup MinHash LSH, Quality model classifier or LLM-labelled, PII, safety, decontamination, Kept corpusA filtering cascade: cheapest tests first. Raw crawl (every document), URL blocklist + URL dedup ~free, Extract text from HTML, Language ID fastText, Heuristic rules length, symbols, repetition, Exact dedup hash / Bloom filter, Near-dup MinHash LSH, Quality model classifier or LLM-labelled, PII, safety, decontamination, Kept corpus

  1. Rules are hypotheses about junk (too short, too many symbols, too repetitive); each must earn its place in an ablation.
  2. Deduplication has six granularities, from same URL to same meaning; near-duplicates use MinHash, whose collision probability equals Jaccard similarity.
  3. Banding turns a similarity estimate into a tunable threshold: \(P = 1-(1-s^r)^b\).
  4. Quality classifiers estimate the ratio \(p_{\text{ref}}(x)/p_{\text{raw}}(x)\); keeping the top slice is a sharpened version of importance resampling towards the reference.
  5. Measure every choice by training small models on the result; "quality" means "what improves the evaluations you chose".

Ground level

The cascade principle

A pipeline over 100 billion documents is a sequence of predicates, and its cost is dominated by the expensive ones. If test \(i\) costs \(c_i\) per document and passes a fraction \(\pi_i\), the cost per input document of running them in order is

\[ c_1 + \pi_1 c_2 + \pi_1\pi_2 c_3 + \dots \]

so you want cheap, aggressive tests first and expensive, subtle ones last. A URL blocklist costs a hash lookup. A regular-expression rule costs one pass over the text. A fastText classifier, a linear model over hashed n-grams, is cheap enough to run on every document with CPUs alone. A transformer quality scorer costs GPU time: FineWeb-Edu's classifier, an embedding model with a linear head, needed 6,000 H100 GPU-hours to score the 15 trillion tokens of FineWeb (Penedo et al., 2024). Running an LLM itself over every document would cost orders of magnitude more, which is why the LLM is used to label a sample and a small model is trained to imitate it at scale.

Order also matters for correctness, not just cost. Deduplicate before quality filtering and the classifier never sees a thousand copies of the same spam page. But Dolma deliberately removed repeated paragraphs last, because stripping boilerplate paragraphs early disrupts the content analysis of the filters that follow (Soldaini et al., 2024).

Heuristic rules as testable hypotheses

The classic rule sets are worth knowing exactly, because every modern pipeline still runs some version of them.

Rule family C4 (Raffel et al., 2019) Gopher / MassiveText (Rae et al., 2021)
Length drop pages with fewer than 3 sentences; keep lines with at least 5 words keep documents of 50 to 100,000 words
Word shape mean word length 3 to 10 characters; 80% of words contain a letter
Symbols and markup drop pages with a curly bracket; drop lines mentioning Javascript; drop "lorem ipsum" pages hash or ellipsis symbols at most 0.1 per word; at most 90% of lines start with a bullet, at most 30% end with an ellipsis
Prose signal keep only lines ending in terminal punctuation at least two of: the, be, to, of, and, that, have, with
Repetition drop all but one of any repeated three-sentence span thresholds on duplicate lines, paragraphs and top n-gram character fractions
Content drop pages containing any word from a bad-words list; drop policy and cookie boilerplate lines
Language langdetect English probability at least 0.99

Each rule is a hypothesis ("pages with curly brackets are code, not prose") with a false-positive cost. FineWeb tested them rather than trusting them: C4's terminal-punctuation rule alone removed about 30% of tokens, too costly for its benefit, so FineWeb dropped it and added three of its own, found by comparing statistics of good and bad crawls: drop documents where at most 12% of lines end in punctuation (removing 10.1% of tokens), where duplicated lines hold at least 10% of characters (12.5%), or where at least 67% of lines are shorter than 30 characters (3.7%). Together they removed about 22% of tokens for roughly a one-point aggregate gain in 28B-token ablations.

The C4 bad-words filter is the cautionary example. Documenting C4, Dodge et al. found that the blocklist disproportionately removed text from and about minority individuals, largely because many listed words also occur in ordinary, non-offensive writing about sexuality and identity (2021). A rule's errors are not random; they fall on whoever writes differently from the rule-writer's mental model of "good" text.

Language identification and perplexity filters

Language ID is a classifier like any other. The standard tool is fastText's language identifier (fastText docs), a linear model over character n-grams that is cheap to run on CPUs; FineWeb kept pages with an English score of at least 0.65. Thresholds trade recall for purity, and the trade is harsh for low-resource languages, whose pages are short, code-switched and confused with neighbouring languages. FineWeb2 re-tuned the whole pipeline per language for exactly this reason (Penedo et al., 2025).

Perplexity filtering scores text by how likely a reference language model finds it. CCNet trained a 5-gram Kneser–Ney model (KenLM) on Wikipedia for each language, computed each paragraph's perplexity and split the corpus into head, middle and tail terciles (Wenzek et al., 2019). The paper is candid about the failure mode: perplexity measures closeness to Wikipedia, so legitimate text with a different vocabulary (blogs, informal registers) lands in the tail. A perplexity filter is a quality classifier with the positives fixed to "looks like Wikipedia", which is the next topic.

Quality classifiers are density-ratio estimators

The modern quality filter trains a binary classifier: positives from a reference set you like, negatives from the raw pool. GPT-3 used WebText, Wikipedia and books as positives against raw Common Crawl, with a logistic regression on hashed token features (Brown et al., 2020, Appendix A). DCLM's best filter was a fastText classifier with instruction data and highly rated ELI5 answers as positives. FineWeb-Edu used Llama-3-70B-Instruct's 0–5 educational scores on 460,000 pages to train a regressor. These look like three different ideas. They are one idea.

A classifier trained with balanced classes to separate samples of \(p_{\text{ref}}\) from samples of \(p_{\text{raw}}\) learns, at the optimum,

\[ \frac{P(\text{ref} \mid x)}{P(\text{raw} \mid x)} = \frac{p_{\text{ref}}(x)}{p_{\text{raw}}(x)} , \]

so its logit estimates the log density ratio (derivation in The maths). That ratio is exactly the importance weight you would use to turn samples from the raw pool into samples from the reference distribution. So a quality classifier is a tool for resampling the web to look like the reference, and two consequences follow.

  1. Your positives are your definition of quality. Choose Wikipedia and you get encyclopaedic prose; choose instruction data and you get question-answer-shaped text. Gururangan et al. ran GPT-3's quality filter over US high-school newspaper articles and found it preferred articles from larger schools in wealthier, more educated, urban ZIP codes, and that its scores did not track factuality or literary acclaim (2022). The filter was doing its job; the job was "look like the reference".
  2. Keeping the top slice is not the same as resampling. Resampling with weights proportional to the ratio reproduces the reference distribution. Keeping only the top 10% by score over-shoots: it concentrates on the most reference-like documents and narrows the distribution. The code in Build it shows both effects on a toy example.

GPT-3 sat in between. It kept a document if a Pareto-distributed random draw exceeded one minus its score, np.random.pareto(α) > 1 − document_score with \(\alpha = 9\), "to take mostly documents the classifier scored highly, but still include some documents that were out of distribution". DSIR made the resampling view explicit: estimate importance weights on hashed n-gram features and resample; with Wikipedia and books as the target it beat random selection and heuristic filtering by 2 to 2.5 points on GLUE (Xie et al., 2023).

The picture to keep

The raw web is a wide, lumpy distribution; your reference set is a small, tight one inside it. A quality classifier draws the contour lines of "how much more reference-like than average" over the web. Resampling by those contours rebuilds the reference distribution; taking only the peak gives you the reference's most stereotypical corner. Both are choices about diversity, whether you meant them to be or not.

Deduplication at six granularities

"Duplicate" means different things at different scales, and pipelines usually run several of these together.

Deduplication at six granularities
Deduplication at six granularities. What counts as 'the same'?, Same URL keep latest crawl, Identical document hash of normalised text, Repeated line or paragraph hash counts, Bloom filter, Repeated substring suffix array, ≥ 50 tokens, Near-duplicate document MinHash LSH, SimHash, Same meaning embeddings + clustering (SemDeDup)Deduplication at six granularities. What counts as 'the same'?, Same URL keep latest crawl, Identical document hash of normalised text, Repeated line or paragraph hash counts, Bloom filter, Repeated substring suffix array, ≥ 50 tokens, Near-duplicate document MinHash LSH, SimHash, Same meaning embeddings + clustering (SemDeDup)

Why bother? Three reasons, each with a number.

  • Wasted compute and degraded models. Hernandez et al. trained models where 90% of tokens were unique and a small slice was repeated: repeating 0.1% of the data 100 times degraded an 800M-parameter model to the performance of a model half its size (2022). A few heavily repeated documents are far worse than their token count suggests.
  • Memorisation and privacy. A sequence present 10 times in training data is generated about 1,000 times more often than one present once (Kandpal et al., 2022). Lee et al. found a single 61-word sentence repeated over 60,000 times in C4, and that deduplicated training made models emit memorised text ten times less often (2021).
  • Honest evaluation. The same paper found train–test overlap in over 4% of the validation sets of standard datasets. Duplicates across the train/test boundary inflate scores; that is the subject of contamination.

Exact duplicates: hashing, Bloom filters and suffix arrays

Whole documents and lines are deduplicated by hashing a normalised form (lower-cased, whitespace-collapsed, perhaps digits masked) and keeping the first occurrence of each hash. At web scale the set of seen hashes is itself too big for memory, so pipelines use a Bloom filter (Bloom, 1970): a bit array of \(m\) bits and \(h\) hash functions; to insert an item, set its \(h\) bits; to query, check whether all \(h\) are set. It never misses a true duplicate and occasionally flags a new item as seen, with false-positive rate about \((1-e^{-hn/m})^h\) after \(n\) insertions. Dolma ran URL, document and paragraph deduplication through one Bloom filter, and reused it for decontamination by seeding it with test examples first. A Bloom filter's false positive deletes a unique paragraph, so size it for a false-positive rate you can afford (see the maths: about 9.6 bits per item for 1%).

Repeated substrings inside otherwise different documents (licence text, boilerplate, quoted passages) need a different tool. Lee et al.'s ExactSubstr concatenated the whole corpus, built a suffix array (all suffixes, sorted; Manber and Myers, 1993), and removed any span of at least 50 tokens that occurred more than once. In a sorted suffix array, every repeated substring appears as a shared prefix of adjacent suffixes, so one linear scan of the longest-common-prefix values finds them all. The cost is memory: the array holds one integer per token of the corpus.

Near-duplicates: MinHash and locality-sensitive hashing

Most duplication on the web is approximate: the same article with a different header, a template with different product names, a forum post quoted with one line added. You want pairs of documents whose sets of shingles (word \(n\)-grams, usually 5-grams) overlap heavily, measured by Jaccard similarity \(J(A,B) = |A\cap B| / |A\cup B|\). Comparing all pairs of \(10^{10}\) documents is out of the question (\(5\times10^{19}\) pairs), so the method has two stages.

MinHash LSH, end to end
MinHash LSH, end to end. Document, Shingles word 5-grams, Signature k min-hashes, Bands b groups of r, Buckets one per band value, Candidate pairs share ≥ 1 bucket, Optional check true Jaccard or edit similarity, Union-find clusters, Keep one per clusterMinHash LSH, end to end. Document, Shingles word 5-grams, Signature k min-hashes, Bands b groups of r, Buckets one per band value, Candidate pairs share ≥ 1 bucket, Optional check true Jaccard or edit similarity, Union-find clusters, Keep one per cluster

Stage 1, MinHash (Broder, 1997). Apply a random hash function to every shingle of a document and keep the minimum. For two documents, the probability that their minima are equal is exactly their Jaccard similarity. Repeat with \(k\) independent hash functions to get a \(k\)-number signature per document; the fraction of positions where two signatures agree is an unbiased estimate of \(J\) with standard deviation \(\sqrt{J(1-J)/k}\). Signatures are tiny and fixed-size whatever the document length.

Stage 2, banding (locality-sensitive hashing). Cut each signature into \(b\) bands of \(r\) values (\(k = br\)). Hash each band to a bucket; two documents become a candidate pair if they share a bucket in at least one band. A pair with similarity \(s\) matches a given band with probability \(s^r\) and becomes a candidate with probability

\[ P(s) = 1 - (1 - s^r)^b , \]

an S-shaped curve with its steep part near \(s^\star \approx (1/b)^{1/r}\). Increasing \(r\) moves the step right and steepens it; increasing \(b\) moves it left. You choose \((b, r)\) to put the step at the similarity you call "duplicate".

00.20.40.60.8100.51Jaccard similarity s of the two shingle setsP(candidate pair)14 × 8 (FineWeb, k = 112)7 × 16 (same k = 112)450 × 20 (Lee et al., k = 9,000)
The banding S-curve P = 1 − (1 − s^r)^b for three designs; dashed lines mark the approximate threshold (1/b)^(1/r). With the same 112 hashes, 14 bands of 8 rows put the step near 0.72 and 7 bands of 16 near 0.89. Lee et al. spent 9,000 hashes (450 bands of 20 rows) to make the step almost vertical near 0.74, then verified candidates with edit similarity.

Read numbers off the curves. With FineWeb's 14 × 8, a pair at \(s = 0.8\) is caught 92% of the time, a pair at \(0.7\) 57% of the time, and a pair at \(0.6\) 21% of the time. With 7 × 16 (the same 112 hashes) a pair at \(0.8\) is caught only 18% of the time. Lee et al.'s 450 × 20 catches 99.5% at \(0.8\) and 1.6% at \(0.6\): a near-perfect step, bought with 80 times more hashing.

Stage 3, clustering. Candidate pairs form a graph; connected components (computed with union-find) are the duplicate clusters, and one document per cluster is kept. Components are transitive: if A matches B and B matches C, all three share a cluster even if A and C are not similar. On the web, where a document is edited, re-syndicated and edited again, chains like this are common, and a cluster can grow to contain documents that share very little. The toy run in Build it produces exactly that: five versions of a document, each 82% similar to the next, end up in one cluster although the first and last are only 47% similar. Some pipelines accept this (FineWeb keeps one random document per transitive cluster); others verify each candidate pair with an exact similarity before merging (Lee et al. required edit similarity above 0.8).

SimHash is the main alternative (Charikar, 2002): project a document's weighted features onto random hyperplanes and keep the sign bits, giving a fingerprint whose Hamming distance tracks cosine rather than Jaccard similarity. Google's web crawler used 64-bit SimHash fingerprints and declared near-duplicates at Hamming distance of at most 3, validated on 8 billion pages (Manku et al., 2007).

Semantic deduplication

Two documents can say the same thing with no shared 5-grams: paraphrases, translations, the same image cropped differently. SemDeDup embeds every item with a pre-trained model, clusters the embeddings with k-means, and within each cluster removes items whose cosine similarity to another item exceeds a threshold. On LAION it removed 50% of the data with minimal performance loss, halving training time (Abbas et al., 2023). Semantic deduplication blurs into diversity selection: it removes redundancy, but it also removes the repeated emphasis that tells a model a fact is common. Use it with ablations, not faith.

How much to filter depends on how much you will train

FineWeb's sharpest lesson (told in full in pre-training data) is that more deduplication is not always better: deduplicating 96 crawls globally removed up to 90% of the oldest crawls and barely beat no deduplication, because what survived was disproportionately junk, while deduplicating each crawl separately worked better. Duplication count is itself a quality signal; good pages get re-crawled.

The same tension governs quality filtering. Aggressive filtering leaves fewer unique tokens, and a long training run will then repeat them, and repetition decays in value. Goyal et al. made this precise as the quality–quantity trade-off: the best filter depends on the total compute, because "data curation cannot be agnostic of the total compute" a model will be trained for; small budgets favour the cleanest slice, large budgets need to admit lower-quality unseen data rather than repeat the best (2024).

Measuring a filter

You cannot evaluate a filter by reading its output; you evaluate it by training on it. The FineWeb protocol is a good default: for each candidate dataset, train two 1.71B-parameter models (different data subsets and seeds) on about 28B tokens, and score them on benchmarks chosen because they show low variance across seeds, rise steadily during training, and sit above chance at small scale (they used CommonSense QA, HellaSwag, OpenBook QA, PIQA, SIQA, WinoGrande, ARC and MMLU). DCLM turned the same idea into a public competition with fixed training code at several scales, so that only the data varies (Li et al., 2024).

Three traps. Seed noise: differences smaller than the spread between seeds are not differences. Benchmark overfitting: a filter tuned on MMLU-like positives raises MMLU, which says little about anything else. Scale transfer: a filter that wins at 28B tokens may lose at 2T, for the quality–quantity reason above, so confirm finalists with a longer run.

First principles

Why MinHash works at all. A uniformly random permutation of the universe of shingles makes every element of \(A\cup B\) equally likely to come first. The minima of \(A\) and \(B\) coincide if and only if that first element lies in \(A\cap B\). So the probability is the fraction of the union that is shared, which is the definition of Jaccard similarity. Nothing about the documents' lengths or content enters; the hash only needs to behave like a random permutation.

Why banding gives a threshold. A single min-hash comparison is a coin with bias \(s\): far too noisy to threshold. Requiring \(r\) coins to agree (AND) suppresses low similarities as \(s^r\); allowing any of \(b\) bands to succeed (OR) restores high similarities. AND-then-OR composition turns a linear response into a sigmoid, which is the general recipe for amplifying any locality-sensitive hash family.

Why duplicates hurt more than their share. Training on a repeated document is the same as up-weighting it in the mixture. By the mixture argument the model's target distribution then over-represents it, and gradient steps on content already fitted buy memorisation rather than generalisation. Hernandez et al.'s result (0.1% of data repeated 100 times halving effective model size) shows the effect is superlinear in repetition.

Why "quality" is relative. The classifier argument shows that every learned quality filter estimates a ratio against a reference you chose. There is no reference-free notion of quality in these pipelines; there are only choices of reference, and evaluations that reward some choices over others. Goodhart's law applies: once a benchmark defines the reference, filters will optimise for it.

The maths

MinHash collision probability. Let \(\pi\) be a uniformly random permutation of the shingle universe, and \(h_\pi(A) = \min_{a \in A} \pi(a)\).

\[ P\big[h_\pi(A) = h_\pi(B)\big] = \frac{|A \cap B|}{|A \cup B|} = J(A, B). \]
Derivation and the estimator's variance

Let \(x^\star = \arg\min_{x \in A\cup B} \pi(x)\). Under a random permutation \(x^\star\) is uniform on \(A \cup B\). If \(x^\star \in A\cap B\) both minima equal \(\pi(x^\star)\); if \(x^\star\) is in only one set, that set's minimum is \(\pi(x^\star)\) and the other's is larger. Hence \(P[h(A)=h(B)] = |A\cap B|/|A\cup B|\).

With \(k\) independent permutations, \(\hat J = \frac1k \sum_{j=1}^k \mathbf{1}[h_j(A)=h_j(B)]\) is a mean of \(k\) Bernoulli(\(J\)) variables: \(\mathbb{E}[\hat J] = J\) and \(\operatorname{Var}[\hat J] = J(1-J)/k\). At \(J = 0.8\), \(k = 112\): standard deviation \(\sqrt{0.16/112} \approx 0.038\). Hoeffding's inequality gives \(P(|\hat J - J| \ge \varepsilon) \le 2e^{-2k\varepsilon^2}\), so \(k \ge \ln(2/\delta)/(2\varepsilon^2)\) hashes guarantee error below \(\varepsilon\) with probability \(1-\delta\): for \(\varepsilon = 0.1\), \(\delta = 0.05\), \(k \ge 185\). (In practice \(h\) is a cheap universal hash such as \((ax+b) \bmod p\), which approximates a random permutation well enough.)

Shingle Jaccard under edits. Replace a random fraction \(f\) of the words in a document of \(m\) words. A word \(n\)-gram survives only if none of its \(n\) words was replaced, so a fraction \(q \approx (1-f)^n\) of shingles is shared. The intersection has about \(qm\) shingles and the union about \((2-q)m\), so

\[ J \approx \frac{q}{2-q}, \qquad q = (1-f)^n . \]

With \(n = 5\): \(f = 0.02\) gives \(J \approx 0.825\), \(f = 0.05\) gives \(0.631\), \(f = 0.10\) gives \(0.419\), matching the measured \(0.823\), \(0.626\) and \(0.415\) in Build it. Shingle Jaccard is far more sensitive than word overlap: changing one word in twenty already drops it to 0.63. That is why thresholds around 0.7 to 0.8 catch only light edits, and why the shingle size \(n\) is a real design choice (smaller \(n\) tolerates more edits but makes unrelated documents look similar).

Banding. Under independent hashes, a pair of similarity \(s\) agrees on all \(r\) rows of a band with probability \(s^r\), fails every one of \(b\) bands with probability \((1-s^r)^b\), hence

\[ P(s) = 1 - (1-s^r)^b . \]

The curve's midpoint satisfies \((1-s^r)^b = \tfrac12\); for large \(b\), \((1-s^r)^b \approx e^{-bs^r}\), so the midpoint is near \(s^r = \ln 2/b\), and the commonly quoted threshold \((1/b)^{1/r}\) is where \(bs^r = 1\), i.e. \(P = 1 - e^{-1} \approx 0.63\). The slope there grows with \(r\): for fixed \(b\), \(\left.\frac{dP}{ds}\right|_{s^\star} \approx r\, e^{-1} / s^\star\), so a sharper step needs longer bands, and keeping the threshold fixed then needs more bands, i.e. more hashes. That is the cost Lee et al. paid with \(k = 9{,}000\).

Bloom filter sizing. With \(m\) bits, \(h\) hash functions and \(n\) inserted items, a given bit is still zero with probability \((1-1/m)^{hn} \approx e^{-hn/m}\), so a new item is falsely reported present with probability

\[ p_{\text{fp}} \approx \left(1 - e^{-hn/m}\right)^h , \]

minimised at \(h = (m/n)\ln 2\), where \(p_{\text{fp}} = 2^{-h}\) and the memory needed is \(m/n = -\ln p_{\text{fp}}/(\ln 2)^2 \approx 1.44\log_2(1/p_{\text{fp}})\) bits per item. At 1%, that is 9.6 bits per item; for \(10^{11}\) paragraphs, about 120 GB, and every false positive deletes a unique paragraph.

Classifier odds as a density ratio. Train a classifier on \(n_1\) reference samples (label 1) and \(n_0\) raw samples (label 0). By Bayes' rule the Bayes-optimal classifier satisfies

\[ \frac{P(y=1\mid x)}{P(y=0\mid x)} = \frac{n_1\, p_{\text{ref}}(x)}{n_0\, p_{\text{raw}}(x)} \quad\Longrightarrow\quad \operatorname{logit}(x) = \log\frac{p_{\text{ref}}(x)}{p_{\text{raw}}(x)} + \log\frac{n_1}{n_0}. \]

Logistic regression minimises cross-entropy, whose population minimiser is this posterior, so with enough data and a flexible enough model its logit converges to the log density ratio plus a constant. Importance resampling draws raw documents with probability proportional to \(w(x) = p_{\text{ref}}(x)/p_{\text{raw}}(x) \propto e^{\operatorname{logit}(x)}\), and the resampled set is distributed as \(p_{\text{raw}}(x)\,w(x) \propto p_{\text{ref}}(x)\). A hard threshold instead keeps \(p_{\text{raw}}(x)\,\mathbf{1}[w(x) > \tau]\), which is not proportional to \(p_{\text{ref}}\): it discards the reference's own low-ratio regions and weights the rest by \(p_{\text{raw}}\), which is why top-\(k\) filtering distorts.

GPT-3's soft keep rule. NumPy's pareto(α) draws from a Lomax distribution with survival function \(P(X > t) = (1+t)^{-\alpha}\). Keeping a document when \(X > 1 - s\) gives

\[ P(\text{keep} \mid s) = (2 - s)^{-\alpha}, \qquad \alpha = 9:\quad s = 1 \to 1,\; s = 0.9 \to 0.42,\; s = 0.8 \to 0.19,\; s = 0.5 \to 0.026 . \]

A smooth, steep preference for high scores that still admits a few low-scoring documents: a middle path between resampling and a hard threshold.

In practice

  • Libraries. Hugging Face's datatrove (the FineWeb pipeline), AI2's Dolma toolkit, NVIDIA's NeMo Curator (GPU-accelerated deduplication and classifiers) and text-dedup (reference implementations of MinHash, SimHash, suffix arrays and Bloom filters).
  • Defaults that work. Word 5-gram shingles; about 100 to 250 hashes; a step near 0.75 to 0.8 Jaccard; deduplicate within each crawl before across crawls; normalise text (case, whitespace, digits) before exact hashing.
  • Keep the removed data and the scores. Store each document's filter decisions and scores rather than deleting, so a later ablation can change a threshold without re-running the crawl.
  • Look at samples at every threshold. Before trusting a filter, read 50 documents just above and 50 just below its threshold. Most bad filters are obvious within a page.

Common misconceptions

\"MinHash approximates edit distance\"

It estimates Jaccard similarity of shingle sets, which ignores order beyond the shingle length and counts. Two documents with the same paragraphs in a different order have Jaccard near 1.

\"A quality classifier detects quality\"

It detects resemblance to its positives. Swap the positives and "quality" changes meaning; see Gururangan et al. on whose language the GPT-3 filter preferred.

\"Deduplicate as hard as possible\"

Global deduplication across many crawls removed the good, often re-crawled pages and kept junk in FineWeb's experiments; and semantic deduplication can remove useful emphasis. Measure.

Build it

First, MinHash, LSH banding and union-find on synthetic documents (NumPy). Each "document" is 300 random word ids; copies are made by replacing a fraction of words, plus a chain of copies of copies.

import numpy as np
rng = np.random.default_rng(0)
P = (1 << 31) - 1                                  # prime modulus for hashing
V, L, K, B, R = 20_000, 300, 112, 14, 8            # vocab, doc length, hashes = bands x rows

def edit(doc, frac):                               # replace a fraction of words at random
    d = doc.copy(); idx = rng.choice(len(d), int(frac * len(d)), replace=False)
    d[idx] = rng.integers(0, V, len(idx)); return d

def shingles(doc, n=5):                            # word 5-grams -> integer ids in [0, P)
    g = np.lib.stride_tricks.sliding_window_view(doc, n).astype(np.int64)
    return np.unique((g * np.array([1, 31, 961, 29791, 923521])).sum(1) % P)

a, b = rng.integers(1, P, K), rng.integers(0, P, K)
def minhash(sh):                                   # K independent min-hashes
    return ((a[:, None] * sh[None, :] + b[:, None]) % P).min(1)

base = [rng.integers(0, V, L) for _ in range(200)]
docs, pairs = list(base), []                       # (original, copy, edit rate)
for i, f in enumerate([0.02, 0.05, 0.10, 0.20, 0.35] * 8):
    docs.append(edit(base[i], f)); pairs.append((i, len(docs) - 1, f))
for t in range(3): docs.append(edit(docs[-1] if t else docs[200], 0.02))  # copies of copies

S = [shingles(d) for d in docs]
M = np.stack([minhash(s) for s in S])              # signatures: (n_docs, K)
jac = lambda i, j: len(np.intersect1d(S[i], S[j])) / len(np.union1d(S[i], S[j]))

buckets = {}                                       # LSH: same band -> same bucket
for d, sig in enumerate(M):
    for band in range(B):
        buckets.setdefault((band, sig[band*R:(band+1)*R].tobytes()), []).append(d)
cand = {(x, y) for v in buckets.values() for x in v for y in v if x < y}

parent = list(range(len(docs)))                    # union-find over candidate pairs
def find(x):
    while parent[x] != x: parent[x] = parent[parent[x]]; x = parent[x]
    return x
for x, y in cand: parent[find(x)] = find(y)

print(f"docs={len(docs)}  candidate pairs={len(cand)}  clusters={len({find(d) for d in range(len(docs))})}")
print("edit   true J   MinHash J   flagged")
for f in [0.02, 0.05, 0.10, 0.20, 0.35]:
    ps = [(i, j) for i, j, g in pairs if g == f]
    tj = np.mean([jac(i, j) for i, j in ps]); ej = np.mean([(M[i] == M[j]).mean() for i, j in ps])
    print(f"{f:4.2f}   {tj:6.3f}   {ej:9.3f}   {np.mean([(i, j) in cand for i, j in ps]):7.2f}")
chain = [0, 200] + list(range(len(docs) - 3, len(docs)))   # original -> 4 successive 2% edits
print("chain J to neighbour:", [round(jac(u, v), 2) for u, v in zip(chain, chain[1:])],
      f"J(first,last)={jac(chain[0], chain[-1]):.2f}  same cluster: {find(chain[0]) == find(chain[-1])}")

Output:

docs=243  candidate pairs=16  clusters=231
edit   true J   MinHash J   flagged
0.02    0.823       0.833      1.00
0.05    0.626       0.608      0.12
0.10    0.415       0.417      0.00
0.20    0.202       0.209      0.00
0.35    0.058       0.068      0.00
chain J to neighbour: [0.82, 0.82, 0.82, 0.83] J(first,last)=0.47  same cluster: True

Three things to check against the maths: the MinHash estimates sit within about one standard deviation (\(\approx 0.04\)) of the true Jaccard; the flag rates follow the 14 × 8 S-curve (all pairs at 0.82, one in eight at 0.63, none below); and the chain shows transitive clustering merging documents only 47% similar.

Second, the classifier-as-density-ratio claim, in one dimension so you can see it. The "feature" stands for any quality signal; the reference is a tight distribution and the raw web is a wide mixture that contains 20% reference-like documents.

import numpy as np
rng = np.random.default_rng(1)
# One feature per document (think: a "how much it reads like a textbook" score).
# Reference ("good") text ~ N(1, 1); raw web = 20% reference-like + 80% junk ~ N(-1.5, 1.5^2).
ref = rng.normal(1.0, 1.0, 20_000)
is_good = rng.random(200_000) < 0.2
web = np.where(is_good, rng.normal(1.0, 1.0, 200_000), rng.normal(-1.5, 1.5, 200_000))

def feats(x): return np.stack([np.ones_like(x), x, x**2], 1)
X = feats(np.r_[ref, web[:20_000]]); y = np.r_[np.ones(20_000), np.zeros(20_000)]
w = np.zeros(3)
for _ in range(3000):                                  # logistic regression by gradient descent
    p = 1 / (1 + np.exp(-X @ w)); w -= 0.5 * X.T @ (p - y) / len(y)

def log_ratio(x):                                      # true log p_ref(x) / p_web(x)
    n = lambda x, m, s: np.exp(-0.5 * ((x - m) / s) ** 2) / s
    return np.log(n(x, 1, 1) / (0.2 * n(x, 1, 1) + 0.8 * n(x, -1.5, 1.5)))
for x in [-2.0, 0.0, 1.0, 2.0, 3.0]:
    print(f"x={x:5.1f}  classifier logit={(feats(np.array([x])) @ w)[0]:6.2f}  true log-ratio={log_ratio(x):6.2f}")

score = feats(web) @ w                                 # score every web document
top = web[score >= np.quantile(score, 0.8)]            # keep the top 20%
wts = np.exp(score); idx = rng.choice(len(web), 40_000, p=wts / wts.sum())  # importance resampling
for name, s in [("reference", ref), ("raw web", web), ("top-20% by score", top), ("importance resample", web[idx])]:
    print(f"{name:20s} mean={s.mean():5.2f}  std={s.std():4.2f}")
print(f"share of truly good docs: raw {is_good.mean():.2f}, top-20% {is_good[score >= np.quantile(score, 0.8)].mean():.2f}")

Output:

x= -2.0  classifier logit= -3.45  true log-ratio= -3.82
x=  0.0  classifier logit=  0.21  true log-ratio=  0.31
x=  1.0  classifier logit=  1.15  true log-ratio=  1.10
x=  2.0  classifier logit=  1.49  true log-ratio=  1.36
x=  3.0  classifier logit=  1.24  true log-ratio=  1.41
reference            mean= 0.99  std=0.99
raw web              mean=-1.00  std=1.73
top-20% by score     mean= 1.43  std=0.64
importance resample  mean= 1.02  std=0.98
share of truly good docs: raw 0.20, top-20% 0.66

The logit tracks the true log ratio (the quadratic feature cannot bend at the far right, where data are scarce). Importance resampling recovers the reference distribution almost exactly (mean 1.02, std 0.98 against 0.99 and 0.99). Keeping the top 20% raises the share of truly good documents from 20% to 66%, but its kept set is shifted (mean 1.43) and narrower than the reference (std 0.64): it has thrown away the reference's own diversity.

Things to try

  • Change B, R to 7, 16 and to 28, 4 and predict the flag rates from the S-curve before you run it.
  • Set the shingle size to 3 and to 9. How do the true Jaccard values per edit rate change, and does \(q/(2-q)\) with the new \(n\) still predict them?
  • Add a verification step: only merge candidate pairs whose true Jaccard exceeds 0.7. Does the chain still collapse into one cluster?
  • In the second snippet, keep the top 50% and the top 5%. Plot kept mean and std against the kept fraction: where does the distortion start?
  • Implement GPT-3's rule (rng.pareto(9, n) > 1 - p_score, with p_score the classifier's probability) and compare its kept distribution with the other two.

Check yourself

Prove that the probability two MinHash values agree equals the Jaccard similarity.

Under a random permutation the first element of \(A\cup B\) is uniform over the union. Both minima equal that element's rank exactly when it lies in \(A\cap B\), so the probability is \(|A\cap B|/|A\cup B|\).

With 20 bands of 10 rows, roughly where is the duplicate threshold, and what is P(candidate) at s = 0.9?

\(s^\star \approx (1/20)^{1/10} = e^{-\ln 20/10} \approx 0.74\). At \(s = 0.9\): \(0.9^{10} = 0.349\), \((1-0.349)^{20} = 0.651^{20} \approx 1.9\times10^{-4}\), so \(P \approx 0.9998\).

Why does replacing 5% of words drop 5-gram Jaccard to about 0.63?

Each replaced word destroys up to five shingles, so only \((0.95)^5 \approx 0.77\) of shingles survive; with intersection \(0.77m\) and union \(1.23m\), \(J \approx 0.63\).

Your Bloom filter must hold 5 × 10^10 paragraph hashes with a 0.1% false-positive rate. How much memory, and how many hash functions?

Bits per item \(= -\ln(0.001)/(\ln 2)^2 \approx 14.4\), so about \(7.2\times10^{11}\) bits, roughly 90 GB; optimal \(h = 14.4 \ln 2 \approx 10\) hash functions.

Why does keeping the top 10% by quality score narrow the distribution, while importance resampling does not?

Resampling with probability \(\propto p_{\text{ref}}/p_{\text{raw}}\) yields a sample distributed as \(p_{\text{ref}}\). Thresholding keeps only the region where the ratio is largest, which is the most stereotypical part of the reference, and drops the reference's own lower-ratio regions, so variety falls.

Two filtering pipelines differ by 0.4 points on an aggregate benchmark in 28B-token ablations. What do you need before believing it?

The seed-to-seed spread for that setup (FineWeb trained two seeds per dataset for this reason), confirmation that the benchmarks used have signal at that scale, and ideally a longer run, since the best filter changes with the training budget.

Hard: why might the optimal filter for a 7B model trained on 4T tokens differ from the optimal filter for the same model trained on 200B tokens?

With 200B tokens even an aggressive filter leaves enough unique data for about one epoch, so the cleanest slice wins. At 4T tokens that slice would be repeated many times and repeated tokens decay in value, so admitting more lower-quality but unseen data gives more effective tokens: Goyal et al.'s quality–quantity trade-off.

Hard: a cluster from transitive MinHash clustering contains 40,000 documents. What is probably happening, and what would you do?

A chain or template: many documents each near-duplicate to a neighbour (a templated site, a syndicated article with growing edits, boilerplate-heavy pages). Inspect samples; add a verification step on candidate pairs (true Jaccard or edit similarity), strip boilerplate before shingling, or cap cluster size and keep more than one representative.

Go deeper

Papers

Books and courses

Articles and code

Where this leads