Sam Austinon November 17, 202614 min read

How LLM Pretraining Data Is Filtered, Deduplicated, and Mixed

How LLM Pretraining Data Is Filtered, Deduplicated, and Mixed
Contents

Figure 1: How LLM Pretraining Data Is Filtered, Deduplicated, and Mixed — most of the raw web never reaches the model, and the decisions that remove it shape what the model can learn

Two labs can train the same architecture on the same compute and end up with very different models. The difference often hides in the data. The quality of the pretraining corpus sets the ceiling of what a model can learn — more so than the architecture, and often more than the compute budget.

This post walks through how raw web crawls become training data, where each step fits, and the toy versions of the key ideas that I ran on this machine.

The Pipeline at a Glance

Nearly every open pretraining corpus starts with Common Crawl, a public scrape of the web released in monthly snapshots. Raw Common Crawl is not training data. It contains near-duplicates, boilerplate, and spam.

A pipeline turns it into something usable through roughly these stages:

  1. Extraction — pull clean text out of HTML.
  2. Language identification — keep the languages you want.
  3. Quality filtering — heuristics first, then model-based classifiers.
  4. Deduplication — exact first, then near-duplicate.
  5. PII and toxicity handling.
  6. Benchmark decontamination.
  7. Mixing — decide how much of each source the model sees.
  8. Tokenisation and packing.

The order is not fixed. Some teams argue deduplication should come before quality classification, so the classifier is not asked to score redundant near-copies. The DCLM-Baseline pipeline instead dedups with a Bloom filter first, then applies the most compute-heavy step — model-based quality filtering — only to the much smaller remaining data [2]. Each team picks an order based on cost.

Step 1: Extraction and Language ID

Quality starts with extraction. FineWeb extracts text from raw WARC files with Trafilatura rather than using the pre-extracted WET text, then filters language with a fastText classifier [1]. It also applies a URL blocklist before extraction.

Better extraction strips navigation menus and ads that would otherwise pollute everything downstream. A menu line that survives extraction becomes training text, and no filter downstream knows it was never prose.

Step 2: Heuristic Filters

Next come cheap rules. These are pure CPU string operations, and their job is to throw away obviously useless documents before spending compute on anything expensive. Many pipelines borrow rules from the Gopher paper [3], and FineWeb, DCLM, Dolma, and RedPajama all reuse variants [1][2].

Typical checks catch documents that are too short or too long, have strange average word lengths, contain few alphabetic characters, or have few lines ending in punctuation. Some pipelines also filter at the line level, removing noisy lines like social-media counters or navigation links.

Here is a simplified version, which I ran on three toy documents:

def quality_flags(doc):
    words = doc.split()
    flags = []
    if len(words) < 20: flags.append("too short")
    alpha = sum(ch.isalpha() for ch in doc) / max(len(doc), 1)
    if alpha < 0.6: flags.append("low alphabetic fraction")
    lines = [l for l in doc.split("\n") if l.strip()]
    if lines and sum(l.rstrip().endswith((".", "!", "?", '"')) for l in lines) / len(lines) < 0.3:
        flags.append("few lines end in punctuation")
    return flags

Measured output:

article   -> keep                                    (63 words, alpha 0.819)
nav menu  -> ['few lines end in punctuation']        (29 words, alpha 0.667)
spam      -> ['low alphabetic fraction']             (33 words, alpha 0.531)

A real article passes, while a navigation menu and keyword spam get flagged — and each fails for a different reason, which is the point of stacking independent rules.

Real pipelines use many more rules with carefully tuned thresholds, but the logic stays this simple. Heuristics deserve more respect than they get: they are transparent, cheap, and auditable, and at least one survey of the field deliberately favours rule-based filters over ML-based ones to reduce bias and keep the process explainable.

Step 3: Model-Based Quality Filtering

Heuristics catch junk. They cannot tell a mediocre blog post from an excellent explanation. For that, teams train a classifier.

FineWeb-Edu had an LLM grade each document's educational value, trained a small classifier on those labels, and used it to select a high-quality subset. The result was a much smaller dataset: about 1.3 trillion tokens, versus 15 trillion for the full FineWeb [1].

DCLM showed that a single fastText classifier trained on good data can outperform more elaborate combinations [2]. Positive examples come from sources like Wikipedia and curated text, negatives from random web text.

KenLM perplexity filtering, from the CCNet line of work, offers a cheaper alternative: score documents by how likely a language model trained on high-quality text finds them, and drop the ones it finds surprising.

The recurring lesson is that the definition of "quality" lives in whatever you train the classifier on. Change the positives, and you change what your model learns to value. That is powerful, and it is also a bias risk.

Step 4: Deduplication

Duplicates harm models. They waste training compute, and they encourage memorisation. Dedup comes in two flavours.

Exact deduplication hashes documents or paragraphs and removes perfect matches. It is cheap and reliable.

Near-deduplication catches documents that differ by a few words — the same news article with a different header. The standard tool is MinHash with locality-sensitive hashing (LSH), and essentially every modern open pipeline uses a tuned version, FineWeb included [1].

The idea: break each document into overlapping word groups (shingles), compute a compact signature, and compare signatures. The fraction of matching signature values estimates the Jaccard similarity of the shingle sets. I built a tiny MinHash with 128 hash functions and tested it on a news paragraph, a lightly edited copy, and an unrelated paragraph:

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

def jaccard(a, b):
    return len(a & b) / len(a | b) if (a | b) else 0.0
base vs near-dup : true 0.73   MinHash estimate 0.69   (1 sigma = 0.04)
base vs different: true 0.00   MinHash estimate 0.00

The estimate lands one standard error below the true similarity, which is exactly the sampling noise you expect from 128 permutations — the estimator is unbiased, and it gets tighter as you add hashes. At web scale, LSH buckets keep the comparison count manageable, so you never compare every document against every other.

More Dedup Isn't Always Better

Here is a surprise. FineWeb ran MinHash deduplication separately within each Common Crawl snapshot. The authors found that this matched RefinedWeb's performance, while global deduplication across all snapshots gave little improvement over no deduplication at all [1].

That finding contradicts the intuition that more dedup always helps. Dedup is something to measure and tune, not a switch to leave on.

Yet duplicates still hide in large corpora. The Zyda team, assembling a corpus from several open datasets, had to deduplicate both within and across its sources — which means duplicates survived each source's own pipeline [5]. Dedup behaviour depends heavily on how and where you apply it.

Researchers also explore semantic deduplication, such as SemDeDup, which removes documents that mean the same thing without sharing exact words.

Step 5: PII, Toxicity, and Decontamination

Pipelines also scrub personal information, handle toxic content, and remove benchmark contamination — test-set text that leaked into the training data.

The stages have distinct jobs: extraction sets the purity of the raw material, filtering sets the distribution, dedup sets the memorisation, and decontamination sets the honesty of your evaluation. Skip decontamination, and your benchmark scores may measure memory rather than ability.

Step 6: Mixing

Even a clean corpus needs a recipe. The per-domain mixture of web, code, papers, books, and multilingual text is a hyperparameter in itself.

Here is the tension. Web data is huge, and high-quality sources like Wikipedia or books are small. If you sample proportionally, the model sees mostly web text. If you upweight small sources, you repeat them many times. I computed a toy example with made-up numbers, all in billions of tokens:

Source Weight Tokens drawn Available Epochs
web 0.55 1,100B 12,000B 0.09
code 0.20 400B 1,500B 0.27
books 0.15 300B 300B 1.00
wiki 0.10 200B 20B 10.00

With a 2,000B-token budget, Wikipedia would repeat ten times while the web barely gets touched. Repeated data helps up to a point and then hurts, and the exact tradeoff depends on the model and the data.

Smoothing the Mixture

A common trick is to sample sources proportionally to their size raised to a power below 1, which flattens the distribution. On the same toy sizes:

Exponent web code books wiki
1.0 0.868 0.109 0.022 0.001
0.5 0.644 0.228 0.102 0.026
0.25 0.456 0.271 0.181 0.092

Lower exponents give small sources a bigger share without hand-picking every weight, which is why the trick shows up in so many recipes.

Learning the Weights

Teams used to set mixtures by hand. Research moved toward learning them. DoReMi optimised domain weights with a small proxy model and a distributionally robust objective, then applied those weights to a much larger run [4]. Later work extended this to regression and scaling-law approaches, and to online control during training.

Curriculum schemes help too: raising the share of high-quality data late in training — annealing — has shown benefits in FineWeb-line experiments [1].

One published example blend is 40% FineWeb-Edu, 25% DCLM-Baseline, 20% Wikipedia, and 15% books. Treat that as an illustrative recipe, not a standard, because the right mixture depends on your budget and your evaluation.

The Scale

The numbers help set expectations. FineWeb processed 96 Common Crawl snapshots into 15 trillion tokens, about 44 TB of text [1].

Fuzzy dedup typically keeps roughly 60 to 70 percent of documents, and quality scoring keeps another 50 to 70 percent — expect most of the raw web to disappear. Those survival rates vary a lot by pipeline, so treat them as an order of magnitude rather than a target.

If You're Building Your Own

Start with open tooling instead of writing everything yourself. datatrove built FineWeb, Dolma provides filters, dedup, and PII taggers, and NeMo Curator offers another option. A sensible stack layers exact and MinHash dedup, language, PII and safety filters, a learned quality scorer, decontamination, and finally mixture design.

Then ablate. The FineWeb team justified each filter by training small models on the filtered data and comparing benchmark scores [1]. You can do the same at small scale: train a tiny model on two versions of the data and see which one wins.

Common Pitfalls

  • Trusting thresholds from papers without testing. Your data differs from theirs.
  • Over-filtering. Aggressive quality classifiers strip out diverse, useful text and bake in the classifier's biases.
  • Deduplicating by default. Measure whether it helps; FineWeb's own results were mixed.
  • Skipping decontamination. Inflated benchmark scores follow, and you will not know it.
  • Ignoring epochs. Upweighting a tiny source repeats it many times.
  • Mixing without ablations. Intuition about good ratios often fails.
  • Treating data cleaning as one-and-done. Pipelines need iteration as the model and the goals change.

Best Book to Read

CoverBookDescriptionGet it
Cover of “Designing Machine Learning Systems” Designing Machine Learning Systemsby Chip Huyen the data engineering chapters cover collection, labelling, and pipeline design, which is the discipline this whole post sits inside. View on Amazon

As an Amazon Associate I earn from qualifying purchases. Links on this page are affiliate links, and I may earn a commission at no extra cost to you.

Read the data engineering chapters after this post. They frame filtering and dedup as ongoing system design rather than a one-off cleaning script, which is the difference between a corpus that improves and one that quietly rots.

Wrapping Up

Pretraining data goes through extraction, heuristic filters, model-based quality scoring, deduplication, safety and decontamination passes, and finally a carefully chosen mixture. Each stage changes what the model learns, and the best teams justify every choice with small-scale experiments. Fewer, better tokens often beat more, noisier ones.

The two numbers worth carrying: a MinHash signature estimated a 0.73 Jaccard similarity as 0.69 with 128 hashes, and a plausible mixture can repeat Wikipedia ten times while sampling a tenth of the web.

Run the toy filters and the MinHash demo on a few of your own documents. Watching a near-duplicate score near 0.7 while an unrelated paragraph scores 0.0 makes the whole idea click.

Frequently Asked Questions

Why is deduplication important for pretraining data?

Duplicates waste compute on text the model has already seen and push the model toward memorising specific passages rather than learning patterns. Removing them also stops a single document from dominating the effective mixture, which silently changes what the model is trained on.

How does MinHash detect near-duplicate documents?

It breaks each document into overlapping word shingles, hashes each shingle with many different hash functions, and keeps the minimum hash value per function. The fraction of positions where two documents agree estimates the Jaccard similarity of their shingle sets, so you can compare short signatures instead of full texts.

What is benchmark decontamination?

It is removing text from the training corpus that also appears in the evaluation sets. Without it, a benchmark score can measure how well the model memorised test items rather than how well it generalises, which makes the evaluation dishonest.

Why not just train on the highest-quality filtered data?

Because aggressive filtering removes diversity along with noise, and it bakes in whatever the quality classifier was trained to prefer. Most strong pipelines keep a broad base and add high-quality data through the mixture or late in training, rather than discarding everything a filter dislikes.

What is a good data mixture?

There is no universal answer, because the optimum depends on the model size, the token budget, and the downstream tasks. The practical approach is to start from a published mixture, then run small ablations on your own data and measure the tasks you care about.

Sources

  • [1] Penedo et al., The FineWeb Datasets: Decanting the Web for the Finest Text Data at Scale — the pipeline, FineWeb-Edu's 1.3T subset, and the dedup and annealing findings: arxiv.org
  • [2] Li et al., DataComp-LM: In search of the next generation of training sets for language models — DCLM-Baseline, Bloom-filter dedup, and fastText quality classification: arxiv.org
  • [3] Rae et al., Scaling Language Models: Methods, Analysis and Insights from Training Gopher — the heuristic filter rules most pipelines inherited: arxiv.org
  • [4] Xie et al., DoReMi: Optimizing Data Mixtures Speeds Up Language Model Pretraining — learned domain weights from a proxy model: arxiv.org
  • [5] Zyphra, Zyda: A 1.3T Dataset for Open Language Modeling — filtering and deduplication within and across source datasets: arxiv.org

What are You Looking For?

esc