3.1Pretraining data: collect, clean, dedup, mix
How a chaotic web crawl becomes 15–36 trillion carefully chosen tokens, and why data quality often matters as much as model size.
You are what you read
In Part 2 you saw that a language model learns one thing: predict the next tokenTokenA chunk of text (a word, part of a word, or a character) that a language model reads and writes as a single unit.. During pretrainingPretrainingThe first and largest training phase: next-token prediction on trillions of tokens of general text. it does this over and over, across trillions of tokens. Everything the model ends up “knowing” (facts, grammar, how code is structured, how a proof flows) is a statistical echo of that text. So the single most consequential decision before training starts is: which text?
The obvious answer, “all of the internet”, turns out to be wrong. The raw web is mostly navigation menus, cookie banners, spam, machine-generated pages, near-identical copies of the same news story and product listings. Train on it unfiltered and you spend compute teaching the model to reproduce boilerplate. Modern labs treat data as an engineering discipline of its own, with pipelines as carefully tuned as the model architecture. Open efforts such as Hugging Face’s FineWeb have shown that better filtering alone, with the same model and the same token budget, gives a measurably better model.
A prospector scoops up tons of river gravel, sieves out the big rocks, washes away mud, swirls the pan so the heavy flecks stay behind, and finally sorts nuggets by purity. Only a tiny fraction of what was scooped up ends in the jar.
The gravel is the raw web crawl. The sieve is text extraction and heuristic filters, the washing is deduplication, the swirling that keeps heavy flecks is the quality classifier, and the sorting into jars is the data mixture. A smarter pan doesn’t make more gold appear, but it means far less of your time is spent hauling mud.
Stage by stage: from crawl to corpus
1. Crawl. Almost every open corpus starts from Common CrawlCommon CrawlA nonprofit that has crawled the public web since 2008 and releases the raw pages for free. Most LLM pretraining corpora start from its snapshots., a nonprofit that has archived the public web since 2008 and publishes new snapshots several times a year, each with billions of pages. Labs add their own crawls, plus curated sources such as Wikipedia, books, academic papers and code from public repositories. FineWeb, for example, is built from 96 Common Crawl snapshots and ends up at about 15 trillion tokens.
2. Extract text. A crawled page is HTML: menus, ads, scripts, footers and, somewhere in the middle, the actual article. Extraction tools (such as trafilatura) try to keep only the main content. Pages that are nothing but navigation disappear entirely at this step.
3. Identify the language. A fast classifier (typically a fastText model) labels each document with a language and a confidence. A monolingual English corpus keeps only documents labeled English above some confidence threshold; a multilingual one keeps many languages, often with per-language quotas. Code-switched chat and short snippets get low confidence and are frequently dropped, which is one reason low-resource languages end up underrepresented.
4. Heuristic filters. Cheap, hand-written rules remove obvious junk. The Gopher and C4 papers popularized rules like these: drop documents with too few words, too many symbols or ellipses, too many lines that are exact repeats of each other, no sentence-ending punctuation, or telltale strings such as boilerplate filler and “enable JavaScript” warnings. Each rule is crude, but together they remove a large slice of spam and machine-generated pages.
5. Deduplicate. The web is astonishingly repetitive: syndicated news, mirrored documentation, templated pages, scraped copies. DeduplicationDeduplicationRemoving repeated documents (exact copies or near-copies) from a training corpus so the model doesn't over-learn or memorize them. has two levels. Exact dedup hashes each document (or each paragraph) and drops repeats. Near-duplicate dedup catches pages that differ only by a timestamp or a sidebar, using MinHashMinHash (and LSH)A technique that compresses a document's set of word n-grams into a short signature whose agreement rate estimates Jaccard similarity. Locality-sensitive hashing (LSH) then finds likely near-duplicate pairs without comparing every pair. (explained below). Lee et al. (2021) showed that deduplicated training data makes models emit memorized text far less often and train more efficiently.
6. Score quality. This is where modern pipelines differ most from older ones. A quality classifierQuality classifierA small model that scores each web document for usefulness (e.g. 'educational value'); documents below a threshold are dropped. FineWeb-Edu is a well-known example. is a small model that scores every document. The FineWeb-Edu recipe asked Llama-3-70B-Instruct to rate a sample of web pages from 0 to 5 for educational value, trained a small classifier to imitate those ratings, and then ran it over all of FineWeb. Keeping only documents scoring 3 or more shrank the corpus to about 1.3 trillion tokens, yet models trained on it did markedly better on knowledge and reasoning benchmarks such as MMLU and ARC. DCLM took a similar route with a simple fastText classifier trained to recognize high-quality, instruction-like text.
7. Safety and privacy. Toxicity classifiers and URL blocklists remove hateful or adult content. Personally identifiable information (PII) such as email addresses and IP addresses is usually redacted (swapped for a marker like [EMAIL]) rather than dropping the whole document. FineWeb, for instance, anonymizes emails and public IP addresses.
Toggle each stage and tune its threshold. Bars show how many tokens survive, scaled as if the raw crawl held 100T tokens (an illustrative number; the corpus here is a 3,014-document simulation).
- Biology explainer✓ keptPhotosynthesis turns light energy into chemical energy. In the chloroplast, water is split and oxygen is released…lang en (0.99) · quality 4.3 · toxicity 0.01
- Navigation-only page✗ Text extractionHome | About | Products | Login | Cart (0) | © 2024 All rights reserved | Privacy | Cookieslang en (0.80) · quality 0.1 · toxicity 0.00
- Spam listing✗ Heuristic filtersBEST CHEAP W4TCHES $$$ best price best price best price CLICK HERE >>> free shipping!!!lang en (0.70) · quality 0.2 · toxicity 0.10
- Spanish recipe✗ Language IDPara preparar la masa, mezcla la harina con el agua tibia y deja reposar durante una hora…lang es (0.98) · quality 2.4 · toxicity 0.00
- Syndicated news (copy)✗ Exact dedupCity council approves new bike lanes on Main Street after a 6–3 vote on Tuesday evening…lang en (0.99) · quality 2.2 · toxicity 0.02 · exact copy
- Same story, new timestamp✗ Near-dup (MinHash)Updated 9:14 PM. City council approves new bike lanes on Main Street after a 6–3 vote on Tuesday…lang en (0.99) · quality 2.2 · toxicity 0.02 · near-dup J=0.88
- Forum chit-chat✗ Quality classifierlol same here. anyone know when the patch drops? my game keeps crashing after the updatelang en (0.93) · quality 0.9 · toxicity 0.08
- Python tutorial✓ keptA recursive function calls itself. def fib(n): return n if n < 2 else fib(n-1) + fib(n-2). Notice that…lang en (0.95) · quality 3.7 · toxicity 0.00
- Abusive rant✗ Toxicity & PII[a comment thread full of slurs and harassment aimed at another user]lang en (0.97) · quality 2.6 · toxicity 0.93
- Club newsletter with contacts✓ kept, PII redactedOur spring meeting covers soil pH and composting. Questions? Email [EMAIL] or call [PHONE].lang en (0.98) · quality 3.1 · toxicity 0.01
- Product spec sheet✗ Quality classifierSKU 4471-B · Color: red · Size: M · Material: 100% cotton · In stock: 12 · Ships in 2–3 dayslang en (0.85) · quality 0.6 · toxicity 0.00 · near-dup J=0.62
- Code-switched chat✗ Language IDok bro mañana lo vemos, the game starts at 8 jajalang en (0.55) · quality 0.5 · toxicity 0.02
- Number theory proof✓ keptLet n be even, so n = 2k for some integer k. Then n² = 4k², which is divisible by 4…lang en (0.96) · quality 4.6 · toxicity 0.00
- Local history article✓ keptThe mill on the river was built in 1842 and powered the town’s first textile factory until a flood in…lang en (0.99) · quality 3.2 · toxicity 0.01
Things to try:
- Turn the quality classifier off. The corpus grows several-fold, but the average quality score drops sharply. Forum chit-chat and spec sheets now get through.
- Raise the quality threshold to 3.0 or more. You keep only a small fraction of the crawl: this is the FineWeb-Edu trade-off. Great tokens, but few of them.
- Switch to “All languages”. More than half the web is not English, so the corpus grows a lot. The Spanish recipe survives.
- Turn text extraction off. Token counts rise, but much of what you’re keeping is menus and footers (“boilerplate share”).
- Lower the near-dup threshold to 0.6. The spec sheet gets dropped as a near-duplicate of another product page. Set it too low and you start deleting documents that are merely similar, not copies.
The numbers in the demo are a simulation, but the shape is realistic: filtering is a funnel, and most of the raw web does not make it to the end.
How MinHash finds near-duplicates
Comparing every pair of documents is hopeless: a billion documents means about pairs. MinHash makes the problem tractable in two moves.
First, represent each document as its set of shingles: overlapping runs of words. “the cat sat on the mat” with gives {“the cat sat”, “cat sat on”, “sat on the”, “on the mat”}. Two documents are near-duplicates if their shingle sets overlap a lot, measured by the Jaccard similarity: shared shingles divided by total distinct shingles.
Second, compress each set into a short signature. Pick a random hash function, hash every shingle, and keep only the minimum hash value. Here is the beautiful fact: the probability that two documents have the same minimum equals their Jaccard similarity. Repeat with, say, 128 hash functions, and the fraction of matching slots is an estimate of Jaccard similarity. Then locality-sensitive hashing (LSH) groups signatures into bands; two documents become a candidate pair only if some band matches exactly, so similar documents collide in a hash table and dissimilar ones almost never meet.
With 16 bands × 4 rows, a pair becomes a candidate if any band matches completely: P = 1 − (1 − s4)16. The curve rises steeply near s ≈ 0.50. For this pair (s = 0.43) that probability is 42.3%. More bands catch more near-duplicates but also produce more false candidates to check.
Notice three things. The estimate gets closer to the true value as you add hash functions (its error shrinks roughly like ). Larger shingles make similarity stricter, since one changed word breaks shingles. And the banding curve is an S-shape: by choosing bands and rows you choose a threshold, trading missed duplicates against false candidates that need checking.
Mixing: the recipe matters
After filtering you have several clean pools: web text, code, math, scientific papers, books, encyclopedic text, many languages. The data mixtureData mixtureThe proportions of each data source (web, code, math, books, multilingual…) in a training run. Mixtures are tuned with small proxy models. says how much of each the model sees. The Llama 3 paper, for example, reports a final pretraining mix of roughly 50% general knowledge, 25% mathematical and reasoning data, 17% code and 8% multilingual tokens. Labs choose these proportions by training many small proxy models on different mixtures and extrapolating with scaling lawsScaling lawsEmpirical power-law relationships between loss and model size, data and compute., since a full run is far too expensive to experiment on.
Two more ingredients shape modern recipes:
- Annealing (mid-training). Near the end of pretraining, while the learning rateLearning rateThe step size in gradient descent. Too small is slow; too large overshoots or diverges. decays toward zero, the mix shifts toward the best data: math, code, curated reasoning text and long documents. This late phase is called annealing or mid-trainingAnnealing / mid-trainingA late phase of pretraining where the learning rate decays while the mixture shifts toward the highest-quality data (math, code, curated text, long documents).. Qwen3’s report describes three stages: a general stage of over 30 trillion tokens, a reasoning stage of about 5 trillion higher-quality tokens with more STEM and code, and a long-context stage of hundreds of billions of tokens at 32K sequence length.
- Synthetic data. Strong models can rewrite messy web pages into clean explanations, generate textbook-style exercises, or produce verified math and code solutions. Microsoft’s Phi models leaned heavily on “textbook quality” synthetic data. Synthetic data must be filtered too, or it amplifies the generating model’s mistakes and quirks.
Running out of web
High-quality human text is finite. Once filters get strict, frontier runs approach the limit of distinct good tokens. Three responses are common. Repeat data: Muennighoff et al. found that training for up to about four epochs on the same data is nearly as good as fresh data, with returns fading after that. Loosen filters for some sources while upsampling the best, which is what mixture tuning is really doing. And generate more, with all the care synthetic data requires. One more hazard: benchmark questions leak onto the web, so pipelines also try to remove test sets from training data to avoid contaminationData contaminationWhen benchmark questions leak into training data, which inflates scores., which is covered in the evaluation lesson.
MATH CORNER · optionalWhy MinHash estimates Jaccard similarity
Let and be two shingle sets, and a random hash function that orders all shingles randomly. Look at the shingle in with the smallest hash. Every element of the union is equally likely to be that minimum. The two documents share the same minimum exactly when that element lies in . So
With independent hash functions, the number of matching slots is Binomial, so the estimate has standard deviation .
Worked example. = “the cat sat on the mat”, = “the cat sat on a mat”, shingles of words:
| shingles | |
|---|---|
| the cat, cat sat, sat on, on the, the mat | |
| the cat, cat sat, sat on, on a, a mat |
Shared: 3. Union: 7. So . With hashes, has standard deviation , so it typically lands between about 0.39 and 0.47.
LSH banding. Split the signature slots into bands of rows. One band matches with probability ; the pair becomes a candidate if any band matches:
With , (): a pair with is caught with probability , while a pair with is caught with probability . The threshold sits near .
In code
A minimal MinHash near-duplicate check in Python, using the datasketch library that many open pipelines use:
from datasketch import MinHash, MinHashLSH
def shingles(text, k=5):
words = text.lower().split()
return {" ".join(words[i:i + k]) for i in range(len(words) - k + 1)}
def signature(text, num_perm=128):
m = MinHash(num_perm=num_perm)
for s in shingles(text):
m.update(s.encode("utf8"))
return m
lsh = MinHashLSH(threshold=0.8, num_perm=128) # picks bands × rows for you
kept = []
for doc_id, text in corpus: # stream over the corpus
sig = signature(text)
if lsh.query(sig): # a near-duplicate is already kept
continue
lsh.insert(doc_id, sig)
kept.append(doc_id)
- “LLMs are trained on the whole internet.” They’re trained on a heavily filtered fraction of it. Most crawled pages are dropped as boilerplate, spam, duplicates or low quality, and curated sources such as code, papers and books are added on top.
- “More data is always better.” Not if the extra data is junk or duplicates. Smaller, cleaner corpora such as FineWeb-Edu beat larger unfiltered ones at the same training budget. Repeating data too many times also stops helping.
- “Deduplication only saves disk space.” It changes the model: duplicated passages get memorized and regurgitated, and they waste compute that could have gone to new information.
- “A quality classifier knows what ‘good’ text is.” It knows what its labels say is good. Classifier filters encode the taste of whoever wrote the rubric, and they can quietly remove dialects, informal writing or whole topics.
Check your understanding
Q1.Two pages are the same news story, but one has an extra 'Updated 9:14 PM' line. Which stage is designed to catch this?
Q2.MinHash signatures for two documents agree in 96 of 128 slots. What is the best estimate of their Jaccard similarity?
Q3.Raising the quality-classifier threshold (as in FineWeb-Edu) mainly trades…
Q4.What is 'annealing' (mid-training) in a modern pretraining recipe?
Q5.Why do labs run mixture experiments on small proxy models?
Further reading
- paperThe FineWeb Datasets: Decanting the Web for the Finest Text Data at Scale — A fully documented open pipeline (15T tokens) plus FineWeb-Edu's classifier filter. The best single read on this topic.
- paperDeduplicating Training Data Makes Language Models Better — Lee et al. on exact and near-duplicate removal, and why it reduces memorization.
- paperDataComp-LM: In search of the next generation of training sets for language models — A benchmark for data curation; shows how much a simple quality classifier helps.
- paperThe Llama 3 Herd of Models — Section 3 describes Meta's data pipeline, mixture and annealing in unusual detail.
- paperScaling Data-Constrained Language Models — What happens when you run out of unique data and repeat epochs.
- docsCommon Crawl — The open web archive most pretraining corpora start from.