AI State of the Art
SOTA/Training: Modern Training Techniques/48 min
Section 98

Data Quality: Deduplication, Filtering, Toxicity Removal

Listen as a podcast →

The Problem: "Garbage In, Garbage Out"

An LLM (Large Language Model) has no source of knowledge other than the text it was made to read. The analogy is worn but sound: the best chef in the world, given rotten ingredients, produces a bad dish.

Hence a widely held conviction in the field: data quality supposedly matters more than model size. This page has a particular difficulty, and it is best stated up front: that conviction is broadly shared, but in this form it is not measurable. "Better" is not a quantity. What can be measured is something narrower, two models of the same size, trained on the same compute budget over two different corpora, score differently on named tests. Everything beyond that is interpretation.

What Is Measured and What Is Believed

The data literature mixes these two registers constantly. This page keeps them apart.

Measured: "at equal compute, corpus A scores higher than corpus B on MMLU and ARC." That is a reproducible numeric comparison, and it holds only on the tests named. (MMLU, Massive Multitask Language Understanding: a multiple-choice exam spanning 57 subjects. ARC, AI2 Reasoning Challenge, from the Allen Institute: grade-school science questions.)

Believed: "clean data is better," "quality beats quantity," "cleaning your data beats adding more." These are summaries of practitioner experience. They are probably right, but nobody knows how to test them as stated.

The confusion is costly: a gap measured on two specific tests routinely gets quoted as though the corpus were better in general. On reading a score at all, see how to read a benchmark.

The Data Processing Pipeline

Here is the typical journey from raw data to a finished corpus:

  1. Raw data, whatever was harvested from the web
  2. Extraction, strip HTML, convert formats, normalize characters
  3. Language filtering, language detection, removal of anything that is not text
  4. Deduplication, drop copies and near-copies
  5. Quality filtering, by classifier, described below
  6. Rewriting (since 2024, in some pipelines), part of the mediocre documents is rephrased by an LLM instead of being discarded
  7. Safety filtering, toxicity, personal data, illegal content
  8. Decontamination, removal of evaluation benchmark questions
  9. Mixing and proportioning, source balancing
  10. Final corpus

Every stage removes volume, and the total shrinkage is enormous. But treat the absolute figures that circulate on this topic with suspicion: they depend entirely on the chosen starting point, and that starting point is rarely stated.

One Ratio You Can Actually Check

The one publicly documented filtering ratio that is easy to verify is FineWeb's. FineWeb holds 15 trillion tokens, drawn from 96 Common Crawl snapshots. Its educational-filtered version, FineWeb-Edu, holds 1.3 trillion. Do the division in the open: 1.3 / 15 ≈ 9%. The quality classifier therefore discards roughly nine documents in ten, and FineWeb was already cleaned, deduplicated, filtered web text.

What that ratio does not tell you: how much raw web it took to reach those 15 trillion tokens in the first place. The size of a monthly Common Crawl snapshot varies from month to month; claims of the form "you start from 100 TB" have no stable source. Raw volume is covered on pre-training datasets.

The FineWeb Datasets: Decanting the Web for the Finest Text Data at Scale (Penedo et al., 2024)
Pipeline diagram. A cloud labelled Internet Scale Datasets feeds a green box Data Download plus Text Extraction, which flows down to Text Reformatting plus Cleaning, then to Exact plus Fuzzy Deduplication. The output loops back up to a Quality Filtering box, whose arrow ends at a stack of documents captioned Curated documents for LLM pre-training.
The same sequence as the list above, drawn as an assembly line: download and extract the text, clean it, deduplicate (exact then fuzzy), filter on quality, and what comes out the other end is a pre-training corpus.Source : NVIDIA Developer Blog, NeMo Data Curator
Why Public Corpora Matter

Pushing trillions of tokens through this pipeline takes weeks of compute on very large machines. That is why public corpora whose recipe is written down (FineWeb, DCLM (DataComp for Language Models)) are valuable: they spare each new team from redoing all of it, and they make the filtering auditable. That is the interesting part: with a documented public corpus you can find out what was included and why; with a proprietary one you cannot.

Deduplication

Why It Comes First

The web is an ocean of duplicated content: articles picked up by dozens of aggregators, site templates that recur on every page (legal notices, terms of service), copy-pasted HTML boilerplate, syndicated wire stories.

Skipping deduplication has three consequences:

  • Memorization instead of generalization: the model learns duplicated text word for word instead of extracting the regularity behind it. It is the student who recites the flash cards without understanding them.
  • Overrepresentation: whatever is most duplicated weighs most heavily on learning, without anyone having decided so. The model tilts toward those texts.
  • Contamination of evaluation sets: if test questions are sitting in the training data (because a blog post copied them, say) the resulting score measures memory, not competence.
What Deduplication Changes, in the Paper's Own Numbers

The reference study is Lee et al. (2021). Its measured results, as the paper states them:

  • over 1% of the text produced by models trained on these undeduplicated corpora is copied verbatim from the training data;
  • in C4, one 61-word English sentence appeared more than 60,000 times;
  • after deduplication, models emit memorized text ten times less often;
  • they reach the same or better accuracy in fewer training steps;
  • train-test overlap affected over 4% of standard validation sets.

Note what those numbers do not say. There is no "deduplication improves perplexity by about 10%" in there. That figure circulates, but it does not come from this paper. What the paper establishes precisely is the drop in verbatim copying and the repair of evaluation. On perplexity as a quantity, see entropy.

Deduplicating Training Data Makes Language Models Better (Lee et al., 2021)

First Technique: Exact Deduplication by Fingerprint

You compute a fingerprint of each document: a short fixed-length string obtained by running the whole text through a cryptographic hash function (MD5, Message Digest 5; SHA-256, Secure Hash Algorithm at 256 bits). Two identical documents necessarily give the same fingerprint; two different ones, in practice, give different fingerprints. Comparing a few dozen bytes therefore replaces comparing entire documents.

Fast and simple. But it only sees perfect copies: change one character and the two fingerprints have nothing in common.

Second Technique: Fuzzy Deduplication

So you need to catch documents that are close without being identical: the same article lightly rephrased, the same content behind a different introduction.

The standard method is MinHash + LSH, and it reads in three steps.

One. Each document is cut into n-grams: every run of nn consecutive units, often nn words, sometimes nn characters. The document becomes a set of pieces, and overall order disappears.

Two. You want to know whether two documents share many pieces. The measure used is Jaccard similarity: the number of pieces common to both documents, divided by the total number of distinct pieces found in either one.

J(A,B)=∣A∩B∣∣A∪B∣J(A, B) = \frac{|A \cap B|}{|A \cup B|}

AA and BB are the two sets of pieces. ∣A∩B∣|A \cap B| reads "the number of pieces present in both AA and BB." ∣A∪B∣|A \cup B| reads "the number of pieces present in AA or in BB, counted once." The result is 0 when the documents share nothing and 1 when their piece sets are identical. The threshold used in practice sits around 0.8, meaning four shared pieces out of five. There is no theoretical justification for that value: it is an empirical setting.

Computing that ratio exactly is too expensive at web scale. It is replaced by a MinHash signature: a few hundred numbers per document, built so that the fraction of matching numbers between two signatures estimates the Jaccard similarity of the documents. You have traded precision for space.

Three. The real obstacle remains. Comparing every document to every other, for a billion documents, means a billion billion comparisons, impossible. LSH (Locality Sensitive Hashing) solves it: cut each signature into bands, drop each band into a bucket, and only compare documents that landed in the same bucket. Very dissimilar documents never meet. The name says exactly this: unlike a cryptographic fingerprint, this hash is designed so that nearby inputs collide.

In practice the two techniques run in sequence: exact fingerprinting first, which is fast and clears the perfect copies, then fuzzy deduplication, which is slower, for the near-copies.

Two-part diagram. On the left, a vocabulary of words (Computer, Bring, Revolution) is cut into n-grams (Bri, rin, ing) fed through four hash functions h0 to h3; the minimum of each column forms the MinHash signature. On the right, two signature matrices a and b are cut into coloured bands; each band is hashed into buckets, and a collision between the two sides is marked Match candidate pair. At the bottom, a three-step workflow: Compute Hash, Duplicate Pairs, Compute Remove Docs.
How near-duplicates are found without comparing every pair of documents. On the left, each document is reduced to a short MinHash signature. On the right, that signature is cut into bands and dropped into buckets: two documents landing in the same bucket become candidates worth checking. The rest of the corpus is never compared.Source : Preferred Networks Tech Blog, Improve MinHashLSH for Deduplication on Large Scale Dataset

Quality Filtering

First Filter: Simple Rules

A handful of hand-written rules clear out the most flagrant cases:

  • Minimum length: below roughly fifty words, reject. These are near-empty pages and navigation menus.
  • Letter ratio: too many symbols or digits relative to letters is suspicious. Server logs, raw data tables.
  • Repetition: too many identical word sequences recurring within one page means machine-produced text or boilerplate.
  • Function words: function words are the high-frequency connectives carrying little meaning of their own, "the," "of," "and," "which." Real prose contains them in a fairly stable proportion. A page with almost none is not a sentence; a page with nothing else is filler.

Fast, and it lets through a great deal of mediocrity that happens to satisfy these rules.

Second Filter: A Learned Classifier

You train a small model to sort "good" from "bad." Two common choices for the job: BERT (Bidirectional Encoder Representations from Transformers, see BERT), or fastText, a far lighter and far faster classifier.

  • Positive examples: Wikipedia, published books, peer-reviewed articles, careful technical documentation.
  • Negative examples: randomly sampled web pages, spam, machine-produced text, pages written to game search engines.

The classifier assigns each document a score between 0 and 1, and you keep whatever clears a threshold.

It is worth seeing what that construction actually implies. The classifier does not learn "quality." It learns to recognize what resembles the positive examples it was handed. Choosing Wikipedia and textbooks as the definition of good is deciding that the final model will be good at things resembling Wikipedia and textbooks. The decision is editorial, it is made very early, and it is almost never discussed as such.

Three side-by-side plots. The x-axis is training tokens in billions, from 0 to 350. The y-axes are, respectively, an aggregate score over eight NLP benchmarks, the MMLU score and the ARC score. Eight curves compare datasets (FineWeb, C4, Dolma, RefinedWeb, SlimPajama, The Pile, RedPajama2); the dashed pink FineWeb-Edu curve sits clearly above all the others in all three panels. Two annotations note that it reaches 0.336 on MMLU at 38 billion tokens and 0.470 on ARC at 17 billion tokens.
The effect of a quality classifier, measured. FineWeb-Edu is FineWeb run through a classifier that scores how educational a page is. In the two right-hand panels the pink curve reaches, at around 38 billion tokens, a score the other corpora only approach at 350 billion. Mind the scope of that reading: those two panels are MMLU and ARC, two knowledge-and-reasoning exams, precisely the kind of content the classifier was trained to keep. In the left-hand panel, an average over eight tests, the gap is real but markedly smaller.Source : Hugging Face, FineWeb-Edu dataset card
FineWeb-Edu's Improvement Factor: What Has To Be Said For It To Be True

You often read that FineWeb-Edu is "worth ten times more data." Stated that way, the sentence is false. What the paper says is that models pre-trained on FineWeb-Edu do markedly better "on knowledge- and reasoning-intensive benchmarks like MMLU and ARC."

The difference matters. The corpus was filtered by a classifier that favours schoolbook-like, explanatory pages. It is therefore expected to shine on exams of schoolbook knowledge. The improvement factor is real and measured, on those tests. It does not establish that the corpus is better in general, not for dialogue, not for style, and not for languages other than English, on which it was not evaluated.

This is the classic trap: a filter optimizes whatever it is graded on. On that mechanism, see how to read a benchmark.

Rank Rather Than Cut

Instead of a binary keep-or-discard, the score can be used as a weight: well-scored documents are shown to the model several times, poorly-scored ones once or not at all. This avoids losing documents that sit just under the threshold, and more importantly it avoids making the whole corpus hinge on an arbitrarily chosen number. The quality of a text is not a binary property.

Third Generation: An LLM Annotates, a Small Model Generalizes

Since 2024 the dominant recipe no longer rests on "Wikipedia versus random web." It runs in two stages:

  1. a large LLM reads a sample of a few hundred thousand pages and grades them according to a written instruction (for FineWeb-Edu: Llama-3-70B-Instruct grades the educational value of about 460,000 pages from 0 to 5, aiming at middle-school level);
  2. a small classifier learns to reproduce those grades, then runs over billions of documents at minimal cost.

DCLM (DataComp for Language Models) pushed the logic differently: its best filter is a fastText classifier trained to recognise text that looks like clear answers to questions (high-quality instructions and well-rated answers from a popular-explanation forum), and it keeps only the top 10% of documents.

The editorial point made above still holds; it has simply moved: the definition of "good" text now lives in the instruction given to the annotating LLM, or in the choice of examples that look like what you want. And these filters are aggressive: FineWeb-Edu and DCLM both discard around 90% of web text that was already cleaned.

Perplexity Filtering or Model-Based Filtering?

Before classifiers, the most common method was perplexity filtering: train a small language model on a reference corpus (Wikipedia, for the 2019 CCNet pipeline), then keep the pages it finds "unsurprising." Perplexity measures a model's average surprise at a text (see entropy). Advantage: no annotation needed. Drawbacks: it favours whatever resembles the reference corpus, and bland or repetitive text is just as unsurprising as good text.

CCNet: Extracting High Quality Monolingual Datasets from Web Crawl Data (Wenzek et al., 2019)

DCLM compared both families under identical conditions (same starting pool, same model, same budget). On its reference score the fastText classifier comes first (30.2), ahead of perplexity filtering (29.0), a classifier on embedding features (27.2), semantic deduplication (27.1) and ranking pages by PageRank-style centrality (26.1). The gap is measured at small scale, on the study's tasks, but it was enough to make model-based filtering standard practice.

DataComp-LM: In search of the next generation of training sets for language models (Li et al., 2024)

Rewrite Rather Than Discard

Aggressive filters create a quantity problem: keep only a tenth of the web and there is no longer enough unique text to train large models for long. One idea took hold in 2024-2025: rewrite mediocre documents instead of discarding them. An LLM rephrases the page in a clear style while keeping its content.

  • WRAP (2024) has pages from the C4 corpus rephrased "like Wikipedia" or as question-answer pairs, then mixes originals and rephrasings. Measured result: pre-training roughly 3 times faster to reach the same level, and perplexity improved by more than 10% at equal compute.
  • Nemotron-CC (NVIDIA, 2024) rewrites weak documents and generates variants of good ones, ending up with four times more unique real tokens than DCLM at equivalent MMLU score.
  • REWIRE (Meta, 2025) shows that about 82% of the rewritten texts added to the mix come from documents that would have been discarded, and that mixing high-quality raw text with rewritten text beats having twice as much filtered web.
Rephrasing the Web: A Recipe for Compute and Data-Efficient Language Modeling (Maini et al., 2024) Recycling the Web: A Method to Enhance Pre-training Data Quality and Quantity for Language Models (Nguyen et al., 2025)
What Rewriting Delivers, and What It Can Damage

Rewriting adds no facts: it changes the form. Part of its gains come from the rephrased style resembling the style of the benchmarks (the WRAP authors say so themselves). It can also introduce the rewriting model's errors and make the whole corpus stylistically uniform. That is why published pipelines always keep a large share of original text. The broader question of model-produced text is covered on synthetic data for training.

Safety Filtering

Detoxification

The goal is to reduce, not to eliminate, toxic content:

  • Toxicity classifiers: small models trained on text labelled by human annotators (Perspective API, Detoxify).
  • Word lists: keyword filtering. Blunt, but useful as a first pass.
  • A threshold, not zero: aim for a low residual rate rather than total absence.

Why not zero? Because filtering too hard removes legitimate content: nuanced discussion of difficult subjects, medical documentation containing anatomical terms, legal literature describing crimes, history articles. A model that has never read anything sensitive is simply ignorant of those subjects.

Personal Data

The term of art is PII (Personally Identifiable Information). The task is to remove, or replace with a neutral placeholder:

  • phone numbers, email addresses, postal addresses;
  • names of private individuals, not public figures, whom a model must be able to discuss;
  • identification numbers (social security, ID documents).

Two important remarks, rarely highlighted in the technical papers. First, this removal is done with regular expressions and classifiers: it is a statistical procedure, not a guarantee. Second, it happens before training, so anything that slipped past the filter is learned and becomes very hard to remove afterwards, a model has no "delete this document" function (see machine unlearning).

The Trade-Off Between Filtering and Knowledge

Filtering too much degrades the model. Discarding everything that mentions sensitive medical or legal terms also discards medicine and law. A model trained without any delicate content is simply ignorant of those domains, which is itself a safety problem, since an ignorant model answers anyway.

There is no correct setting. There is a judgement call, it belongs to whoever builds the corpus, and it is almost never published.

The Mix: How Much of Each Source?

Commonly Observed Proportions

The ranges below summarize what teams who publish their recipes report. They are not demonstrated optima: they are customs.

SourceShareNote
Web (filtered Common Crawl)60 to 80%The only source available at this volume
Code (public repositories)5 to 15%Reputed to help reasoning, see the caveat below
Books3 to 8%Access limited by copyright
Scientific articles2 to 5%arXiv, PubMed
Wikipedia2 to 5%Good factual coverage, uniform style
Conversation (forums)1 to 3%Supplies the dialogue register
Languages other than EnglishVariableDepends entirely on the intended target
"Code Improves Reasoning": A Belief, and Best Treated As One

This is the most repeated claim in the field about data mixing, and one of the least established. The intuition is appealing: code is explicit logic, chains of cause and effect, nested structure. Several teams report that raising the code share raises reasoning scores.

But clean ablations (same model, same budget, only the code share varying, everything else held fixed) are rare, and the direction of the link remains open. A code corpus is also better written, better structured and less duplicated than average web text: the observed effect may come from that. Treat this as a well-supported working hypothesis, not a result.

How Proportions Get Chosen

Three ways, from most artisanal to most instrumented.

  1. By experience. You reuse the previous model's proportions with intuitive adjustments. Fast, subjective, and by far the most common.
  2. By small experiments extrapolated upward. You train several small models on different mixes, see which wins, and assume the ranking will hold at scale. More rigorous, but that assumption of rank preservation is itself fragile, see scaling laws.
  3. By automatic optimization. This is what DoReMi (Domain Reweighting with Minimax Optimization) does.
DoReMi: The Paper's Numbers

The principle: first train a small "scout" model whose only job is to determine the weight each source should get, by seeking the mix that minimizes the loss of the worst-served domain, that is what "minimax" means. Then resample the corpus with those weights and train the real model.

What the paper measures: a 280-million-parameter scout sets the weights for an 8-billion-parameter model, 30 times larger. On The Pile, this improves average downstream accuracy by 6.5 points over the default mixture, and reaches the baseline accuracy in 2.6 times fewer training steps.

Worth noting: the scout has no knowledge of the downstream evaluation tasks. That is what makes the result interesting, the gain does not come from tuning on the exam.

DoReMi: Optimizing Data Mixtures Speeds Up Language Model Pretraining (Xie et al., 2023)

Other methods have since made mixing more instrumented. RegMix (2024) trains 512 tiny models (1 million parameters) on randomly drawn mixtures, fits a regression that predicts how well a mixture will do, then applies the best predicted mixture to a model 1,000 times larger. It matches or beats DoReMi with about 10% of its compute. Its most surprising finding runs against intuition: the share of generic web text, more than that of supposedly "high-quality" Wikipedia, is what correlates most with downstream performance, and domains interact in often counter-intuitive ways.

RegMix: Data Mixture as Regression for Language Model Pre-training (Liu et al., 2024)

In practice, 2025 recipes also mix over time: a large, diverse mixture for most of training, then a final phase that sharply raises the share of rare, carefully curated data (mathematics, code, educational text, rewritten data), covered on mid-training. Measuring what each source, or each document, is worth in that mix is a problem in its own right: see how much is a piece of data worth?.

Benchmark Decontamination

The last stage, and the easiest to forget: remove from the corpus the questions of the benchmarks the model will be evaluated on. The web is full of copies of these tests (blogs, help forums, code repositories), and a model that has seen the answers gets a score that measures its memory.

The classic method compares word sequences: drop any document that shares a long run with a benchmark question (13 consecutive words, for instance, in the GPT-3 paper). It has a serious weakness, measured by Yang et al. in 2023: a simple rephrasing or translation of the question slips through. With such variants left in the data, a 13-billion-parameter model reaches scores comparable to GPT-4 on MMLU, GSM8K or HumanEval. Their finer, LLM-based detection method finds that 8 to 18% of HumanEval problems (a programming benchmark) have an equivalent in public pre-training corpora such as RedPajama, and spots the same contamination in synthetic data produced by GPT-3.5 and GPT-4.

Rethinking Benchmark and Contamination for Language Models with Rephrased Samples (Yang et al., 2023)

Decontamination is therefore essential but never complete. It is one reason the field is turning to benchmarks that are refreshed, kept private, or dated after the data was collected: see the limits of benchmarks.

Reference Public Corpora

  • The Pile: 800 GB across 22 distinct sources. The pioneer of open, documented corpora.
  • RedPajama: an open reconstruction of the LLaMA data recipe.
  • FineWeb: 15 trillion tokens of filtered web text, with the pipeline documented step by step and the ablations that justify each choice.
  • FineWeb-Edu: the 1.3 trillion tokens of FineWeb retained by an educational-quality classifier.
  • DCLM: a corpus shipped with a comparison protocol, designed so that filtering recipes can compete on equal footing.
  • Nemotron-CC: 6.3 trillion tokens, rewriting weak documents rather than discarding them.
  • FineWeb2: the FineWeb logic extended to more than 1,000 languages.
  • Common Pile: 8 TB of openly licensed text, for training without copyrighted data.

The corpora and their sources are covered in detail on pre-training datasets.

What To Take Away

  1. Deduplication is the only one of these operations whose effects are clearly established: less verbatim copying, more trustworthy evaluation, faster convergence. The figures come from Lee et al., and they concern those quantities, not some general improvement.
  2. Quality filtering works, but there is no such thing as "quality" in itself. A classifier reproduces the choice of positive examples it was given. FineWeb-Edu is better on MMLU and ARC because it was filtered toward that kind of content. That is a result; it is not general superiority.
  3. Source mixing is still often set by experience. DoReMi and RegMix show it can be done better automatically, with quantified gains, and that intuition ("Wikipedia means quality") is sometimes wrong.
  4. Rewriting recycles discarded web text, with measured gains, but it adds no facts and pipelines always keep a large share of original text.
  5. Word-sequence decontamination is not enough: a rephrased question slips through, and scores get inflated.
  6. "Clean data is better" is not a measurement. It summarizes solid collective experience. Every time someone tries to quantify it, the tests have to be named, otherwise the number means nothing.

Data work is invisible, unglamorous, and it is where most of the outcome is decided. It is also the least published part: when a lab keeps one secret, it is almost always this one.

What comes next: synthetic data, when you decide to manufacture text rather than find it; ordering the examples, when you ask in what sequence to present them; and mid-training, where the rarest data is placed at the moment it counts most.

Check your understanding0 / 6

1. You often read that FineWeb-Edu is « worth ten times more data ». What was actually measured?

2. What does a quality classifier trained with Wikipedia and textbooks as positive examples actually learn?

3. Which effects of deduplication does the Lee et al. paper actually establish?

4. Why does safety filtering aim for a low residual rate rather than zero sensitive content?

5. A piece of personal data that slipped past the PII filter before training…

6. A team removes from its corpus every document sharing 13 consecutive words with a benchmark question. Why is that not enough?