Chapter 5: Corpus Pipeline
A training corpus is the output of a program, and like any program it has bugs, tests, and provenance. This chapter treats the corpus as code: stages with typed interfaces, tests on hand-labelled fixtures, a manifest with content hashes, and a ledger that answers “where did this text come from, and may we use it?” for every shard. The payoff is concrete. Data quality bounds model quality: filtering, deduplication, and decontamination change a model’s loss and its benchmark numbers more than most architecture choices at small scale, and the FineWeb paper documents each filter’s measured effect.
Concepts from other sections (13)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- Pinned checksum: the sha256 recorded in the config after review; the only digest fetch trusts. Read more: 5.1 Async fetch with resume, checksums, and license capture
- Perplexity: , the geometric mean of ; the effective number of choices per token. Read more: 17.2 Perplexity, bits per byte, NLL accumulator in Mathematics
- Bloom filter: a bit array with hash functions that has no false negatives and a tunable false-positive rate. Read more: 5.3 Exact dedup: paragraph hashes, a Bloom screen, and a sort-merge confirm
- MinHash signature: the minima of hash functions over a document’s shingles; equal entries estimate Jaccard. Read more: 5.4 Near-duplicate dedup: MinHash, LSH, union-find, and decontamination
- LSH banding: splitting signatures into bands of rows so only documents sharing a whole band are compared. Read more: 5.4 Near-duplicate dedup: MinHash, LSH, union-find, and decontamination
- Union-find: a disjoint-set forest that merges confirmed pairs into clusters; here rooted at the smallest id. Read more: 5.4 Near-duplicate dedup: MinHash, LSH, union-find, and decontamination
- Typed placeholder: a token such as
<EMAIL>that replaces a match and names its kind. Read more: 5.5 PII scrub with typed placeholders and audit spans - MinHash: estimating Jaccard similarity by how often the minima of random permutations agree. Read more: 12.5 Discrete math 2 problem set, part b: trees, birthday bounds, MinHash and LSH, Bloom filters, recurrences in Mathematics
- Ledger row: one JSON record per fetched source with its URL, license, digest, time, and document count. Read more: 5.1 Async fetch with resume, checksums, and license capture
- NFC: Unicode canonical composition; equal text gets equal bytes without rewriting compatibility characters. Read more: 5.2 Extract, normalize, and quality filters
- Gopher rules: seven cheap document statistics with published thresholds for filtering web text. Read more: 5.2 Extract, normalize, and quality filters
- Bits per byte (bpb): , total information divided by the UTF-8 length; comparable across tokenizers. Read more: 17.2 Perplexity, bits per byte, NLL accumulator in Mathematics
- SPDX expression: a combined license where
ORmeans choice (union of uses) andANDmeans both apply (intersection). Read more: 5.8 Licensing ledger verification and the datasheet
The chapter builds one pipeline, end to end, over a single Doc type. It starts by fetching sources with resumable downloads, pinned checksums, and license capture. It then composes streaming stages, each a generator so memory stays flat on any corpus size: Unicode normalization, language identification, the Gopher quality rules, repetition and perplexity filters. Deduplication comes in two halves: exact (paragraph hashes screened by a Bloom filter and confirmed by sort-merge) and near (MinHash signatures, LSH banding, union-find clusters), with decontamination against eval sets as near dedup’s sibling. A PII scrub replaces personal data with typed placeholders. The survivors are written as hash-split Parquet shards with a manifest, tokenized and packed into llm.c .bin files, and checked against the licensing ledger, which also generates the datasheet. The last section wraps the whole pipeline as CorpusBuild, a durable workflow that survives worker kills and cleans up after cancels.
Two properties run through every section. Every output byte traces to a licensed source: a shard whose source is unknown or not allowlisted fails the build. And determinism is a feature: the same config gives the same output hash regardless of worker count, which is what makes the durable, resumable pipeline of the final section possible. The pipeline is complete when, built from the small reference corpus config, its shards, manifest, ledger, and .bin files match the format contracts with a deterministic output hash across two runs and across worker counts 1 and 4.
Learning objectives
- Build a corpus pipeline as composed streaming stages over one document type, with flat memory on any corpus size.
- Remove exact and near duplicates correctly and at scale, and decontaminate a corpus against protected eval sets.
- Scrub PII with typed placeholders and an audit trail that never copies the PII.
- Write sorted, hash-split Parquet shards and llm.c token files with manifests whose bytes are a function of the input.
- Verify that every row of training text traces to a license that permits training, and generate a datasheet from the files.
- Run the pipeline as a durable workflow whose output hash does not depend on kills, retries, or worker count.
Before you begin
Section titled “Before you begin”You should be comfortable with the material in Foundations and with columnar files from Storage and Warehousing. The fetch stage uses Python asyncio from Programming and Algorithms, and the ledger and PII sections enforce policies argued in AI Engineering: Data licensing and the ledger and Privacy and PII policy. The dedup sections use the Bloom filter from A Bloom filter in Programming and Algorithms and the hashing of Modular arithmetic, hashing, and PCG32 in Mathematics. The tokenize section runs the tokenizer of Tokenizers in AI Engineering, and the final section runs on the engine of Durable Orchestration and Workers in Systems Engineering, so read that chapter before the last section. A good warm-up is to work the MinHash and LSH chapter of Mining of Massive Datasets by hand for a 3-band example.
In this chapter
Section titled “In this chapter”- Async fetch with resume, checksums, and license capture: download each configured source with HTTP Range resume, verify it against the pinned sha256, quarantine mismatches, and write one ledger row per source so reruns cost nothing.
- Extract, normalize, and quality filters: define the
DocandStagetypes every later stage shares, and build idempotent NFC normalization, stop-word language identification, the Gopher rules, and repetition and perplexity filters. - Exact dedup: paragraph hashes, a Bloom screen, and a sort-merge confirm: keep the first occurrence of every paragraph using a Bloom filter that only nominates candidates and a sort-merge that confirms them, so no unique paragraph is ever dropped.
- Near-duplicate dedup: MinHash, LSH, union-find, and decontamination: find almost-copies in roughly linear time, cluster them deterministically, and drop any document that shares a 13-gram with a protected eval set.
- PII scrub with typed placeholders and audit spans: detect emails, phones, cards, IPs, and keys with regex-plus-validator detectors, redact them, and record kinds and offsets under a per-source policy.
- Parquet shards, the manifest, and the document-hash split: write sorted, zstd-compressed shards split by the hash of each text, with a manifest that is the output’s identity, swapped in atomically.
- Tokenize and pack to llm.c .bin: turn each split into memory-mappable token files with separators, whole-document rollover, exact conservation, and the bytes-per-token factor for bits per byte.
- Licensing ledger verification and the datasheet: evaluate SPDX expressions against an allowlist, join the ledger with every shard row, fail with a non-retryable exit 65, and generate the datasheet.
- CorpusBuild: the pipeline as a durable workflow: run fetch, shard, and tokenize as activities keyed by the config’s content hash, so kills resume and cancels clean up.
Where this chapter connects
Section titled “Where this chapter connects”The Parquet layout behind the shard writer comes from Storage and Warehousing, and Orchestration and Modeling covers Airflow and dbt, the conventional alternatives to the durable workflow of the last section. The corpus this chapter builds is the one TinyStories, owned end to end in AI Engineering trains on.
The same practices appear across the field. Hugging Face’s FineWeb and datatrove are documented, reproducible web-scale filtering; the Allen Institute for AI’s Dolma is an open corpus with its toolkit and datasheet; and every frontier lab decontaminates against eval sets before reporting benchmark numbers.
Further reading
Section titled “Further reading”- Penedo et al., The FineWeb Datasets: read it end to end; it documents each filter’s measured effect.
- Soldaini et al., Dolma.
- Hugging Face, datatrove (Apache-2.0): skim its pipeline stages alongside this chapter.
- Lee et al., Deduplicating Training Data Makes Language Models Better.
- Broder, On the Resemblance and Containment of Documents (1997): the origin of MinHash.
- Rae et al., Scaling Language Models: Methods, Analysis & Insights from Training Gopher: the Gopher quality rules.
- Leskovec, Rajaraman, and Ullman, Mining of Massive Datasets, chapter 3.