Pretraining Data Pipelines
local graph
Chapter 6 — Pretraining Data Pipelines
Section titled “Chapter 6 — Pretraining Data Pipelines”A model is a compression of its training data, and no architecture can rescue a bad corpus. The last few years have made this the field’s worst-kept secret: the gap between a mediocre model and a great one at the same size is, more than anything, the data. This chapter walks the pipeline that turns the raw internet into the trillions of clean, deduplicated, packed tokens a model actually trains on — sourcing, filtering, deduplication, and the on-disk format that feeds the training loop.
6.1 Sourcing and the Scale of Modern Corpora
Section titled “6.1 Sourcing and the Scale of Modern Corpora”Pretraining data is assembled from a few broad sources, each contributing a different competence: filtered web text for breadth and fluency, code for structure and reasoning, mathematical and scientific text for rigor, books for long-range coherence, and deliberately upweighted multilingual and reference data for coverage and facts. The exact recipe is the most closely guarded part of any model, but the scale is not, and it has exploded. Table 6.1 shows the trajectory.
| Model | Released | Pretraining tokens (approx.) |
|---|---|---|
| GPT-3 | 2020 | ~0.3T |
| Llama 2 | 2023 | ~2T |
| Llama 3 | 2024 | ~15T |
| DeepSeek-V3 | 2024 | ~14.8T |
| Qwen3 | 2025 | ~36T |
| DeepSeek-V4 | 2026 | ~32T |
Table 6.1 — Pretraining token budgets have grown by orders of magnitude
Figures are as reported or estimated and count tokens, so they depend on the tokenizer. The lesson is the trend: leading models now train on tens of trillions of tokens, which makes the efficiency of the data pipeline a first-order concern.
Beyond scale, two themes dominate modern data work. The first is quality over quantity: aggressive filtering of a huge crawl to a smaller, cleaner subset reliably beats training on the raw bulk. The second is provenance — tracking licenses and sources, both to respect rights and to reason about contamination of evaluation benchmarks (Chapter 29). For specialized models, the mix shifts hard toward the target domain; DeepSeek-Coder, for instance, is built on a repository-level code corpus with careful filtering and dependency-aware ordering.
6.2 Cleaning and Quality Filtering
Section titled “6.2 Cleaning and Quality Filtering”Raw web text is mostly junk: navigation bars, boilerplate, spam, markup, and near-duplicate templates. A cleaning pipeline applies a cascade of filters, ordered cheap-to-expensive so the costly steps see less data. Table 6.2 lists the usual stages.
| Stage | What it removes |
|---|---|
| Text extraction | HTML markup, boilerplate, navigation; keep main content |
| Language identification | documents not in target languages |
| Heuristic quality filters | too short/long, bad symbol ratios, repeated lines, gibberish |
| Model-based quality filter | low-quality pages, scored by a small classifier or perplexity |
| Safety / PII filters | toxic content and personal data (emails, IDs, keys) |
| Deduplication | exact and near-duplicate documents (Section 6.3) |
Table 6.2 — A typical cleaning cascade, cheap filters first
Each stage is individually simple; the engineering is in running them reliably over petabytes. Open frameworks now encapsulate this — Hugging Face’s datatrove provides composable filtering, deduplication, and tokenization stages that scale across a cluster, and the FineWeb work documents how far careful filtering of Common Crawl alone can go.
6.3 Deduplication
Section titled “6.3 Deduplication”Deduplication deserves its own section because it does double duty: it improves quality (the model spends capacity on diverse content rather than memorizing boilerplate seen a thousand times) and it reduces verbatim memorization of training data. There are two regimes. Exact deduplication hashes whole documents (or fixed-length substrings) and drops collisions — trivial and cheap. Near-duplicate detection is the hard, important case: pages that differ only in a timestamp or a header should still be collapsed.
The standard tool is MinHash with locality-sensitive hashing (LSH). The idea: represent each document by the set of its overlapping word shingles; estimate the Jaccard similarity between two documents cheaply using a handful of min-wise hashes; then use LSH to bucket only the documents likely to be similar, so you never compare all pairs. The sketch below conveys the core; production implementations (in datatrove and others) add banding and tuning.
import hashlib
def shingles(text, k=5): words = text.split() return {" ".join(words[i:i+k]) for i in range(len(words) - k + 1)}
def minhash(shingle_set, num_hashes=128): sig = [] for seed in range(num_hashes): def h(s): return int(hashlib.md5((str(seed)+s).encode()).hexdigest(), 16) sig.append(min(h(s) for s in shingle_set)) # min-wise hash return sig
def estimated_jaccard(sig_a, sig_b): # fraction of matching min-hashes approximates set similarity return sum(a == b for a, b in zip(sig_a, sig_b)) / len(sig_a)Python — MinHash similarity, the core idea (illustrative)
Two documents with Jaccard similarity above a threshold (commonly around 0.8) are treated as duplicates and one is dropped. LSH makes this scale: by hashing bands of the signature into buckets, only documents sharing a bucket are ever compared, turning an impossible all-pairs problem into a linear scan. Run at corpus scale, deduplication routinely removes a large fraction of a raw crawl — and measurably improves the resulting model.
6.4 Tokenize, Shard, and Pack
Section titled “6.4 Tokenize, Shard, and Pack”Once text is clean and deduplicated, it is tokenized once, ahead of time, and written to disk as a flat stream of token ids. The training loop then reads this stream with a memory-mapped array, so even a multi-terabyte dataset uses almost no RAM and batches are nearly free to sample. This is the nanoGPT data format, and it is as simple as it is fast.
import numpy as np
# 1) tokenize the corpus once and write a flat .bin fileids = tokenizer.encode(corpus_text) # list[int]np.array(ids, dtype=np.uint16).tofile("train.bin") # uint16 if vocab < 65536
# 2) at train time: memory-map it (near-zero RAM) and sample batchesdata = np.memmap("train.bin", dtype=np.uint16, mode="r")
def get_batch(B, T): ix = np.random.randint(0, len(data) - T - 1, size=B) # random windows x = np.stack([data[i : i+T ] for i in ix]) y = np.stack([data[i+1 : i+T+1] for i in ix]) # shifted target (Ch 4) return torch.from_numpy(x), torch.from_numpy(y)Python — prepare.py: write tokens to a binary shard, then sample batches by mmap
Use uint32 instead of uint16 for vocabularies larger than 65,536 tokens (o200k, Gemma). Two refinements matter at scale. Packing concatenates many documents into each fixed-length training window so no compute is wasted on padding; a special end-of-document token marks boundaries, and well-built pipelines mask attention so packed documents do not attend across the boundary. Data mixtures and curriculum control the recipe over training — the proportions of web, code, and math, and sometimes a shift toward higher-quality or longer-context data late in training. These ratios are among the highest-leverage hyperparameters a lab tunes, and among the least disclosed.
The write side of this pipeline — turning a tokenized dataset into the binary shard the get_batch above reads — is worth seeing in its real form. nanoGPT’s prepare.py preallocates a memory-mapped file and fills it batch by batch, which is what lets it tokenize datasets far larger than memory:
import numpy as np# preallocate the output file on disk, then fill it in batchesarr = np.memmap("train.bin", dtype=np.uint16, mode="w+", shape=(total_tokens,))idx = 0for b in range(n_shards): shard = dset.shard(n_shards, b).with_format("numpy") batch = np.concatenate(shard["ids"]) # this shard's token ids arr[idx : idx + len(batch)] = batch # write without loading all idx += len(batch)arr.flush() # commit to diskPython — karpathy/nanoGPT · data/openwebtext/prepare.py: writing shards (reproduced, MIT licence)
Together with the get_batch above, this is nanoGPT’s complete data path — write once to a flat binary of uint16 token ids, then memory-map it and slice random windows at training time, never holding the corpus in RAM. The production tooling scales the same idea: Hugging Face’s datatrove runs the filtering, MinHash deduplication, and tokenization stages of this chapter across thousands of CPU cores and writes sharded token files in exactly this spirit, and the DeepSeek-Coder report documents the repository-level, dependency-aware packing used for code data. The mechanism never changes — tokens to a binary, memory-mapped back — only the scale of the machine that produces it.
Continued pre-training You rarely need to start from raw web data. Continued pre-training takes an existing open-weight base model and trains it further on a new corpus — a domain (medicine, law, finance), a language, or a longer context window — before any instruction tuning. It reuses everything in this chapter at a fraction of the cost and is the most practical way for a small team to specialize a frontier model. We return to it in Part V.
The model now has a vocabulary and a stream of tokens to learn from. Everything in Parts I and II has been preparation; Part III begins the model itself, deriving the transformer one component at a time — starting with the mechanism that lets a token see its context: attention.
6.5 Deduplication and Why It Matters
Section titled “6.5 Deduplication and Why It Matters”Web-scale corpora are saturated with duplication: the same news article copied across a hundred sites, boilerplate repeated on every page, passages quoted endlessly. Training on this redundancy is not harmless — it wastes compute on content the model has already seen, biases the model toward over-represented text, and measurably increases verbatim memorization. Deduplication is, dollar for dollar, among the highest-leverage steps in the entire data pipeline, and its near-duplicate form relies on a compact trick:
def minhash_signature(doc, hashes): shingles = set(ngrams(doc, n=5)) # overlapping 5-grams return [min(h(s) for s in shingles) for h in hashes]# docs whose signatures collide in many buckets are near-duplicatesPython — data/dedup.py: MinHash signatures for near-duplicates
Exact deduplication catches identical documents with a simple hash, but most real duplication is near-duplication — the same text with a changed headline or a different template wrapped around it. MinHash handles this by reducing each document to a short signature with the property that similar documents produce similar signatures; comparing signatures rather than full documents makes deduplication tractable at the scale of billions of pages. The payoff is consistent across the field: models trained on deduplicated data reach the same quality in fewer tokens and memorize less of their training set, which is why careful deduplication has become a standard, and quietly decisive, part of preparing a pretraining corpus.
Duplication is wasted compute and extra memorization Web corpora repeat themselves heavily; training on the repeats buys nothing and worsens memorization. MinHash makes near-duplicate detection feasible at scale, and removing duplicates reaches the same quality in fewer tokens — one of the cheapest wins in the pipeline.
6.6 Data Mixing and Curriculum
Section titled “6.6 Data Mixing and Curriculum”A pretraining corpus is never one thing — it is a deliberate mixture of sources: general web text, books, code, mathematics, academic papers, and more. The proportions in which these are combined, the mixing weights, are among the most consequential and least visible design choices in building a model, because they shape what the model becomes as directly as the architecture does.
The effects are concrete and now well established. Upweighting code in the mixture improves not only coding but general reasoning, apparently because code’s explicit logical structure teaches transferable habits of thought; upweighting a domain improves that domain at some cost to others. The mixture is therefore tuned, often through small-scale experiments that reveal how a proportion change moves downstream metrics before committing to a full run. Curriculum adds a temporal dimension: the order in which data is presented can matter, with one common pattern reserving the highest-quality or most task-relevant data for late in training, when it most shapes the final weights. Modern recipes — DeepSeek-V3’s among them — visibly upweight code and mathematics for exactly the reasoning benefits this implies. The lesson is that data work is not only about cleaning and deduplication (Sections 6.4 and 6.5) but about composition: a model is, in a real sense, a compression of its data mixture, and choosing that mixture is choosing the model’s priorities.
The mixture is a design choice What proportions of web, code, math, and books go into pretraining shapes the model as much as its architecture — more code improves reasoning, and curriculum ordering can place the best data where it matters most. A model is a compression of its mixture.
6.7 Quality Filtering with Classifiers
Section titled “6.7 Quality Filtering with Classifiers”Deduplication (Section 6.5) removes redundancy, but it does not address quality: the web is full of spam, gibberish, boilerplate, and low-effort text that teaches a model little of value. Filtering this out is one of the highest-leverage things data work can do, and a common technique borrows a model to do it. A classifier is trained to distinguish high-quality text — using a reference corpus of known-good writing, such as curated or reference sources, as positive examples — from ordinary scraped web text, and then used to score every document, keeping the ones it rates as high quality.
The effect is to upweight well-written, informative text in the training mixture, on the premise that a model learns better from good writing than from noise — the pretraining-scale version of “garbage in, garbage out,” which applies with real force here, since a model is in a meaningful sense a compression of its training data (Section 6.6). The technique carries a risk worth naming: a quality classifier trained against a particular reference corpus can encode that corpus’s style as well as its quality, filtering toward a narrow register and quietly reducing the diversity that Section 6.6 identified as valuable. Good filtering therefore balances rigor against breadth, removing genuine junk without homogenizing the corpus into a single voice. That this filtering uses a model to curate the data for the next model is itself a small instance of a theme that recurs at the frontier (Section 42.8) — models increasingly participating in the construction of their own training data, here in the humble but consequential role of separating signal from noise.
Filter for quality, but not into a monoculture A classifier trained to tell good writing from web noise can score and filter a corpus, upweighting informative text — “garbage in, garbage out” at pretraining scale. The danger is encoding the reference corpus’s style and shrinking diversity; good filtering balances rigor with breadth.