Pre-training data¶
A language model learns the distribution of whatever text you average its loss over. This page follows a web crawl all the way to a training batch (extraction, filtering, deduplication, quality scoring, mixing) with the real numbers from the papers that opened up the recipe, and explains why the data, not the architecture, is now where most of the difference between models is made.
10,000 ft
The language-modelling objective says "match the distribution of the training text". So the training text is the specification: what is in it, how often, and how clean it is decides what the model knows and how it writes. Since GPT-3, architectures have converged on minor variations of one decoder-only transformer, while the data pipelines behind open models (FineWeb, DCLM, Dolma) have shown double-digit benchmark swings from data choices alone. Data also sets a limit: scaling laws say loss improves with tokens, and the stock of public human text is finite. The Data for AI track covers collection, licensing and labelling in depth; this page is the pre-training slice.
2,000 ft
Start from a crawl of the web (plus code, books, papers and other curated sources). Extract clean text from HTML, keep the languages you want, remove junk with cheap rules, remove duplicates, then rank what is left with a learned quality classifier. Mix sources with chosen weights, tokenise, pack into fixed-length sequences, and shuffle. Late in training, switch to a smaller, higher-quality mix ("annealing").
- Extract: HTML to text. The extractor alone moves benchmark scores.
- Filter by rules: language, length, symbol ratios, repetition, bad-URL lists.
- Deduplicate: exact hashes and fuzzy MinHash; repeated text wastes compute and drives memorisation.
- Score quality: a small classifier trained to recognise "good" text keeps the top slice.
- Mix and schedule: decide how many tokens each source contributes, and save the best data for the end.
Ground level¶
Where the tokens come from¶
Almost every large corpus is built from the same few kinds of source:
| source | what it adds | typical issues |
|---|---|---|
| Web crawl (Common Crawl) | scale and breadth: the bulk of all tokens | boilerplate, spam, duplication, unsafe content, many languages |
| Code (public repositories) | programming, and structured reasoning that transfers | licences, auto-generated files, secrets in code |
| Books | long-range coherence, narrative, formal prose | copyright and licensing |
| Academic text (arXiv, PubMed and similar) | maths, science, technical vocabulary | LaTeX and PDF extraction errors |
| Encyclopaedic (Wikipedia) | dense, factual, well edited | small: a few billion English tokens |
| Q&A and forums | dialogue, explanation, question–answer shape | quality varies hugely |
| Synthetic (model-written) | targeted skills, textbook-style explanations | diversity collapse, inherited errors |
Common Crawl is a non-profit that has published free web crawls since 2007; as of 2026 its site describes the archive as over 300 billion pages, with 3 to 5 billion added each month (commoncrawl.org). It ships each crawl as WARC files (raw HTTP responses with HTML) and WET files (text it extracted itself).
The corpora built from these sources have grown by about four orders of magnitude in seven years:
| corpus | year | size | what it is notable for |
|---|---|---|---|
| WebText (GPT-2) | 2019 | 40 GB, ~8M documents | outbound Reddit links with at least 3 karma as a human quality signal (Radford et al.) |
| C4 (T5) | 2019 | ~750 GB | one April 2019 crawl plus simple published rules (Raffel et al.) |
| GPT-3 mix | 2020 | 300B tokens trained | filtered Common Crawl up-weighted against curated sets (Brown et al.) |
| The Pile | 2020 | 825 GiB, 22 subsets | diversity from academic and professional sources (Gao et al.) |
| RefinedWeb | 2023 | ~5T tokens (600B released) | "web data only, done well" beats curated mixes (Penedo et al.) |
| Dolma | 2024 | 3T tokens | fully open corpus and tooling for OLMo (Soldaini et al.) |
| FineWeb / FineWeb-Edu | 2024 | 15T / 1.3T tokens | every pipeline choice ablated and published (Penedo et al.) |
| DCLM | 2024 | 240T-token pool; 3.8T baseline | a benchmark for datasets: fixed model, vary the data (Li et al.) |
| Llama 3 | 2024 | ~15T multilingual tokens | flagship 405B trained on 15.6T tokens (Llama Team) |
The frontier labs rarely publish their exact pipelines, so most of what follows is learned from the open efforts (C4, RefinedWeb, FineWeb, DCLM, Dolma) and the partial descriptions in technical reports such as Llama 3's.
Step 1: extraction is not a detail¶
A web page is mostly not text: navigation menus, cookie banners, footers, adverts, scripts. Turning
HTML into clean prose is the first filter and one of the most consequential. FineWeb compared
Common Crawl's own WET text with re-extracting the raw WARC HTML using the open-source
trafilatura library, training identical 1.71B-parameter models on 28B tokens of each, and found
the WARC-plus-trafilatura text clearly better (Penedo et al., 2024).
Llama 3's team built its own parser, kept image alt text because maths is often rendered as
images with the formula in the alt attribute, and removed Markdown markers after finding them
harmful for a model trained mainly on web text (Llama Team, 2024).
Step 2: language identification and rule-based filters¶
A fast classifier (usually fastText) labels each document's language; FineWeb keeps English with
score ≥ 0.65, C4 kept pages that langdetect scored as English with probability ≥ 0.99. Then come
cheap, interpretable rules. The C4 rules are worth reading once because they show the genre
(Raffel et al., 2019, section 2.2):
- keep only lines ending in terminal punctuation; keep only lines with at least 5 words;
- drop pages with fewer than 3 sentences;
- drop pages containing any word from a public list of "bad words";
- drop lines containing "Javascript"; drop pages containing "lorem ipsum";
- drop pages containing a curly bracket
{(a crude code detector); - drop lines with "terms of use", "privacy policy", "cookie policy" and similar boilerplate;
- deduplicate: keep only one copy of any three-sentence span.
Rules like these are blunt. The curly-bracket rule deletes every programming tutorial, and an audit of C4 found that the bad-word blocklist disproportionately removed text from and about minority individuals (Dodge et al., 2021). Later pipelines replaced fixed lists with measured filters: Gopher's "MassiveText" rules (word-length, symbol-to-word ratio, fraction of lines starting with bullets, repeated n-gram fractions), and Llama 3's duplicated n-gram coverage ratio for log spam plus a token-distribution KL filter for documents full of outlier tokens. FineWeb started from over fifty candidate filters from earlier work and kept only those that improved small-model ablations.
Step 3: deduplication¶
The web repeats itself: mirrors, syndicated news, templated product pages, licence texts, forum signatures. Lee et al. (2021) found a single 61-word English sentence repeated over 60,000 times in C4, that over 1% of the unprompted output of models trained on these datasets was copied verbatim from training data, and that train–test overlap affected over 4% of the validation sets of standard datasets. Deduplicating let them train models that emit memorised text ten times less often and need fewer steps to reach the same accuracy.
Three granularities are used, usually together:
- URL-level: keep one (usually the most recent) copy of each URL.
- Exact: hash whole documents or lines; for repeated substrings inside different documents, use a suffix array to find every span of, say, 50+ tokens that occurs more than once.
- Fuzzy (near-duplicate): MinHash with locality-sensitive hashing (LSH) finds documents whose sets of word n-grams overlap heavily, even if a few words or a footer differ.
MinHash is a beautiful trick and gets a full derivation in The maths. In one sentence: hash every 5-word shingle of a document with \(k\) random hash functions and keep only the minimum for each; the fraction of positions where two documents' minima agree is an unbiased estimate of their Jaccard similarity. Grouping the \(k\) minima into \(b\) bands of \(r\) and flagging any pair that matches on a whole band turns that estimate into a sharp threshold. FineWeb used \(k=112\) hashes as 14 bands of 8, targeting documents at least 75% similar.
More deduplication is not always better
FineWeb's most surprising finding. Deduplicating all 96 crawls globally, newest first, removed up to 90% of the oldest crawls and left 4T tokens, yet models trained on it barely beat the undeduplicated data. Looking inside one old crawl (2013-48), the 10% that survived global deduplication was worse than the 90% removed: the survivors were disproportionately adverts, keyword lists and broken pages, because good content tends to be re-crawled and hence duplicated across years. Deduplicating each crawl independently (20T tokens) worked better. Duplication count is itself a quality signal, so deduplication and quality filtering cannot be tuned separately.
Step 4: model-based quality filtering¶
Rules catch junk; they cannot recognise good writing. The modern answer is a cheap classifier trained to tell a reference set of desirable text from random web text, applied to every document, keeping the top slice.
What counts as a positive is the whole game:
- "Looks like a reference source." GPT-3 trained a classifier to separate WebText, Wikipedia and books from raw Common Crawl and kept documents it scored highly. Llama used pages referenced by Wikipedia as positives, and Llama 3 also trained DistilRoBERTa classifiers on labels produced by Llama 2.
- "Looks like what users ask for." DCLM tried many choices and found a fastText classifier whose positives were instruction-style data (OpenHermes 2.5) and high-scoring answers from the r/ExplainLikeImFive subreddit, keeping roughly the top 10%, worked best. Their 7B model trained on the resulting DCLM-Baseline reached 64% on MMLU (5-shot) with 2.6T training tokens (Li et al., 2024).
- "An LLM says it is educational." For FineWeb-Edu, Llama-3-70B-Instruct scored 460,000 web pages from 0 to 5 for educational value; a small regressor trained on those scores was applied to all 15T FineWeb tokens (6,000 H100 GPU-hours) and documents scoring ≥ 3 were kept, leaving 1.3T tokens. In 1.71B-parameter ablations on 350B tokens, MMLU rose from 33% to 37% and ARC from 46% to 57%.
These filters work, and they have costs: they narrow the distribution towards whatever the positives look like (often Western, formal, English), they can remove dialects and informal registers, and a filter tuned to raise MMLU will tend to raise MMLU. "Quality" here is operational: text that improves the evaluations you chose at small scale.
Step 5: PII, safety and decontamination¶
Pipelines also drop domains known for adult content or high volumes of personal data, mask emails and phone numbers, and remove documents that overlap benchmark test sets (usually by n-gram overlap with the test questions). Decontamination is imperfect: paraphrases, translations and answer keys discussed on forums slip through. The consequences for evaluation get their own page, Contamination and evaluation hygiene. The legal and licensing side (robots.txt, opt-outs, copyright) is covered in Collection, licensing and curation and Governance and regulation.
Step 6: the mixture¶
The final corpus is a weighted mixture of sources, and weights are not proportional to size. GPT-3's mix (Brown et al., 2020, Table 2.2) is the clearest public example:
| source | tokens available | weight in training | epochs over 300B tokens |
|---|---|---|---|
| Common Crawl (filtered) | 410B | 60% | 0.44 |
| WebText2 | 19B | 22% | 2.9 |
| Books1 | 12B | 8% | 1.9 |
| Books2 | 55B | 8% | 0.43 |
| Wikipedia | 3B | 3% | 3.4 |
Wikipedia is seen 3.4 times while most of Common Crawl is never seen at all. Up-weighting small, high-quality sources is how a mixture expresses a belief about quality.
How are weights chosen? Three approaches, in increasing sophistication:
- Hand-tuning against small-model ablations (GPT-3, The Pile).
- Optimising a proxy: DoReMi trains a 280M proxy model with group distributionally robust optimisation to pick domain weights, then trains an 8B model on them; on The Pile it reached the baseline's downstream accuracy in 2.6× fewer steps (Xie et al., 2023).
- Scaling-law experiments on the mix: Llama 3 trained small models on candidate mixes, predicted large-model performance from them, and classified web data by topic to down-sample over-represented categories such as arts and entertainment. Its final mix was roughly 50% general knowledge, 25% maths and reasoning, 17% code and 8% multilingual tokens.
Step 7: packing, shuffling and the end of training¶
Documents are tokenised, joined with an end-of-text token between them, and cut into fixed-length sequences (2,048 to 8,192 tokens is typical for the bulk of pre-training). A sequence therefore often contains the end of one document and the start of an unrelated one; the end-of-text token tells the model that context is about to be useless, and some pipelines also mask attention across document boundaries (Llama 3 did, finding it mattered little in standard pre-training but was important for continued pre-training on very long sequences). Everything is shuffled globally so that each batch is a fair sample of the mixture.
The order is not quite random at the end. Annealing (also called mid-training) switches to a small, high-quality, upsampled mixture while the learning rate decays to zero. Llama 3 annealed on high-quality code and maths, which improved its pre-trained 8B model on the GSM8K and MATH validation sets by 24.0% and 6.4% respectively, and used the same trick as a cheap test of a dataset's value: anneal a half-trained 8B model on 40B tokens with 30% of the new dataset, and see whether benchmarks move. This is also where context length is usually extended (see Long context).
How much text is there?¶
Chinchilla scaling suggests about 20 tokens per parameter for compute-optimal training, and modern models are trained far past that. Villalobos et al. (2022, revised 2024) estimate the effective stock of public human-written text on the indexed web at around \(4\times10^{14}\) tokens and project that, if trends continue, training sets will reach that size between 2026 and 2032 (median 2028). Three escape routes, all active as of 2026:
- Repeat data. Muennighoff et al. (2023) trained 400 models for up to 1,500 epochs: up to about 4 epochs, repeated data is almost as good as new; by around 40 epochs extra repetition is nearly worthless. Their fitted model is in The maths.
- Relax the filters. The same paper found that adding code, or removing some common filters, recovers usable tokens.
- Synthesise. phi-1 (1.3B parameters) trained on 6B tokens of filtered "textbook quality" web data plus 1B tokens of GPT-3.5-generated textbooks and exercises reached 50.6% pass@1 on HumanEval (Gunasekar et al., 2023). Synthetic data is now standard in mid- and post-training; its risks and recipes are in Distillation and synthetic data.
History¶
From 'the whole web' to 'the right web'
2018–2019: GPT-1 trained on BooksCorpus; GPT-2's WebText used Reddit karma as a free human quality label; T5's C4 published simple rules. 2020: GPT-3 introduced classifier-based filtering and deliberate up-weighting; The Pile bet on diversity. 2021–2022: Gopher's MassiveText rules and Chinchilla's demand for more tokens made data volume the bottleneck. 2023: RefinedWeb showed that well-filtered web data alone could beat curated mixtures; phi-1 showed small models gain enormously from textbook-like text. 2024: FineWeb, DCLM and Dolma turned data into an open, ablated science, and model-based filtering using LLM judgements became standard. The arc: from maximising volume to maximising value per token.
First principles¶
Why data choices move the loss so much¶
The objective minimises \(D_\text{KL}(p_\text{train}\,\|\,p_\theta)\), so the model approximates \(p_\text{train}\), the mixture you built, not "language" in the abstract. Three consequences follow directly.
- Every token is a vote. A document repeated 60,000 times gets 60,000 times the weight in the loss. Duplicates do not just waste compute; they tell the model that this text is 60,000 times more likely than it is, which is exactly the condition for verbatim memorisation.
- The mixture weights are a prior over skills. Up-weighting maths does not change the architecture; it changes how many gradient steps pull towards mathematical structure. Llama 3's 25% maths-and-reasoning share is a decision about what the model should be good at.
- The evaluation distribution is not the training distribution. Users ask questions, mostly in clean language, about a skewed set of topics. Filtering towards "text that looks like good answers" (DCLM's positives, FineWeb-Edu's educational score) shifts \(p_\text{train}\) towards where the model will be used.
Why quality filtering works at all¶
If the model can represent the whole distribution, why not keep everything and let it learn? Because capacity and compute are finite. Under a fixed budget of tokens, every junk token displaces a useful one, and the loss on junk (random keyword lists, broken HTML, near-random spam) has high irreducible entropy: the model spends gradient steps on text where there is little structure to learn. Filtering raises the learnable signal per token. This is the same reason the scaling-law constants differ between datasets: data quality changes the coefficients, not just the amount.
Why diversity still matters¶
The counter-force is coverage. A model trained only on top-decile "educational" text sees fewer dialects, less code, fewer styles, and has never seen many of the things users will paste into it. The forward KL objective punishes the model for assigning low probability to anything in the training data, but says nothing about text that was filtered out. Data teams therefore filter hard within a source and mix broadly across sources.
The maths¶
Jaccard similarity and the MinHash property¶
Represent a document \(A\) by its set of shingles (here, word 5-grams). The Jaccard similarity of two documents is
Computing it for all pairs among billions of documents is impossible (\(\sim10^{18}\) pairs). MinHash compresses each set into a short signature whose agreement rate estimates \(J\).
Derivation: P[min h(A) = min h(B)] = J(A, B)
Let \(h\) be a random hash function that behaves like a random permutation of the shingle universe, so every element of \(A\cup B\) is equally likely to have the smallest hash value. Let \(m = \arg\min_{x\in A\cup B} h(x)\).
- If \(m\in A\cap B\), then \(m\) is the minimum of both \(A\) and \(B\), so \(\min h(A) = \min h(B)\).
- If \(m\in A\setminus B\), then \(\min h(A)=h(m)\) while \(\min h(B) > h(m)\), so they differ (and symmetrically for \(m \in B\setminus A\)).
So the minima agree exactly when the overall minimiser lands in the intersection, and since it is uniform over \(A\cup B\),
With \(k\) independent hash functions, the fraction of agreeing positions \(\hat J\) is an average of \(k\) Bernoulli(\(J\)) variables: unbiased, with standard deviation \(\sqrt{J(1-J)/k}\). For \(k=112\) and \(J=0.8\) that is \(0.038\).
Banding: from an estimate to a threshold¶
Split the \(k=br\) signature values into \(b\) bands of \(r\) rows. Two documents become a candidate pair if all \(r\) values agree in at least one band. For a pair with similarity \(s\):
This is an S-curve whose steepest region sits near \(s^\ast\approx(1/b)^{1/r}\). For FineWeb's \(b=14\), \(r=8\): \(s^\ast\approx 0.72\), \(\Pr[\text{flagged}\mid s=0.6]=0.211\), \(\Pr[\text{flagged}\mid s=0.8]=0.924\). Increasing \(r\) sharpens and shifts the step right (fewer false positives); increasing \(b\) shifts it left (fewer false negatives). Only documents sharing a band bucket are ever compared, which turns an all-pairs problem into a hash-join that scales linearly with the corpus.
Mixture weights and epochs¶
If source \(i\) has \(S_i\) tokens and weight \(w_i\), and training sees \(D\) tokens in total, then source \(i\) is traversed
For GPT-3's Wikipedia, \(e = 0.03\times 300\text{B}/3\text{B} = 3.0\) using the rounded weight (the paper's table says 3.4, so the unrounded weight was about 3.4%).
The value of a repeated token¶
Muennighoff et al. model \(U\) unique tokens seen for \(1 + R\) epochs as worth an effective number of fresh tokens
with a fitted \(R^\ast\approx 15.4\) for data. Each extra repetition is worth a factor \(e^{-1/R^\ast}\) less than the previous one, so \(D'\) saturates at \(U(1+R^\ast)\): no amount of repetition is worth more than about 16 epochs of fresh data. At 4 epochs, \(D'\approx 0.93\times\) the tokens seen; because the loss depends on data through a term like \(B/D'^{\beta}\) with \(\beta\approx 0.3\), a 7% shortfall in effective tokens moves the loss very little, which is their "4 epochs is almost free" result.
Build it¶
1. MinHash deduplication from scratch. Uses Tiny Shakespeare (input.txt, downloaded on
the language-modelling page) as a source of realistic documents.
import numpy as np, re, zlib
rng = np.random.default_rng(0)
P = (1 << 61) - 1 # a Mersenne prime for hashing
def shingles(doc, n=5): # set of hashed word 5-grams
w = re.findall(r"\w+", doc.lower())
return {zlib.crc32(" ".join(w[i:i + n]).encode()) for i in range(len(w) - n + 1)}
def minhash(sh, a, b):
x = np.array(sorted(sh), dtype=object) # Python ints: exact mod-P arithmetic
return np.array([min((ai * x + bi) % P) for ai, bi in zip(a, b)])
text = open("input.txt").read()
base = text[:3000]
docs = {"original": base,
"8 words edited": re.sub(r"\b(the|you)\b", "thee", base, count=8),
"nav + footer added": "Home | About | Shop\n" + base + "\nCookie policy. Subscribe now!",
"half copied": base[:1500] + text[50000:51500],
"different scene": text[3000:6000]}
k = 112 # FineWeb: 112 hashes = 14 bands x 8 rows
a, b = rng.integers(1, P, k), rng.integers(0, P, k)
S = {name: shingles(d) for name, d in docs.items()}
sig = {name: minhash(s, a, b) for name, s in S.items()}
for name in list(docs)[1:]:
jac = len(S["original"] & S[name]) / len(S["original"] | S[name])
est = (sig["original"] == sig[name]).mean()
bands = (sig["original"].reshape(14, 8) == sig[name].reshape(14, 8)).all(axis=1)
print(f"{name:18s} Jaccard {jac:.3f} MinHash est. {est:.3f} "
f"bands equal {bands.sum():2d}/14 -> {'DUPLICATE' if bands.any() else 'keep'}")
print("\nP(flagged) = 1 - (1 - s^r)^b with b=14 bands of r=8 rows")
for s in [0.5, 0.6, 0.7, 0.75, 0.8, 0.9]:
print(f" Jaccard {s:.2f}: {1 - (1 - s**8)**14:.3f}")
print(f" steepest point near (1/b)^(1/r) = {(1/14)**(1/8):.3f}")
8 words edited Jaccard 0.861 MinHash est. 0.929 bands equal 8/14 -> DUPLICATE
nav + footer added Jaccard 0.987 MinHash est. 0.991 bands equal 13/14 -> DUPLICATE
half copied Jaccard 0.323 MinHash est. 0.295 bands equal 0/14 -> keep
different scene Jaccard 0.000 MinHash est. 0.000 bands equal 0/14 -> keep
P(flagged) = 1 - (1 - s^r)^b with b=14 bands of r=8 rows
Jaccard 0.50: 0.053
Jaccard 0.60: 0.211
Jaccard 0.70: 0.565
Jaccard 0.75: 0.772
Jaccard 0.80: 0.924
Jaccard 0.90: 1.000
steepest point near (1/b)^(1/r) = 0.719
Note the "half copied" document: 1,500 characters lifted verbatim, yet document-level MinHash keeps it because the sets only overlap by a third. That is exactly the case exact-substring deduplication (suffix arrays) exists for.
2. Mixture epochs and the diminishing value of repeats.
import numpy as np
# GPT-3 training mix (Brown et al. 2020, Table 2.2): tokens available, sampling weight
mix = {"Common Crawl (filtered)": (410e9, 0.60), "WebText2": (19e9, 0.22),
"Books1": (12e9, 0.08), "Books2": (55e9, 0.08), "Wikipedia": (3e9, 0.03)}
total = 300e9 # tokens seen in training
print(f"{'source':24s} {'size':>7s} {'weight':>7s} {'epochs':>7s}")
for name, (size, w) in mix.items():
print(f"{name:24s} {size/1e9:6.0f}B {w:7.2f} {w * total / size:7.2f}")
# Value of repeated data (Muennighoff et al. 2023): U unique tokens seen for 1 + R epochs
# are worth D' = U + U * R* * (1 - exp(-R / R*)) fresh tokens, with fitted R* ~ 15.4
U, R_star = 100e9, 15.4
print(f"\n{'epochs':>6s} {'tokens seen':>12s} {'worth (fresh)':>14s} {'value/token':>12s}")
for epochs in [1, 2, 4, 10, 40, 100]:
R = epochs - 1
worth = U + U * R_star * (1 - np.exp(-R / R_star))
print(f"{epochs:6d} {epochs * U / 1e9:10.0f}B {worth / 1e9:12.0f}B {worth / (epochs * U):12.2f}")
print(f"ceiling as epochs -> inf: {(1 + R_star) * U / 1e9:.0f}B fresh-token equivalents")
source size weight epochs
Common Crawl (filtered) 410B 0.60 0.44
WebText2 19B 0.22 3.47
Books1 12B 0.08 2.00
Books2 55B 0.08 0.44
Wikipedia 3B 0.03 3.00
epochs tokens seen worth (fresh) value/token
1 100B 100B 1.00
2 200B 197B 0.98
4 400B 373B 0.93
10 1000B 782B 0.78
40 4000B 1518B 0.38
100 10000B 1638B 0.16
ceiling as epochs -> inf: 1640B fresh-token equivalents
The recomputed epochs differ slightly from the paper's table (2.9, 1.9, 3.4) because the published weights and sizes are rounded.
Things to try
- Change the shingle size from 5 words to 3 and to 10. Which near-duplicates are caught or missed, and why do short shingles inflate similarity between unrelated documents?
- Add exact-substring detection for the "half copied" case: hash every 50-character window of each document and report shared windows. How many windows does it take before you flag it?
- Sweep \((b, r)\) with \(br = 112\) fixed (e.g. 7×16, 14×8, 28×4) and plot the S-curves. Pick the setting that flags Jaccard 0.85 with 99% probability while flagging Jaccard 0.5 under 1%.
- Write three C4-style rules (terminal punctuation, minimum words per line, curly bracket) and
run them over
input.txtsplit into 2,000-character "pages". What fraction of Shakespeare would C4 have thrown away, and why? - Using the repeated-data formula, how many unique tokens do you need so that 15T tokens of training lose less than 5% of their value?
Check yourself¶
Why do pipelines deduplicate at all, if the model could simply learn that some text is common?
Because duplication distorts the training distribution: a repeated document gets proportionally more weight in the loss, which wastes compute on text the model already fits and drives verbatim memorisation (Lee et al. found >1% of unprompted output copied from training data). Deduplicating also reduces train–test overlap, which otherwise inflates evaluations.
Prove that the MinHash agreement probability equals the Jaccard similarity.
For a random permutation, the element of \(A\cup B\) with the smallest hash is uniformly distributed over \(A\cup B\). Both minima are equal iff that element lies in \(A\cap B\). Hence the probability is \(|A\cap B|/|A\cup B|\).
In FineWeb, why did global deduplication across all crawls hurt?
Good pages tend to persist and be re-crawled across years, so they are duplicated across snapshots; junk pages are often unique. Global deduplication against newer crawls removed most of the good content from old crawls and left a residue that was disproportionately low quality. Duplication frequency was acting as a quality signal.
GPT-3 saw Wikipedia 3.4 times but less than half of its Common Crawl. Why would a team choose that?
Because the mixture is a quality prior: Wikipedia is dense, factual and well edited, so its tokens are worth more per token than average filtered web text. Repeating a small high-quality source a few times costs little (repeats are nearly as good as fresh data for a few epochs) while the web has more tokens than the budget can use anyway.
What does a model-based quality filter actually optimise for, and what can go wrong?
It keeps documents that resemble its positive examples (Wikipedia-referenced pages, instruction data, LLM-judged educational text). So "quality" means "like the positives", and in practice "text that improves the chosen small-scale evaluations". It can narrow the distribution (dialects, informal registers, non-Western content), entrench the judge model's biases, and overfit benchmarks it was selected against.
Hard: with 4T unique high-quality tokens and a plan to train on 16T, how much is the run worth in fresh-token terms, under the Muennighoff model?
16T tokens is 4 epochs, \(R = 3\). \(D' = U + U\cdot15.4\,(1-e^{-3/15.4}) = 4\text{T}\times(1 + 15.4\times0.177) \approx 4\text{T}\times 3.72 \approx 14.9\)T fresh-token equivalents, about 93% of face value.
Hard: a sequence of 4,096 tokens contains the end of one document and the start of another. What does the model learn at the boundary, and what are two ways to handle it?
Without intervention, tokens after the boundary attend to the unrelated previous document, so the model learns that the end-of-text token means "ignore what came before", which it mostly does. You can (1) rely on the separator token and accept the small waste, or (2) use a document-aware attention mask so tokens never attend across the boundary (and reset positions), which costs some kernel complexity but gives cleaner long-context training.
Go deeper¶
Papers
- The FineWeb Datasets — Penedo et al., 2024. The single best document on how a web corpus is built; read section 3 (every pipeline stage with ablations) and the deduplication surprise.
- DataComp-LM — Li et al., 2024. Data as a benchmark: fixed training recipe, vary the dataset. The quality-filter comparisons are the payoff.
- Deduplicating Training Data Makes Language Models Better — Lee et al., 2021. Exact-substring and MinHash deduplication, with the memorisation numbers.
- Exploring the Limits of Transfer Learning (T5) — Raffel et al., 2019. Section 2.2 defines C4; section 3.4 compares pre-training datasets.
- The RefinedWeb Dataset for Falcon LLM — Penedo et al., 2023. The case that filtered web data alone can beat curated corpora.
- Dolma — Soldaini et al., 2024. A fully open three-trillion-token corpus with its tooling and design rationale.
- The Pile — Gao et al., 2020. The diversity-first corpus; its datasheet sections are a model of documentation.
- Scaling Data-Constrained Language Models — Muennighoff et al., 2023. What repeating data costs, quantified.
- Will we run out of data? — Villalobos et al., 2022 (revised 2024). The stock-of-text estimate and its assumptions.
- The Llama 3 Herd of Models — Llama Team, 2024. Section 3.1 is a rare frontier-scale description of web curation, mixing and annealing.
- DoReMi — Xie et al., 2023. Choosing mixture weights with a small proxy model.
- Documenting Large Webtext Corpora: A Case Study on C4 — Dodge et al., 2021. What a filtered crawl actually contains, and what the filters removed.
Articles and blog posts
- FineWeb: decanting the web for the finest text data at scale — Hugging Face. The interactive companion to the paper, with plots for every ablation.
- Will we run out of data? (Epoch AI) — The accessible version of the stock-of-data argument.
Videos and lectures
- Deep Dive into LLMs like ChatGPT — Andrej Karpathy. The opening section walks through FineWeb's pipeline and what web text looks like after each stage.
Courses and code
- Stanford CS336: Language Modeling from Scratch — Includes lectures and an assignment on filtering and deduplicating Common Crawl.
- huggingface/datatrove — The pipeline library used to build FineWeb: extraction, filters, MinHash, all readable.
- FineWeb-Edu on Hugging Face — Browse the data a classifier judged educational; read twenty random rows before you trust any filter.
Where this leads¶
- Scaling laws — how much data a given compute budget wants, and what happens when it runs out.
- Build a GPT from scratch — pack a corpus into training batches and train on it.
- Quality filtering and deduplication — the data track's deeper treatment of filters and dedup at scale.
- Contamination and evaluation hygiene — why decontamination matters for every number you read.
- Distillation and synthetic data — the main answer to running out of human text.