Skip to content
LearnAI

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.

⏱ 16 minIntermediate

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.

ANALOGY· Panning for gold

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.

INTERACTIVEThe data pipeline funnel

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).

Raw crawl
HTML pages, all languages
100T · 3014d
Text extraction
Strip HTML menus, ads, footers; keep main text
64T · 3011d
Language ID
fastText-style classifier; keep target languages above a confidence
27T · 1288d
Heuristic filters
Too short, symbol soup, repeated lines, filler text…
22T · 1034d
Exact dedup
Hash each document; drop byte-identical copies
18T · 891d
Near-dup (MinHash)
Drop documents too similar to one already kept
16T · 808d
Quality classifier
Model-scored “educational value”, 0–5
4.0T · 189d
Toxicity & PII
Drop toxic pages; redact emails and phone numbers
3.9T · 184d
Languages kept:
final corpus
3.9T tokens
kept
3.9% of raw
avg quality score
2.62
PII spans redacted
67
Example documents and their fate
  • Biology explainer✓ kept
    Photosynthesis 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 extraction
    Home | About | Products | Login | Cart (0) | © 2024 All rights reserved | Privacy | Cookies
    lang en (0.80) · quality 0.1 · toxicity 0.00
  • Spam listing✗ Heuristic filters
    BEST 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 ID
    Para 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 dedup
    City 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 classifier
    lol same here. anyone know when the patch drops? my game keeps crashing after the update
    lang en (0.93) · quality 0.9 · toxicity 0.08
  • Python tutorial✓ kept
    A 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 redacted
    Our 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 classifier
    SKU 4471-B · Color: red · Size: M · Material: 100% cotton · In stock: 12 · Ships in 2–3 days
    lang en (0.85) · quality 0.6 · toxicity 0.00 · near-dup J=0.62
  • Code-switched chat✗ Language ID
    ok bro mañana lo vemos, the game starts at 8 jaja
    lang en (0.55) · quality 0.5 · toxicity 0.02
  • Number theory proof✓ kept
    Let 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✓ kept
    The 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
Each bar shows the tokens that survive that stage. Switch stages off to see what leaks through, drag the quality threshold to trade quantity for quality, and switch between English-only and multilingual. The cards below show where each example document is dropped and why.

Things to try:

  1. 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.
  2. 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.
  3. Switch to “All languages”. More than half the web is not English, so the corpus grows a lot. The Spanish recipe survives.
  4. Turn text extraction off. Token counts rise, but much of what you’re keeping is menus and footers (“boilerplate share”).
  5. 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 5×10175 \times 10^{17} pairs. MinHash makes the problem tractable in two moves.

First, represent each document as its set of shingles: overlapping runs of kk words. “the cat sat on the mat” with k=3k = 3 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.

INTERACTIVEMinHash near-duplicate lab
Try:
shingles A / B / shared
23 / 27 / 15
true Jaccard
0.429
MinHash estimate (64 hashes)
0.391
LSH candidate pair?
yes (1 band)
Signature slots: filled = A and B have the same minimum hash (25 of 64). Bands of 4 rows are outlined.
000.50.511Jaccard similarity sP(candidate)

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.

Edit either document. Compare the exact Jaccard similarity of their word shingles with the MinHash estimate, and see whether LSH banding flags them as a candidate pair. Try the presets, then change the shingle size and the number of bands.

Notice three things. The estimate gets closer to the true value as you add hash functions (its error shrinks roughly like 1/n1/\sqrt{n}). Larger shingles make similarity stricter, since one changed word breaks kk 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:

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 AA and BB be two shingle sets, and hh a random hash function that orders all shingles randomly. Look at the shingle in A∪BA \cup B 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 A∩BA \cap B. So

Pr⁡[min⁡h(A)=min⁡h(B)]=∣A∩B∣∣A∪B∣=J(A,B).\Pr\big[\min h(A) = \min h(B)\big] = \frac{|A \cap B|}{|A \cup B|} = J(A, B).

With nn independent hash functions, the number of matching slots is Binomial(n,J)(n, J), so the estimate J^\hat J has standard deviation J(1−J)/n\sqrt{J(1-J)/n}.

Worked example. AA = “the cat sat on the mat”, BB = “the cat sat on a mat”, shingles of k=2k = 2 words:

shingles
AAthe cat, cat sat, sat on, on the, the mat
BBthe cat, cat sat, sat on, on a, a mat

Shared: 3. Union: 7. So J=3/7≈0.43J = 3/7 \approx 0.43. With n=128n = 128 hashes, J^\hat J has standard deviation 0.43⋅0.57/128≈0.044\sqrt{0.43 \cdot 0.57 / 128} \approx 0.044, so it typically lands between about 0.39 and 0.47.

LSH banding. Split the nn signature slots into bb bands of rr rows. One band matches with probability JrJ^r; the pair becomes a candidate if any band matches:

P(candidate)=1−(1−Jr)b.P(\text{candidate}) = 1 - (1 - J^r)^b .

With b=16b = 16, r=8r = 8 (n=128n = 128): a pair with J=0.9J = 0.9 is caught with probability 1−(1−0.43)16≈0.99991 - (1 - 0.43)^{16} \approx 0.9999, while a pair with J=0.5J = 0.5 is caught with probability 1−(1−0.0039)16≈0.061 - (1 - 0.0039)^{16} \approx 0.06. The threshold sits near (1/b)1/r≈0.71(1/b)^{1/r} \approx 0.71.

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)
COMMON MISCONCEPTIONS
  • “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

0/5 answered
  1. 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?

  2. Q2.MinHash signatures for two documents agree in 96 of 128 slots. What is the best estimate of their Jaccard similarity?

  3. Q3.Raising the quality-classifier threshold (as in FineWeb-Edu) mainly trades…

  4. Q4.What is 'annealing' (mid-training) in a modern pretraining recipe?

  5. Q5.Why do labs run mixture experiments on small proxy models?

Further reading

Progress is saved in this browser only.
Type to search across all lessons and glossary terms.