# Pretraining Data Engineering: Filtering, Deduplication and Mixing

> A pretraining corpus is filtered, deduplicated and mixed step by step, and every step throws data away. This page shows what FineWeb, Gopher, DCLM and Llama 3 drop and why, then runs MinHash near-duplicate removal on a demo corpus: how many words may change before a copy stops counting.

- URL: https://dmxsf.com/en/wiki/pretraining/data-engineering/
- [DMXSF](https://dmxsf.com/en/about/)
- Intermediate
- Updated: 2026-11-22
- Tags: Pretraining, Data engineering

## After this page you will be able to

- Draw the pipeline from web pages to a training corpus, say what each step drops and on what evidence, and explain the choices with the public numbers of C4, Gopher, FineWeb and DCLM.
- Explain why MinHash is an unbiased estimator of Jaccard similarity, derive the banded hit probability 1−(1−s^r)^b, and pick the number of bands and rows for a similarity threshold.
- Use p* = 1−(2t/(1+t))^(1/n) to turn a similarity threshold into the share of words a copy may change, and name the blind spots of whole-document exact, near-duplicate and paragraph-level deduplication.
- Weigh global against per-snapshot deduplication (FineWeb's experiment and conjecture), and say how data mixture, annealing and repeated epochs (the effective-data formula) shape the final model.
- Write a checklist for a corpus pipeline: record what each step drops, inspect samples, ablate with small models, and check subsets for bias.

Pretraining data engineering is the chain of **lossy** steps that turns raw web pages, books and code into training tokens: extract the text, identify the language, filter with rules and models, deduplicate, and mix by proportion. Every step throws data away, and what is thrown away, and how much, often changes the result more than swapping the architecture. The public FineWeb gives a complete ledger: 96 Common Crawl snapshots leave about 36T tokens after base filtering, 20T after per-snapshot deduplication and 15T after further filtering; an educational-value classifier then picks 1.3T tokens, FineWeb-Edu, and the same 1.71B-parameter ablation model goes from 33% to 37% on MMLU (Penedo et al., 2024; [paper walkthrough](https://dmxsf.com/en/blog/the-fineweb-datasets-decanting-the-web-for-the-finest-text-data-at-scale/)).

This page follows the pipeline in order and says what each step drops and why, then puts the step that is hardest to reason about, near-duplicate removal (MinHash and locality-sensitive hashing, LSH), on a demo corpus you can run on a laptop, from estimation error to the method's blind spots. The [training pipeline](https://dmxsf.com/en/wiki/pretraining/training-pipeline/) page treats “data preparation” as one box; this page opens the box.

> [!NOTE] Experiment environment
> The five experiments run in one script, in order; the code blocks on this page, joined in sequence, are the full script. Environment: Apple M2 Max (64 GB), CPU only; Python 3.14.3 and NumPy 2.4.2, with nothing else besides the standard library's `hashlib` and no network access. All randomness is seeded: building documents, making edits and picking sources, and drawing hash multipliers each use an independent generator, so a rerun gives bit-identical numbers (a different NumPy version may change a digit or two). A full run takes under 10 seconds.
>
> **The corpus is synthetic demo data**: documents are sequences of integer “words” drawn from a 50,000-word vocabulary with a Zipf distribution (exponent 1.1). They have no meaning and none of the templates and boilerplate that fill real web pages. So the hit rates and false-merge counts below only illustrate the mechanism; they are not numbers for real web text.

## The pipeline at a glance

Common Crawl produces about 20 TB of extracted text per month, and most of it is not natural language but gibberish, menus, error pages and repeated text (Raffel et al., 2020). Public recipes are broadly similar: extract the text, then filter it with ever more expensive methods. The figure below is FineWeb's version, with numbers from the paper (GPT-2 tokens).

*Figure: Numbers from the FineWeb paper (Penedo et al., 2024): about 36T after base filtering, 20T after per-snapshot MinHash, 15T for the final FineWeb and 1.3T for FineWeb-Edu. The “kept” shares divide the paper's rounded numbers and are rough; the sixth step is an optional branch, not part of FineWeb itself.*

| Stage | What it does | What it drops | Evidence |
| --- | --- | --- | --- |
| Text extraction | Pull the main text out of raw pages (WARC) | Navigation bars, menus, ads and other page scaffolding | Trafilatura on WARC beat Common Crawl's own text version (WET) in ablations, because WET kept too much menu and boilerplate text |
| Base filtering | URL blocklist, language identification, quality and repetition rules | Adult sites, non-English pages, obvious junk | Part of RefinedWeb's setup plus Gopher's rules at their original thresholds; 96 snapshots leave about 36T tokens |
| Deduplication | Find duplicates and near-duplicates, keep one per group | Mirrors, templated pages, reposts | MinHash, run on each snapshot separately, leaves 20T |
| Heuristic filtering | C4's rules (without “lines must end in punctuation”) plus three custom rules | List pages without punctuation, pages with many repeated lines, pages with many short lines | Each rule ablated on a small model; 15T remain |
| Model scoring | A classifier scores “educational value” and keeps high scores | Low-information content | FineWeb-Edu, threshold 3, 1.3T remain |

The classifier is the most expensive step (scoring FineWeb's 15T tokens took 6,000 H100 GPU hours), so it runs last, on what the earlier steps leave. Every number here carries the same warning: **it is a choice, not a law**. Each FineWeb step comes with an ablation: a fixed Llama-style model with 1.71B parameters, 28B tokens for the filtering ablations and 350B for deduplication, two models per version, compared on the aggregate score of several benchmarks.

## Extraction and filtering

### Heuristic rules: cheap, explainable, and they misfire

Three public rule sets share one idea: put a threshold on a statistic of the document.

**C4 (Raffel et al., 2020)** was built from the April 2019 Common Crawl and came to about 750 GB:

- Keep only lines that end in terminal punctuation (a period, exclamation mark, question mark or closing quote) and have at least 5 words; drop any page with fewer than 3 sentences.
- Drop any page that contains a word from the “List of Dirty, Naughty, Obscene or Otherwise Bad Words”, the phrase “lorem ipsum” or a curly bracket `{`.
- Drop lines that mention Javascript or contain strings such as “terms of use”, “privacy policy” or “cookie policy”.
- Keep only one copy of any three-sentence span that occurs more than once, and drop pages that langdetect does not classify as English with probability at least 0.99.

**Gopher's MassiveWeb (Rae et al., 2021, appendix A)**:

- Drop documents with fewer than 50 or more than 100,000 words, or a mean word length outside 3 to 10 characters.
- Drop documents where the ratio of “#” symbols or ellipses to words exceeds 0.1, where more than 90% of the lines start with a bullet point or more than 30% end with an ellipsis, where fewer than 80% of the words contain an alphabetic character, or that contain fewer than two of the words the, be, to, of, and, that, have, with.
- Repetition: drop a document if the fraction of duplicated lines, or of duplicated paragraphs, exceeds 0.30; if the characters inside them exceed 0.20 of the text; if the most frequent 2-, 3- or 4-gram covers more than 0.20, 0.18 or 0.16 of the characters; or if duplicated 5- to 10-grams cover more than 0.15, 0.14, 0.13, 0.12, 0.11 or 0.10 respectively.
- Adult content is filtered with Google SafeSearch rather than a word list (see “Filtering introduces bias” below).

**FineWeb's three custom rules** came from a fairly systematic process: collect more than 50 document statistics, plot their histograms on the “good” (per-snapshot deduplicated) and “bad” (globally deduplicated) versions of the 2013-48 snapshot, pick the statistics whose distributions differ most, set thresholds by eye on the histograms, which gave 16 candidates, then ablate each on a small model trained on 28B tokens and keep three.

| Rule | Drop a document when | Tokens removed |
| --- | --- | --- |
| Line-ending punctuation | the fraction of lines ending in punctuation is at most 0.12 | 10.14% |
| Duplicate lines | the character fraction in duplicated lines is at least 0.1 | 12.47% |
| Short lines | the fraction of lines shorter than 30 characters is at least 0.67 | 3.73% |

Together the three remove about 22% of the tokens and raise the aggregate score by about 1%. C4's terminal-punctuation rule alone removes about 30% of the tokens, and FineWeb dropped it for removing too much while keeping the rest of C4's rules (about 7% removed in total). For the second rule the paper's text says 0.1 but its table 2 and the datatrove code use 0.01; the [FineWeb walkthrough](https://dmxsf.com/en/blog/the-fineweb-datasets-decanting-the-web-for-the-finest-text-data-at-scale/) checks this.

### Model scoring: classifiers rank documents

Rules see statistics, not content. The second layer uses models to score documents and keeps what scores well:

| Method | How | Result |
| --- | --- | --- |
| DCLM's fastText classifier (Li et al., 2024) | Positives are OpenHermes 2.5 instruction data and high-scoring r/ExplainLikeImFive posts, negatives are random web pages, about 400k documents split evenly; keep the top 10% by score | CORE 30.2 at 1B scale against 27.5 for a RefinedWeb reproduction; in the same table perplexity filtering 29.0, AskLLM 28.6, semantic deduplication (SemDedup) 27.1, top 20% by PageRank 26.1 |
| FineWeb-Edu | Llama-3-70B-Instruct scores 460,000 pages from 0 to 5; a linear regression head on a frozen embedding model (410k for training, 50k for validation); threshold 3, validation F1 82% | 1.3T tokens kept; a 1.71B model trained on 350B tokens goes from 33% to 37% on MMLU and from 46% to 57% on ARC |
| Llama 3 (Dubey et al., 2024) | A fastText model that predicts whether Wikipedia would reference a text, a DistilRoBERTa model trained on Llama 2's quality judgments, plus code and math classifiers; a knowledge classifier downsamples over-represented categories | The paper gives no ablation for each classifier separately |

A few observations:

- **What the positives are matters more than how complex the classifier is.** At 7B scale DCLM's instruction-data-plus-ELI5 positives give a CORE of 41.0, against 37.5 for the best of three conventional sources (Wikipedia, OpenWebText2, a GPT-3-like mix), about 3.5 points more; keeping the top 10% also beats the top 15% and 20% (39.8 and 38.7).
- **A cheap classifier on top of an expensive annotator.** FineWeb-Edu has the big model read only 460,000 pages and lets a linear head process everything else, which distills the big model's preferences into the whole corpus.
- **Classifiers have taste.** The FineWeb paper clusters the topics of FineWeb-Edu and FineWeb: education and history-culture-politics grow, while business-finance-law, entertainment-film and places-travel-real estate shrink. A threshold of 3 is a compromise between knowledge benchmarks and others such as HellaSwag, not a free gain.

### Filtering introduces bias

A word-list filter looks the safest and misfires the most. Dodge et al. (2021) analyzed C4's “bad words” list: of 50 clusters of excluded documents only 16 (31% of the excluded documents) are mostly sexual content, and the rest include science, medicine, health, law and politics; by dialect, African American English and Hispanic-aligned English documents are removed by the list at 42% and 32%, against 6.2% and 7.2% for White-aligned and other English. Gopher switched to SafeSearch for this reason. Before any filter ships, check which subsets it drops.

## Deduplication: why and how

### Why deduplicate

Lee et al. (2022) studied duplication systematically in C4, RealNews and other corpora and reached four conclusions:

- **Near-duplicates are more common than you would think.** Their NearDup finds 3.04% near-duplicate documents in C4 and 13.63% in RealNews; most are generated pages whose text is identical except for place names, business names and dates, which exact matching cannot see. One 61-word sentence is repeated verbatim 61,036 times in C4.
- **Duplicates make models memorize.** In a model trained on non-deduplicated data, more than 1% of the tokens it generates unprompted belong to memorized training sequences; after deduplication, verbatim reproduction is about ten times rarer.
- **Duplicates contaminate evaluation.** 4.6% of C4's validation examples and 14.4% of RealNews's have a near-duplicate in the training set.
- **Deduplication does not hurt.** Datasets get up to 19% smaller and perplexity is no worse, and in some cases up to 10% better.

### Three granularities

| Granularity | How | Catches | Misses |
| --- | --- | --- | --- |
| Whole-document exact | Hash the normalized full text; equal hashes mean duplicates | Identical copies (mirrors, repeated crawls) | A few changed words, or an added header or footer |
| Near-duplicate (MinHash plus LSH) | Compare the Jaccard similarity of n-gram sets | Copies with a few edited words, templated pages generated in bulk | A text pasted into a longer document, heavy rewriting |
| Paragraph, line or substring exact | Hash paragraphs or lines (CCNet, Llama 3), or find identical substrings of at least 50 tokens with a suffix array (Lee et al.'s ExactSubstr) | Copied paragraphs inside long documents, repeated headers and menus | Duplicates where every word differs a little |

The three complement each other, and real pipelines stack them. CCNet (Wenzek et al., 2019) estimated that duplicated paragraphs make up about 70% of the text in a Common Crawl snapshot; with 5 GB shards, deduplicating inside a shard leaves 42% of the characters and deduplicating across 100 shards leaves 28%. Llama 3 uses three layers: URL level (keep the most recent version of each page), global MinHash, and line level (drop lines that occur more than 6 times in each bucket of 30M documents); the paper admits that line-level deduplication also removes frequent high-quality text, but its empirical evaluation showed clear gains. The two methods of Lee et al. find largely overlapping content: 77% of the C4 examples NearDup removes contain at least one verbatim match of 50 tokens, and ExactSubstr removes 7.18% of C4's tokens.

### MinHash: estimating Jaccard similarity with minimum hashes

Cut document $d$ into a set $S_d$ of word n-grams (FineWeb uses $n=5$; they are also called shingles). The similarity of two documents is the Jaccard coefficient:

$$
J(A,B)=\frac{|S_A\cap S_B|}{|S_A\cup S_B|}
$$

Comparing every pair costs $O(N^2)$, which is out of reach. MinHash takes a hash function $h$ that maps n-grams to integers (equivalent to shuffling all n-grams into a random order) and records $m_A=\min_{x\in S_A}h(x)$. The element of $S_A\cup S_B$ with the smallest hash is equally likely to be any element of the union; $m_A=m_B$ only when it lies in the intersection. So

$$
\Pr[m_A=m_B]=\frac{|S_A\cap S_B|}{|S_A\cup S_B|}=J(A,B)
$$

With $k$ independent hash functions and one minimum per function you get a **signature** of length $k$. The fraction $\hat J$ of positions where two signatures agree is an unbiased estimate of $J$: each position is a Bernoulli trial with success probability $J$, so the variance is $J(1-J)/k$. Those are the two facts experiment 1 checks: the mean equals $J$ and the standard deviation shrinks as $1/\sqrt{k}$.

A signature has fixed size: however long the document, it is $k$ integers. FineWeb's $k=112$ makes 896 bytes per document.

### Banded LSH: from “compare all pairs” to “look up buckets”

You still cannot compare every pair of signatures. Locality-sensitive hashing (LSH) cuts the signature into $b$ bands of $r$ values ($k=br$), hashes the $r$ values of a band together into a **bucket id**, and makes two documents candidates if they share a bucket id in **any band**. Now you only place documents into buckets and compare those that share one, at a cost linear in the number of documents.

*Figure: A randomly generated schematic (fixed seed); a cell is green with probability J. In the left panel 4 of the 14 bands are all green, so the pair lands in the same bucket and becomes a candidate duplicate; the right panel has none and the pair is never compared.*

For a pair with Jaccard similarity $s$, one band matches in full with probability $s^r$, and at least one of the $b$ bands matches with probability

$$
P(s)=1-\left(1-s^{r}\right)^{b}
$$

This is an S-shaped curve whose steepest point is at $s\approx(1/b)^{1/r}$. Choosing $(b,r)$ chooses the curve, that is, how similar counts as a duplicate and how much you pay:

The widget below makes this curve draggable: load one of experiment 2's four configs or drag the bands b and rows r yourself to see the S-curve, its steepest point and the signature cost change; the lower panel converts a similarity threshold into the tolerable fraction of changed words (experiment 3's p* formula).

- FineWeb uses $b=14$, $r=8$ ($k=112$); the midpoint is about 0.72 and the hit probability at $s=0.75$ is 77%. The paper's appendix gives 56%, 77%, 92% and 98.8% at $s=0.70$, 0.75, 0.80 and 0.85; the [walkthrough](https://dmxsf.com/en/blog/the-fineweb-datasets-decanting-the-web-for-the-finest-text-data-at-scale/) recomputes them and checks the curve with a simulation of 6,000 document pairs.
- Lee et al. use 5-grams and a signature of $k=9{,}000$ with 20 values per band and 450 bands (the letters $b$ and $r$ mean the opposite in their paper); the curve is much steeper, at about 80 times the signature size, and they confirm every candidate pair with the true Jaccard similarity and an edit similarity (threshold 0.8). RefinedWeb's setup is also 9,000 hashes in 450 bands of 20 (FineWeb's appendix). FineWeb chose a much cheaper setup and clusters candidate pairs transitively (if A matches C and B matches C, then A, B and C form one cluster), keeping one random document per cluster.

### How “near” is near?

The threshold is a Jaccard similarity, but what you want to know is how many words can change before a copy stops counting. The conversion depends on the n-gram length. Replace each word with probability $p$ by a word that never appeared; an n-gram survives with probability $q=(1-p)^n$. With two sets of similar size, the intersection is about a fraction $q$ and the union about $2-q$, so

$$
J\approx\frac{q}{2-q},\qquad q=(1-p)^{n}
$$

and the largest share of words you can change while keeping $J\ge t$ is

$$
p^{*}=1-\left(\frac{2t}{1+t}\right)^{1/n}
$$

The larger $n$ is, the more n-grams a given share of edits destroys, and the fewer edits are tolerated. 5-grams with a 0.75 threshold (FineWeb) tolerate only about 3% changed words, and 13-grams with 0.8 (Gopher) less than 1%; the numbers are in experiment 3. To catch looser duplicates you must lower $n$ or the threshold, at the price of merging documents that are truly different and merely share templates and boilerplate.

### Scope, and which copy to keep

FineWeb ran an instructive experiment. First it deduplicated **globally** across all 96 snapshots with MinHash (starting from the most recent snapshot and working backwards, each snapshot compared with all the newer ones already processed). The oldest snapshots lost up to 90%, only 4T tokens remained, and a model trained on 350B of them was barely better than one trained on non-deduplicated data and far below RefinedWeb. To find out why, they trained two models on the old 2013-48 snapshot: one on the data that deduplication kept, one on the data it removed. The part that was kept (the paper says about 10% of the original data, though its own figures of 31B and 460B tokens give 6.3%; the walkthrough explains) turned out to be worse than the part that was removed, and visual inspection found more ads, keyword stuffing and badly formatted text in what had been kept.

Deduplicating **each snapshot on its own** (20T) matched RefinedWeb. The paper's conjecture is that most of the gain comes from removing the huge clusters of duplicates, hundreds of thousands of documents that appear in every crawl, and that removing small clusters of a few duplicates can hurt. Llama 3 describes global MinHash across its whole dataset and does not publish an ablation of that choice; the two reports differ in sources, filter order and later processing and cannot be compared directly. There is no universal answer: **the scope of deduplication is a hyperparameter you have to ablate on your own data.**

Which copy to keep is a choice too. FineWeb keeps a random one per cluster and Gopher removes a random one of each pair; Llama 3's URL-level step keeps the most recent version of a page. A finer rule keeps the highest-quality copy, which needs a quality score first.

## Mixture, annealing and repetition

Deduplication and filtering decide what is in the corpus; the mixture decides how much each source contributes, and annealing and repetition decide order and number of passes.

| Practice | Example |
| --- | --- |
| Downsample over-represented categories | Llama 3 trained a knowledge classifier to downsample categories that are over-represented on the web, such as arts and entertainment |
| Predict the large model's mixture with small models | Llama 3 trained several small models on different mixtures, used scaling laws to predict a large model's results on each, then trained a larger model on a candidate mixture to check; the final mix is roughly 50% general knowledge, 25% math and reasoning, 17% code, 8% multilingual |
| A learned mixture | DoReMi (Xie et al., 2023) learns domain weights with Group DRO on a 280M proxy model and uses them to train an 8B model, 30 times larger; on The Pile the average few-shot accuracy rises by 6.5 points and the baseline accuracy is reached with 2.6 times fewer training steps |
| Annealing | At the end of training, decay the learning rate linearly to 0 while raising the share of high-quality code and math data. For Llama 3 this improved the 8B model on the GSM8k and MATH validation sets by 24.0% and 6.4% (the paper does not say whether absolute or relative) and did almost nothing for the 405B model; annealing is also used to rate small datasets: anneal a half-trained 8B model on 40B tokens, with 30% weight on the new dataset |

The [training pipeline](https://dmxsf.com/en/wiki/pretraining/training-pipeline/) page runs a mixture experiment on a 0.86M-parameter model. When high-quality human text runs short, besides repeating data a model can rewrite or generate it; when that helps and when it collapses is covered in [Synthetic data and self-improvement](https://dmxsf.com/en/wiki/frontier/synthetic-data-and-self-improvement/).

**What is repeated data worth?** High-quality data is scarce, so it is often repeated. Muennighoff et al. (2023) fitted an “effective data” formula from many controlled experiments: with $U$ unique tokens repeated $R$ times ($R+1$ epochs in total),

$$
D'=U+U\,R^{*}\left(1-e^{-R/R^{*}}\right)
$$

where $R^{*}$ is a fitted decay constant of about 15. For $R\ll R^{*}$, $D'\approx U(1+R)$ and repeated data is worth almost as much as fresh data; for large $R$, $D'$ approaches $U(1+R^{*})$, so no amount of repetition beats $1+R^{*}$ copies of fresh data. Their example: an 8.7B-parameter model trained for 4 epochs on 44B unique tokens ends with a validation loss only 0.5% higher than one trained for a single epoch on 178B unique tokens. The takeaway is that at a fixed compute budget about 4 repeats are nearly lossless, repeating still pays off up to about 16 epochs, and returns decay quickly after that; experiment 5 tabulates the formula.

## Contamination and privacy

- **Evaluation contamination belongs in the pipeline, not in a clean-up afterwards.** Gopher computes the 13-gram Jaccard similarity between training and test documents and drops training documents above 0.8; GPT-3 dropped training examples that share a 13-gram with an evaluation example. Detecting contamination, and its blind spots, is covered in [LLM evaluation](https://dmxsf.com/en/wiki/evaluation/llm-evaluation/); keeping an evaluation set's labels clean, private and versioned is covered in [Building Evaluation Sets](https://dmxsf.com/en/wiki/evaluation/building-eval-sets/).
- **Personal information.** FineWeb's release anonymizes email addresses and public IP addresses; Llama 3 filters websites known to hold large amounts of personal information at the domain level.

## Hands-on: run deduplication on a demo corpus

The experiments verify the concepts above in turn: MinHash's estimation error (experiment 1), the banded S-curve and its cost (experiment 2), how many changed words can still be caught (experiment 3), which duplicates escape (experiment 4), and the effective data of repeated training (experiment 5).

### Setup: build a corpus

A document is a sequence of integer “words” with Zipf word frequencies, in paragraphs of 25 to 45 words and 6 to 10 paragraphs per document. `mults(k)` uses “multiply by a random odd number modulo $2^{64}$” as $k$ hash functions: multiplying by an odd number is a permutation of the 64-bit integers, which reorders the n-grams, and the minimum under that order is the min-hash. It is a teaching simplification and not a strictly min-wise independent family; experiment 1 checks its mean and variance.

```python
"""Pretraining dedup: MinHash, banding and three dedup tools (demo data)."""
import hashlib
import platform
from collections import Counter

import numpy as np

V = 50_000                               # vocabulary size
cdf = np.cumsum(1 / np.arange(1, V + 1) ** 1.1)
cdf /= cdf[-1]                           # Zipf word frequencies, exponent 1.1
cdf[-1] = 1.0
# three independent random generators
r_doc = np.random.default_rng(7)         # builds documents
r_edit = np.random.default_rng(13)       # edits, picks sources
r_hash = np.random.default_rng(11)       # hash multipliers

def h64(text):
    d = hashlib.blake2b(text.encode(), digest_size=8).digest()
    return int.from_bytes(d, "little")

def mults(k):
    """k odd multipliers: x -> m*x mod 2^64 is a permutation, used as one."""
    m = r_hash.integers(0, 2**63, size=k, dtype=np.uint64)
    return m * np.uint64(2) + np.uint64(1)

def shingles(words, n=5):
    return {h64(" ".join(map(str, words[i:i + n])))
            for i in range(len(words) - n + 1)}

def signature(sh, mult):
    x = np.fromiter(sh, dtype=np.uint64, count=len(sh))
    return (x[:, None] * mult).min(axis=0)       # minimum for every hash

def jaccard(a, b):
    return len(a & b) / len(a | b)

def para(n):
    return [int(w) for w in np.searchsorted(cdf, r_doc.random(n))]

def new_doc(n_par=None):
    n_par = n_par or int(r_doc.integers(6, 11))
    return [para(int(r_doc.integers(25, 46))) for _ in range(n_par)]

def flat(doc):
    return [w for par in doc for w in par]

def edit(doc, p):
    """Replace each word, with probability p, by a never-seen new word."""
    return [[int(r_edit.integers(V, 10**9)) if r_edit.random() < p else w
             for w in par] for par in doc]

print(f"Python {platform.python_version()}, NumPy {np.__version__}")
base = [new_doc() for _ in range(2000)]
n_words = [len(flat(d)) for d in base]
print(f"{len(base)} documents, {np.mean(n_words):.0f} words on average, "
      f"shortest {min(n_words)}, longest {max(n_words)}")
```

```text
Python 3.14.3, NumPy 2.4.2
2000 documents, 280 words on average, shortest 172, longest 410
```

### Experiment 1: the estimation error of a signature

Build two sets of 450 elements each, with intersections of 225, 300 and 400 elements, so that $J=1/3$, $1/2$ and $4/5$. Estimate $J$ from the first $k$ of 512 shared hashes ($k=16$, 64, 112, 512), repeat 300 times, and compare the mean and standard deviation with the theory, $\sqrt{J(1-J)/k}$.

```python
N = 450                                  # 450 elements per set
print("    s     k   mean est.  std     theory sqrt(s(1-s)/k)")
for s, c in ((1 / 3, 225), (1 / 2, 300), (4 / 5, 400)):   # c = intersection
    est = {k: [] for k in (16, 64, 112, 512)}
    for _ in range(300):
        ids = r_hash.integers(0, 2**63, size=2 * N - c, dtype=np.uint64)
        a, b = ids[:N], ids[N - c:]                  # intersection ids[N-c:N]
        m = mults(512)
        eq = (a[:, None] * m).min(axis=0) == (b[:, None] * m).min(axis=0)
        for k in est:
            est[k].append(eq[:k].mean())             # estimate from first k
    for k, v in est.items():
        print(f"{s:.3f} {k:4d}   {np.mean(v):.4f}    {np.std(v):.4f}   "
              f"{(s * (1 - s) / k) ** 0.5:.4f}")
```

```text
    s     k   mean est.  std     theory sqrt(s(1-s)/k)
0.333   16   0.3396    0.1132   0.1179
0.333   64   0.3359    0.0562   0.0589
0.333  112   0.3328    0.0424   0.0445
0.333  512   0.3325    0.0203   0.0208
0.500   16   0.5019    0.1191   0.1250
0.500   64   0.4985    0.0613   0.0625
0.500  112   0.5025    0.0446   0.0472
0.500  512   0.4996    0.0221   0.0221
0.800   16   0.7996    0.1019   0.1000
0.800   64   0.8002    0.0491   0.0500
0.800  112   0.7982    0.0373   0.0378
0.800  512   0.7988    0.0181   0.0177
```

How to read it:

- **The mean sits on the truth.** In all 12 rows the mean estimate agrees with $J$; there is no systematic bias.
- **The standard deviation matches theory.** Every row is within 6% of $\sqrt{J(1-J)/k}$, and the standard deviation of 300 repeats has a sampling error of about 4% itself, so the agreement is the formula holding. Four times the hashes (16 to 64) roughly halves the standard deviation.
- **One pair's estimate is coarse.** At $k=112$ and $J=0.5$ the standard deviation is 0.0446. LSH is therefore not designed to estimate each pair's $J$ accurately, only to ensure that a similar pair collides in at least one of enough bands.

### Experiment 2: the banded S-curve and its cost

Compute $P(s)=1-(1-s^r)^b$ for four setups at several similarities: FineWeb's 14×8, Lee et al.'s 450×20, and two bad setups with the same 128 hashes (32×4 and 8×16). The last column is the signature size per document in bytes (8 bytes per hash).

```python
K, B, R = 112, 14, 8                     # FineWeb: 112 hashes = 14 bands x 8

def p_dup(s, b, r):
    """P(two docs with Jaccard s share at least one band of r hashes)."""
    return 1 - (1 - s**r) ** b

print(f"{'config':<30}{'b':>4}{'r':>5}{'k':>6}{'thr':>7}{'P(.5)':>7}"
      f"{'P(.6)':>7}{'P(.7)':>7}{'P(.75)':>7}{'P(.8)':>7}{'P(.9)':>7}"
      f"{'bytes/doc':>11}")
for name, b, r in (("FineWeb", 14, 8), ("Lee et al. / RefinedWeb", 450, 20),
                   ("k=128, too many bands", 32, 4),
                   ("k=128, too few bands", 8, 16)):
    ps = "".join(f"{p_dup(s, b, r):7.3f}" for s in (.5, .6, .7, .75, .8, .9))
    print(f"{name:<30}{b:4d}{r:5d}{b * r:6d}{(1 / b) ** (1 / r):7.3f}{ps}"
          f"{b * r * 8:11d}")
print(f"Signatures for 1e9 docs: FineWeb {112 * 8 * 1e9 / 1e9:.0f} GB, "
      f"Lee et al. {9000 * 8 * 1e9 / 1e12:.0f} TB")
```

```text
config                           b    r     k    thr  P(.5)  P(.6)  P(.7) P(.75)  P(.8)  P(.9)  bytes/doc
FineWeb                         14    8   112  0.719  0.053  0.211  0.565  0.772  0.924  1.000        896
Lee et al. / RefinedWeb        450   20  9000  0.737  0.000  0.016  0.302  0.761  0.995  1.000      72000
k=128, too many bands           32    4   128  0.420  0.873  0.988  1.000  1.000  1.000  1.000       1024
k=128, too few bands             8   16   128  0.878  0.000  0.002  0.026  0.077  0.204  0.806       1024
Signatures for 1e9 docs: FineWeb 896 GB, Lee et al. 72 TB
```

How to read it:

- **FineWeb's curve is wide and cheap.** At $J=0.5$ a pair is still merged with probability 0.053; the probability is 0.565 at $J=0.7$, 0.772 at 0.75 and 0.924 at 0.8 (the paper's appendix says 56%, 77% and 92%). Lee et al.'s 450×20 is almost zero at 0.5 and 0.995 at 0.8, but needs 72,000 bytes per document, about 80 times FineWeb; for a billion documents the signatures come to 896 GB and 72 TB.
- **The same number of hashes with a different $(b,r)$ is a completely different curve.** 32×4 merges pairs with probability 0.873 already at 0.5, lumping documents that are only half similar; 8×16 catches only 0.204 at 0.8 and misses many near-duplicates.
- **A threshold is not a switch.** “Target 75%” names the curve's midpoint; it does not mean “everything above 75% is deleted and everything below is kept”.

### Experiment 3: how many changed words can still be caught

Take the first 200 documents and replace each word with probability $p$ by a word that never appeared. Compute the true Jaccard similarity for 3-, 5- and 13-grams and compare it with the closed form $q/(2-q)$; then count how often 14×8 banding catches the 5-gram copies and compare with the formula's prediction. Finally convert a few common settings with the $p^*$ formula.

```python
docs = base[:200]
sets = {n: [shingles(flat(d), n) for d in docs] for n in (3, 5, 13)}
M = mults(K)
sig0 = [signature(s, M).reshape(B, R) for s in sets[5]]
print("edit rate  J(n=3)  J(n=5)  J(n=13)  caught(measured)  caught(formula)")
worst = 0.0
for p in (0.005, 0.01, 0.02, 0.03, 0.04, 0.06, 0.08):
    js = {n: [] for n in sets}
    hit, pred = [], []
    for i, d in enumerate(docs):
        e = flat(edit(d, p))
        for n in js:
            js[n].append(jaccard(sets[n][i], shingles(e, n)))
        se = signature(shingles(e), M).reshape(B, R)
        hit.append((se == sig0[i]).all(axis=1).any())
        pred.append(p_dup(js[5][-1], B, R))
    row = {n: np.mean(v) for n, v in js.items()}
    for n, j in row.items():
        q = (1 - p) ** n
        worst = max(worst, abs(j - q / (2 - q)))
    print(f"{p:7.1%}    {row[3]:.3f}   {row[5]:.3f}   {row[13]:.3f}"
          f"    {np.mean(hit):12.1%}    {np.mean(pred):13.1%}")
print(f"Largest gap to J=q/(2-q), q=(1-p)^n: {worst:.4f}")
print("\nMost words you can change while J>=t: p* = 1-(2t/(1+t))^(1/n)")
for n, t, who in ((5, .75, "FineWeb"), (5, .8, "Lee et al."),
                  (13, .8, "Gopher"), (3, .75, "for comparison")):
    ps = 1 - (2 * t / (1 + t)) ** (1 / n)
    print(f"  n={n:2d}  t={t:.2f}  p*={ps:.2%}  about 1 word in {1 / ps:.0f}"
          f"  ({who})")
```

```text
edit rate  J(n=3)  J(n=5)  J(n=13)  caught(measured)  caught(formula)
   0.5%    0.970   0.950   0.881          100.0%            99.9%
   1.0%    0.944   0.910   0.793           98.0%            99.1%
   2.0%    0.893   0.832   0.644           91.5%            92.1%
   3.0%    0.840   0.755   0.513           71.5%            73.9%
   4.0%    0.800   0.699   0.435           58.5%            56.6%
   6.0%    0.708   0.579   0.293           23.0%            20.8%
   8.0%    0.639   0.493   0.204            6.5%             6.8%
Largest gap to J=q/(2-q), q=(1-p)^n: 0.0191

Most words you can change while J>=t: p* = 1-(2t/(1+t))^(1/n)
  n= 5  t=0.75  p*=3.04%  about 1 word in 33  (FineWeb)
  n= 5  t=0.80  p*=2.33%  about 1 word in 43  (Lee et al.)
  n=13  t=0.80  p*=0.90%  about 1 word in 111  (Gopher)
  n= 3  t=0.75  p*=5.01%  about 1 word in 20  (for comparison)
```

*Figure: Left: drawn from P = 1−(1−s^r)^b. Right: J = q/(2−q) with q = (1−p)^n, fed into the same P (14 bands × 8 rows); the dots come from the output of experiment 3. At the same threshold, longer shingles tolerate fewer edits.*

How to read it:

- **The closed form matches.** The largest gap between the measured Jaccard similarity and $q/(2-q)$ across all three n-gram sizes and all $p$ is 0.0191.
- **The catch rate goes from almost always to almost never within a few points of edits.** For 5-grams it is 98.0% at 1%, 71.5% at 3% and 6.5% at 8%. The biggest gap between the measurement and the formula is at 3% (71.5% against 73.9%); each $p$ uses only 200 documents, so the rate itself has a sampling error of about 3 points, and the gap is within the noise.
- **A larger n is stricter.** At $p=3\%$ the Jaccard similarity is 0.840 for 3-grams, 0.755 for 5-grams and only 0.513 for 13-grams.
- **The $p^*$ conversions.** FineWeb's 5-grams with 0.75 tolerate only 3.04% changed words, about one in 33; Lee et al.'s 0.8 gives 2.33%; Gopher's 13-grams with 0.8 give 0.90%, about one in 111 (Gopher did not publish banding parameters, so this uses the exact Jaccard threshold); 3-grams give 5.01%.

### Experiment 4: which duplicates escape

Make 600 copies, 100 of each of six kinds, each from a different source document: identical; 1%, 3% or 8% of the words replaced (with at least one word changed); the same 40-word header and the same 40-word footer added; and the source pasted into a new 26-paragraph document. Mix them with the 2,000 originals and deduplicate with three methods:

1. **Whole-document exact**: the hash of the normalized full text is equal.
2. **MinHash**: 14×8 banding, documents sharing a bucket are merged with union-find, and a copy is caught if it lands in the same cluster as its source; repeat with 30 sets of hash functions and report the mean and the minimum and maximum.
3. **Paragraph exact**: keep each paragraph only at its first occurrence in the whole corpus and count the share of the copy's “copied words” that is removed.

The “formula” column averages $P(s)$ evaluated at each pair's true Jaccard similarity. “Combined” deletes the copies MinHash catches and applies paragraph-level deduplication to those it misses.

```python
HEAD, FOOT = para(40), para(40)          # header and footer templates

def edited(d, p):
    while True:                          # at least one edit, else it is exact
        e = edit(d, p)
        if e != d:
            return e, sum(w < V for w in flat(e))   # words left untouched

def embed(d):
    longer = new_doc(26)                 # 26 new paragraphs, copy goes inside
    at = int(r_edit.integers(0, 27))
    return longer[:at] + d + longer[at:]

KINDS = [
    ("identical copy", lambda d: (d, len(flat(d)))),
    ("1% of words edited", lambda d: edited(d, 0.01)),
    ("3% of words edited", lambda d: edited(d, 0.03)),
    ("8% of words edited", lambda d: edited(d, 0.08)),
    ("header + footer", lambda d: ([HEAD] + d + [FOOT], len(flat(d)))),
    ("embedded in long doc", lambda d: (embed(d), len(flat(d)))),
]
src_ids = r_edit.permutation(len(base))[:100 * len(KINDS)]
corpus, meta = list(base), []        # meta: (kind, source, copy, copied words)
for j, (name, make) in enumerate(KINDS):
    for i in src_ids[j * 100:(j + 1) * 100]:
        dup, n_copy = make(base[i])
        corpus.append(dup)
        meta.append((j, int(i), len(corpus) - 1, n_copy))
print(f"{len(base)} originals plus {len(meta)} copies, "
      f"{len(corpus)} documents")
```

```text
2000 originals plus 600 copies, 2600 documents
```

```python
# Method 1: exact whole-document dedup (hash the text, drop repeats)
doc_key = [h64(" ".join(map(str, flat(d)))) for d in corpus]
first = {}
for i, k in enumerate(doc_key):
    first.setdefault(k, i)
exact_dup = [first[k] != i for i, k in enumerate(doc_key)]

# Method 2: MinHash + banding; documents sharing a band bucket are merged
shs = [shingles(flat(d)) for d in corpus]

def minhash_clusters(mult):
    parent = list(range(len(corpus)))

    def find(i):
        while parent[i] != i:
            parent[i] = parent[parent[i]]
            i = parent[i]
        return i

    bucket = {}
    for i, sh in enumerate(shs):
        sg = signature(sh, mult).reshape(B, R)
        for b in range(B):
            key = (b, sg[b].tobytes())
            if key in bucket:
                parent[find(i)] = find(bucket[key])
            else:
                bucket[key] = i
    return [find(i) for i in range(len(corpus))]

draws = [minhash_clusters(mults(K)) for _ in range(30)]  # 30 hash sets

# Method 3: paragraph-level exact dedup (keep the first occurrence)
par_key = [[h64(" ".join(map(str, p))) for p in d] for d in corpus]
seen, dropped = set(), []
for keys in par_key:
    dropped.append([k in seen for k in keys])
    seen.update(keys)

mh = [[[] for _ in KINDS] for _ in draws]      # [hash set][kind] -> hits
ex, pa, both, fm = ([[] for _ in KINDS] for _ in range(4))
for j, i, c, n_copy in meta:
    mine = set(par_key[i])
    gone = sum(len(p) for p, k, dr in zip(corpus[c], par_key[c], dropped[c])
               if dr and k in mine)      # count only paragraphs from source
    ex[j].append(float(exact_dup[c]))
    fm[j].append(p_dup(jaccard(shs[i], shs[c]), B, R))   # formula
    pa[j].append(gone / n_copy)
    hits = [cl[c] == cl[i] for cl in draws]
    for d, h in enumerate(hits):
        mh[d][j].append(float(h))
    both[j].append(np.mean([1.0 if h else gone / n_copy for h in hits]))
print("Share of copied words removed (100 copies per kind, 30 hash sets)")
print(f"{'kind':<24}{'exact':>8}{'MinHash':>9}{'formula':>9}{'range':>11}"
      f"{'paragraph':>11}{'combined':>10}")
for j, (name, _) in enumerate(KINDS):
    per = [np.mean(mh[d][j]) for d in range(len(draws))]
    rng_ = f"{min(per):.0%}-{max(per):.0%}"
    print(f"{name:<24}{np.mean(ex[j]):8.0%}{np.mean(per):9.0%}"
          f"{np.mean(fm[j]):9.0%}{rng_:>11}{np.mean(pa[j]):11.0%}"
          f"{np.mean(both[j]):10.0%}")
L = np.arange(25, 46)                    # paragraphs of 25-45 words, uniform
print("Chance a paragraph survives unedited (word-weighted): " + ", ".join(
    f"{p:.0%} -> {(L * (1 - p) ** L).sum() / L.sum():.3f}"
    for p in (.01, .03, .08)))
cnt = Counter(draws[0][:len(base)])
print(f"Originals wrongly merged with another original: "
      f"{sum(v for v in cnt.values() if v > 1)}")
```

```text
Share of copied words removed (100 copies per kind, 30 hash sets)
kind                       exact  MinHash  formula      range  paragraph  combined
identical copy              100%     100%     100%  100%-100%       100%      100%
1% of words edited            0%      99%      99%   97%-100%        70%       99%
3% of words edited            0%      72%      73%    61%-79%        36%       79%
8% of words edited            0%       8%       8%     3%-14%         7%       13%
header + footer               0%      82%      83%    55%-98%       100%      100%
embedded in long doc          0%       0%       0%      0%-1%       100%      100%
Chance a paragraph survives unedited (word-weighted): 1% -> 0.697, 3% -> 0.339, 8% -> 0.056
Originals wrongly merged with another original: 0
```

How to read it:

- **Whole-document exact deduplication catches only identical copies.** It catches none of the other five kinds.
- **MinHash agrees with the formula, kind by kind.** It catches almost every copy with 1% of words changed (99%), about 72% at 3%, only 8% at 8%, and 0% for the pasted text.
- **Paragraph exact deduplication covers MinHash's blind spot and has its own.** With a header and footer, or pasted into a longer document, it catches 100%; but for copies with edited words it catches only the paragraphs that were not touched. The chance that a paragraph survives unedited falls fast with $p$ (word-weighted: 0.697, 0.339 and 0.056 at 1%, 3% and 8%), which agrees within sampling error with the measured 70%, 36% and 7%.
- **Combining them is best, but heavy edits still escape.** At 8% changed words even the combination catches only 13%. Such duplicates need a smaller n, a looser threshold, or embedding-based semantic deduplication (DCLM tried SemDedup at 1B scale and got a CORE of 27.1, no better than the 27.5 of the RefinedWeb reproduction).
- **A single MinHash run is unreliable.** For “header + footer” the 30 hash sets range from 55% to 98%. The 100 copies share the same header and footer, so when the hash functions happen to give some n-grams of the template very small values, all the copies are affected together and their outcomes are correlated.
- **Do not read “0 originals wrongly merged” as a real false-positive rate.** The demo originals share almost no 5-grams, while real web pages are full of templates and boilerplate.

> [!NOTE] Two things I adjusted in the experiment design
> - The first version of the script drew one set of hash functions and measured 34% for the header-and-footer kind, far from the formula; the cause was the correlation from the shared template, so I switched to 30 independent sets and report the mean and range.
> - In the first version about 6% of the “1% changed” copies had no word changed at all, which makes them identical copies that whole-document exact matching caught, and it raised that kind's exact-match recall to 8%; the script now guarantees that every copy has at least one changed word.
>
> With 100 copies per kind the sampling error of a share is about ±5 points; do not interpret differences smaller than that.

### Experiment 5: what repeated passes are worth in fresh data

List how much fresh data $E$ epochs are worth by the formula of Muennighoff et al. ($R^*=15$).

```python
R_STAR = 15                              # fitted R_D* of the paper, ~15 repeats

def effective(epochs, r_star=R_STAR):
    """Fresh-data equivalent (in multiples) of data repeated `epochs` times."""
    r = epochs - 1
    return 1 + r_star * (1 - np.exp(-r / r_star))

print("epochs  effective fresh data  share")
for e in (1, 2, 4, 8, 16, 40):
    print(f"{e:6d}  {effective(e):17.2f}x  {effective(e) / e:6.1%}")
```

```text
epochs  effective fresh data  share
     1               1.00x  100.0%
     2               1.97x   98.4%
     4               3.72x   93.0%
     8               6.59x   82.4%
    16              10.48x   65.5%
    40              14.89x   37.2%
```

Four epochs are worth 3.72 copies of fresh data (93.0% of the tokens still count), 8 epochs 6.59 (82.4%), 16 epochs 10.48 (65.5%) and 40 epochs only 14.89 (37.2%). The formula's asymptote is $1+R^*=16$ copies: however often you repeat, you never beat 16 copies of fresh data. The formula was fitted for the paper's setup (GPT-2 architecture, up to 9B parameters and 900B training tokens, data-constrained training); with other model sizes and data types $R^*$ will change, and this experiment only turns the formula into a table.

## Practical checklist

- **Record what each step drops, and sample by eye.** When a rule removes 30% of the tokens, first look at what it removed; FineWeb reported the share removed by each rule and visually inspected extraction and deduplication results.
- **Change one thing at a time and ablate with small models.** Fix the model and the budget, use at least two seeds per version, and compare the aggregate score of several benchmarks; a gain on one benchmark is not necessarily a real gain (FineWeb-Edu's threshold was a compromise between MMLU and HellaSwag).
- **Know the blind spots of small-scale ablations.** In the FineWeb paper a 28B-token sample shows almost no effect of deduplication, so the deduplication ablations use 350B tokens; Llama 3's annealing helped the 8B model and did almost nothing for 405B.
- **Convert thresholds into tolerated edits.** Answer “how many words may change before it still counts as a duplicate” with the $p^*$ formula instead of writing “Jaccard 0.8”.
- **Stack at least two granularities.** Near-duplicate removal catches small edits to whole documents, and paragraph- or line-level exact matching catches pasted text and templates (experiment 4).
- **Check subsets for bias.** Dialects, topics and domains before and after filtering; both classifiers and word lists have taste.
- **Decontaminate evaluation sets inside the pipeline.** Treat the test set as a “duplicate document” to remove from the training set, with the same n-gram methods.
- **Version every step's parameters and what remains.** Otherwise you cannot explain a change in downstream evaluation, or reproduce it.

### Common misconceptions

| Misconception | What actually happens |
| --- | --- |
| “The more thorough the deduplication, the better” | FineWeb's global deduplication left 4T tokens, which in a 350B-token ablation barely beat no deduplication and trailed RefinedWeb; per-snapshot deduplication (20T) matched RefinedWeb |
| “Exact deduplication is enough” | In experiment 4, whole-document exact deduplication caught only identical copies and none of the five other kinds |
| “A Jaccard threshold of 0.8 means a copy with 20% of its words changed is still caught” | 5-grams with 0.8 tolerate only about 2.3% changed words, and 13-grams less than 1% (experiment 3) |
| “One MinHash run's recall is its recall” | For “header + footer” in experiment 4, recall ranges from 55% to 98% across hash sets |
| “The higher the classifier score, the better” | A classifier pulls the corpus toward its taste; FineWeb-Edu shrank business, entertainment and travel topics, and its threshold is a compromise between benchmarks |
| “Repeated data is always harmful” | Up to about 4 repeats it is almost as good as fresh data; what hurts is thousands of repeats, such as the sentence repeated 61,036 times in C4 |

## Make corpus filtering auditable and repeatable

[CS336 Assignment 4](https://cs336.stanford.edu/#assignments) traces raw web pages to a trainable corpus. [Berkeley Scalable AI's data assignment](https://scalable-ai.eecs.berkeley.edu/F2026/) applies a curation workflow, and [Stanford CS324's data lecture](https://stanford-cs324.github.io/winter2022/calendar/) examines sources and documentation. Together they suggest keeping three types of evidence at each filtering stage.

| Evidence | Record | Check |
| --- | --- | --- |
| Input snapshot | File list, sources, collection times, content digests, and tokenizer version | The same input ID should resolve to the same data |
| Decisions | Filter versions and thresholds, which copy survives deduplication, and removed documents and tokens by language and domain | Sample accepted and rejected records separately, including less represented languages and short documents |
| Output and evaluation | Output manifest, sharding rule, train and validation splits, and near-duplicate policy | Compare before and after filtering at the same training-token budget on one independent validation set |

The same deletion rate can conceal very different retained corpora. Give each duplicate cluster a stable representative rule, such as ranking by source priority and breaking ties by stable document ID. This helps make the result independent of parallel shard-processing order. Retain only the decision records needed for traceability, and store sensitive audit samples under controlled access.

## Summary and exercises

1. A pretraining corpus is a lossy pipeline: extraction, base filtering, deduplication, heuristic filtering and model scoring; record what each step drops and ablate on small models instead of trusting intuition.
2. MinHash turns document similarity into the fraction of equal signature positions: $\Pr[m_A=m_B]=J$; banding turns the hit probability into the S-curve $1-(1-s^r)^b$, and $(b,r)$ are the knobs for threshold and cost.
3. “Near” is narrow: 5-grams with 0.75 tolerate only about 3% changed words; a text pasted into a longer document and heavy rewriting are invisible to MinHash and need paragraph- or substring-level matching or semantic methods.
4. Global deduplication is not always better: FineWeb's global run kept worse data from the older snapshots, and per-snapshot deduplication matched RefinedWeb; the scope of deduplication is a hyperparameter to ablate.
5. Mixture, annealing and repetition all need experiments: Llama 3 extrapolates mixtures from small models, about 4 repeats are nearly lossless, and returns then decay quickly.

### Quick self-check

**1. Two documents have a 5-gram Jaccard similarity of 0.6. With one random hash function, what is the probability that the two minimum values are equal?**

- [ ] 0.36
- [x] 0.6
- [ ] 0.75
- [ ] It depends on the set sizes

> $\Pr[m_A=m_B]=J(A,B)=0.6$. 0.36 is $0.6^2$, the chance of two independent trials both succeeding. The probability depends only on the ratio of the intersection to the union, not on the set sizes.

**2. FineWeb uses 14 bands of 8 rows. About how likely is a pair with Jaccard similarity 0.75 to be flagged as duplicates?**

- [ ] 0.10
- [ ] 0.56
- [x] 0.77
- [ ] 0.99

> $1-(1-0.75^8)^{14}=0.772$ (experiment 2). 0.56 is the value at $J=0.7$; at $J=0.9$ the probability is already close to 1.

**3. With 5-grams and a threshold $t=0.75$, roughly what share of random word replacements brings the Jaccard similarity down to the threshold?**

- [ ] 0.9%
- [x] 3%
- [ ] 5%
- [ ] 25%

> $p^*=1-(2t/(1+t))^{1/n}=3.04\%$ (experiment 3). 0.90% is Gopher's 13-grams with 0.8, and 5.01% is 3-grams with 0.75. A 0.75 threshold does not mean you can change 25% of the words: n-gram damage comes in runs.

**4. Which statements about experiment 4 are correct?**

- [x] Whole-document exact deduplication catches only identical copies
- [x] When the source is pasted into a longer document, MinHash almost never catches it, while paragraph-level exact deduplication does
- [ ] For copies with 8% of words changed, the two methods combined still catch more than 90%
- [ ] With another set of hash functions MinHash's result on “header + footer” hardly changes

> At 8% the combination catches only 13%. The result for “header + footer” ranges from 55% to 98% across 30 hash sets, because the 100 copies share one template and their outcomes are correlated; one set of hashes cannot be trusted.

**5. What does FineWeb's global deduplication experiment show?**

- [ ] The more thorough the deduplication, the better the model
- [x] For an old snapshot, the data that global deduplication kept was of lower quality than the data it removed
- [ ] MinHash cannot be used across several snapshots
- [ ] Per-snapshot deduplication is worse than no deduplication

> Global deduplication left only 4T tokens and barely beat no deduplication; in the 2013-48 snapshot the kept part was worse than the removed part (more ads and keyword stuffing). Per-snapshot deduplication (20T) matched RefinedWeb.

**6. By the effective-data formula ($R^*=15$), roughly how many copies of fresh data are 4 epochs of the same data worth?**

- [ ] 4.00
- [x] 3.72
- [ ] 2.00
- [ ] 1.00

> $D'/U=1+15(1-e^{-3/15})=3.72$, so 93.0% of the tokens still count (experiment 5).

### Exercises

1. **How many words.** In a 600-word document, replace every 30th word with a new word, $m$ words in total. What is the 5-gram Jaccard similarity? What is the largest $m$ that keeps $J\ge0.75$? Derive it with the formula first, then read the output.
2. **Choose parameters.** The signature may have at most 200 hashes. A pair with $J=0.9$ must be caught at least 99% of the time and a pair with $J=0.5$ falsely merged at most 5% of the time. How do you choose $(b,r)$? Does FineWeb's 14×8 satisfy it?
3. **A pasted copy.** A 256-word document is pasted unchanged into a 1175-word document. What is the 5-gram Jaccard similarity? Why does MinHash miss it while paragraph-level deduplication catches it? What would catch the pasted copy?
4. **Design.** You must deduplicate a new corpus of 500 million documents. Write your plan: which kinds of deduplication, in what order, how to set the parameters, which statistics to record, and how to verify that deduplication did not hurt the model.

<details>
<summary>Reference answers</summary>

Continue in the same session (this uses `shingles`, `jaccard`, `p_dup`, `meta` and others):

```python
# Exercise 1: 600 words, one word changed every 30 words; when does J < 0.75?
doc = flat(new_doc(24))[:600]
assert len(doc) == 600
s0 = shingles(doc)
for m in (16, 17, 18):
    w = list(doc)
    for t in range(m):
        w[30 * t + 15] = 10**9 + t
    print(f"Exercise 1: {m} words changed, J = {jaccard(s0, shingles(w)):.4f}")

# Exercise 2: smallest b*r <= 200 with P(0.9) >= 0.99 and P(0.5) <= 0.05
ok = [(b * r, b, r) for r in range(1, 21) for b in range(1, 201)
      if b * r <= 200 and p_dup(.9, b, r) >= .99 and p_dup(.5, b, r) <= .05]
k, b, r = min(ok)
print(f"Exercise 2: {k} hashes at least, b={b}, r={r}, "
      f"P(0.9)={p_dup(.9, b, r):.4f}, P(0.5)={p_dup(.5, b, r):.4f}")
print(f"            FineWeb's b=14, r=8: P(0.5)={p_dup(.5, 14, 8):.4f}")

# Exercise 3: how low is the Jaccard of a copy embedded in a longer document?
j = [n for n, _ in KINDS].index("embedded in long doc")
_, i, c, _ = [m for m in meta if m[0] == j][0]
n_src, n_long = len(flat(base[i])), len(flat(corpus[c]))
print(f"Exercise 3: source {n_src} words, long document {n_long} words, "
      f"J = {jaccard(shs[i], shs[c]):.3f}")
```

```text
Exercise 1: 16 words changed, J = 0.7633
Exercise 1: 17 words changed, J = 0.7504
Exercise 1: 18 words changed, J = 0.7376
Exercise 2: 72 hashes at least, b=9, r=8, P(0.9)=0.9937, P(0.5)=0.0346
            FineWeb's b=14, r=8: P(0.5)=0.0533
Exercise 3: source 256 words, long document 1175 words, J = 0.215
```

**1.** One replacement destroys the 5 five-grams that contain it, and with a spacing of 30 words they do not overlap. A 600-word document has 596 five-grams, so $J=\dfrac{596-5m}{596+5m}$. Solving $J\ge0.75$ gives $m\le596/35$, that is $m\le17$: in the output $m=17$ gives $J=0.7504$ and $m=18$ gives $J=0.7376$, so at most 17 words may be replaced. Seventeen words are under 3% of the text, consistent with $p^*=3.04\%$ from experiment 3.

**2.** Searching all combinations with $b\cdot r\le200$, the smallest is $k=72$: $b=9$, $r=8$, with $P(0.9)=0.9937$ and $P(0.5)=0.0346$. FineWeb's 14×8 gives 0.0533 at 0.5, above 5%, so it does not meet this constraint (its goal is a midpoint near 0.75, not this constraint). $r$ sets the position and steepness of the curve and $b$ how far it is lifted: here $r$ is the same as FineWeb's and only the band count drops from 14 to 9.

**3.** The 256-word document has 252 five-grams and the long document has 1171 of them, including all 252, so $J=252/1171=0.215$ and the hit probability under 14×8 is practically 0. MinHash estimates Jaccard similarity, and Jaccard is sensitive to set sizes; paragraph-level exact matching does not care how large the whole document is: the pasted paragraphs are identical, and as long as they appeared before they are all caught. To catch pasting with an approximate method you need containment $|A\cap B|/|A|$ (100% here) or substring matching (suffix arrays), at the price of more false positives.

**4.** A reference plan: first whole-document exact deduplication (cheap and risk-free); then MinHash, using the $p^*$ formula to convert the tolerated edit share into $(n,b,r)$ and measuring the catch rate on a sampled subset the way experiment 3 does, instead of copying someone else's parameters; then paragraph- or line-level exact deduplication to cover pasting and templates. Record the documents and tokens removed by each step, the distribution of cluster sizes (how much the largest clusters and the many small ones account for), the share left per source, and inspect random samples of removed and kept documents. To verify, fix a small model and budget and compare “no deduplication, exact only, plus near-duplicate, plus paragraph level” with at least two seeds per version, reporting the noise, and watch how evaluation-set overlap (contamination) changes before and after. Ablate the scope (global or batched) as well.

</details>

## Further reading

Links were checked in November 2026.

- Penedo et al., [The FineWeb Datasets: Decanting the Web for the Finest Text Data at Scale](https://arxiv.org/abs/2406.17557), 2024 ([paper walkthrough](https://dmxsf.com/en/blog/the-fineweb-datasets-decanting-the-web-for-the-finest-text-data-at-scale/))
- Lee et al., [Deduplicating Training Data Makes Language Models Better](https://arxiv.org/abs/2107.06499), ACL 2022
- Rae et al., [Scaling Language Models: Methods, Analysis & Insights from Training Gopher](https://arxiv.org/abs/2112.11446), 2021 (appendix A)
- Raffel et al., [Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer](https://arxiv.org/abs/1910.10683), 2019 (§2.2, [paper walkthrough](https://dmxsf.com/en/blog/t5-exploring-the-limits-of-transfer-learning/))
- Wenzek et al., [CCNet: Extracting High Quality Monolingual Datasets from Web Crawl Data](https://arxiv.org/abs/1911.00359), 2019
- Li et al., [DataComp-LM: In search of the next generation of training sets for language models](https://arxiv.org/abs/2406.11794), 2024
- Dubey et al., [The Llama 3 Herd of Models](https://arxiv.org/abs/2407.21783), 2024 (§3.1, [paper walkthrough](https://dmxsf.com/en/blog/the-llama-3-herd-of-models/))
- Dodge et al., [Documenting Large Webtext Corpora: A Case Study on the Colossal Clean Crawled Corpus](https://arxiv.org/abs/2104.08758), EMNLP 2021
- Xie et al., [DoReMi: Optimizing Data Mixtures Speeds Up Language Model Pretraining](https://arxiv.org/abs/2305.10429), NeurIPS 2023
- Muennighoff et al., [Scaling Data-Constrained Language Models](https://arxiv.org/abs/2305.16264), NeurIPS 2023
- Leskovec, Rajaraman and Ullman, [Mining of Massive Datasets](http://www.mmds.org/), chapter 3 (finding similar items: shingles, MinHash and LSH)

- Gao et al., [The Pile](https://arxiv.org/abs/2101.00027) (2020): a public corpus mixing 22 sources, starting the tradition that the source list and mixing ratios deserve a paper of their own.
- Groeneveld et al., [OLMo](https://arxiv.org/abs/2402.00838) (2024) with the Dolma corpus ([Dolma](https://arxiv.org/abs/2402.00159)): a fully open model and data recipe — the ideal object for studying data engineering.
- Pyatkin et al., [Nemotron-CC](https://arxiv.org/abs/2412.02595) (2024): re-scoring and rewriting Common Crawl with models, a purification route beyond quality classifiers.
- Lovelace et al., [The Common Pile](https://arxiv.org/abs/2506.05209) (2025): a fully deduplicated, commercially usable English public corpus.

## Companion code

[Data engineering: build and audit a dedup filter](https://github.com/dmxsf/dmxsf/tree/main/labs/pretraining/data-engineering): Compare exact duplicates and shingle similarity, then read the banding curve before choosing a deduplication threshold.

- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run pretraining/data-engineering`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/pretraining/data-engineering/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/pretraining/data-engineering/README.en.md)
- [`dedup.py`](https://github.com/dmxsf/dmxsf/blob/main/src/dmxsf/pretraining/dedup.py)
- [Find this lab in the catalog](https://dmxsf.com/en/code/#data-engineering)

## FAQ

### Why deduplicate pretraining data, and does it hurt the model?

Duplicates make a model more likely to recite training text verbatim and worsen the overlap between training and evaluation sets. Lee et al. (2022) found near-duplicates in 3.04% of the C4 training documents and a 61-word sentence repeated 61,036 times; after deduplication, models emitted memorized text about ten times less often, perplexity did not get worse, and the datasets were up to 19% smaller. More is not always better, though: FineWeb deduplicated all 96 snapshots globally with MinHash and got worse results than deduplicating each snapshot separately, because what survived in the older snapshots was of lower quality.

### How does MinHash deduplication work?

Cut each document into a set of word n-grams (FineWeb uses 5-grams), apply k hash functions and keep the minimum of each, which gives a signature of k numbers. For any one hash, the probability that two documents have the same minimum is exactly the Jaccard similarity of their n-gram sets. Split the signature into b bands of r values; if any band matches in full, the pair is a duplicate candidate, with probability 1−(1−s^r)^b. FineWeb uses 112 hashes as 14 bands of 8 rows, which flags a pair with Jaccard 0.75 about 77% of the time. Candidate pairs are then merged into clusters and one document per cluster is kept.

### How much can a document change before MinHash stops calling it a duplicate?

It depends on the n-gram length and the threshold. If every word is replaced with probability p, an n-gram survives with probability q=(1−p)^n and the Jaccard similarity is about q/(2−q). FineWeb's 5-grams with a 0.75 target tolerate only about 3% changed words (one in 33); Gopher's 13-grams with 0.8 tolerate about 0.9%. And if a text is pasted unchanged into a longer document the Jaccard similarity is low, so document-level MinHash misses it and you need paragraph-level or substring-level exact matching.

### Should quality filtering use rules or classifiers?

They complement each other. Rules (the statistical thresholds of C4, Gopher and FineWeb) are cheap and explainable and remove the obvious junk; classifiers rank what is left. At the 1B scale DCLM compared several methods: a fastText classifier trained with OpenHermes 2.5 and ELI5 posts as positives and keeping the top 10% scored 30.2 on CORE, against 27.5 for a RefinedWeb reproduction and 29.0 for perplexity filtering. FineWeb-Edu trained a classifier on 460,000 pages annotated by Llama-3-70B-Instruct, with a threshold of 3, and lifted a 1.71B model from 33% to 37% on MMLU. But a classifier pulls the data toward its own taste: FineWeb-Edu favors education and history-politics topics and downweights business, entertainment and travel.

### How is the data mixture chosen, and how many times can data be repeated?

There is no formula, only experiments. Llama 3 first downsampled categories that are over-represented on the web (such as arts and entertainment), then used scaling-law experiments with small models to predict a large model's results for each mixture; the final mix is roughly 50% general knowledge, 25% math and reasoning, 17% code and 8% multilingual. DoReMi tuned the mixture with a 280M proxy model and raised an 8B model's average few-shot accuracy by 6.5 points, reaching the baseline with 2.6 times fewer steps. On repetition, Muennighoff et al. (2023) found that at a fixed compute budget about 4 epochs are almost as good as fresh data and returns decay after that, with a fitted decay constant of about 15 repeats.
