SysDesignAtlas

Training Data Pipelines

Crawl, dedup, filter, tokenize, shard, mix — the pipeline that determines model quality more than the architecture does, and the systems problems inside each stage.

HLDHard11 min readaidatadeduppipeline
Confidence

#Why this matters more than the model

The consistent finding across the last several years of published work: at a fixed compute budget, data quality moves benchmark results more than architecture does. Comparable architectures trained on differently-curated corpora differ substantially; architecture variations at the same data quality mostly don't.

That makes the data pipeline a first-class infrastructure system — and it is a genuinely hard one. Processing 15 trillion tokens means moving petabytes through a series of stages, each with its own scaling problem.

  1. 1 Acquire crawl, licensed corpora, code repos
  2. 2 Extract HTML → text, PDF → text, boilerplate removal
  3. 3 Filter language ID, quality heuristics, classifiers, safety
  4. 4 Deduplicate exact and near-duplicate, across the whole corpus
  5. 5 Tokenize & shard to fixed-size binary shards for fast loading
  6. 6 Mix weight sources, order the curriculum
Each stage removes a large fraction of what enters it. The pipeline is mostly a filter.

#Extraction

Turning HTML into text sounds trivial and consumes an unreasonable amount of engineering time. Navigation, ads, cookie banners, and footers are the majority of the bytes on most pages and none of it is content.

Options, in ascending quality and cost: strip tags naively (fast, terrible); heuristic main-content extraction like Trafilatura or Resiliparse (the practical default); or a learned extractor (best, expensive at petabyte scale).

The failure mode to know: boilerplate becomes a duplication problem. The same cookie banner on ten million pages is ten million near-identical passages, and if it survives to training the model over-learns it. Extraction quality and deduplication effectiveness are coupled.

#Filtering

Several independent filters, cheapest first so expensive ones see less data.

FilterMethodRemoves
Language IDfastText classifierWrong-language or mixed-language documents
Heuristic qualityRules: mean word length, symbol ratio, fraction of lines ending in punctuation, stopword presenceMachine-generated pages, keyword spam, navigation dumps
PerplexityScore with a small model trained on known-good text; perplexity measures how surprised the model is by each wordText a language model finds bizarre (high perplexity)
ClassifierTrain on "high quality" (Wikipedia, books) vs random crawlLow-value pages, at scale
SafetyClassifiers plus blocklistsCSAM, extreme content, PII
Benchmark decontaminationn-gram overlap against evaluation setsTest-set leakage

#Deduplication

The stage with the most interesting systems content, and the one with the largest measured quality effect.

Why it matters: duplicated data causes memorisation rather than generalisation, wastes compute on content the model already saw, and creates a train/test leakage risk. Removing duplicates has repeatedly been shown to improve quality and reduce the compute needed.

Two levels:

Exact duplicates are easy in principle: hash every document, group by hash. At 10 billion documents that's a 10-billion-key shuffle — every record is sent across the cluster so that all documents with the same hash land on the same machine. That's large, but a standard batch problem. Most documents appear only once, so a Bloom filter makes a cheap first pass: it can quickly confirm "this hash has definitely not been seen before", and only the possible repeats go on to the expensive grouping step.

Near-duplicates are the hard case, and the common one: the same article on twenty sites with different boilerplate, or a page with one word changed. Hashing doesn't help — change one character and the hash is entirely different — so you need a way to ask "are these two documents mostly the same?" without comparing every pair, which at 10 billion documents would be 50 quintillion comparisons.

   MinHash + LSH, the standard approach

   1. Shingle each document into overlapping n-grams
        "the quick brown fox" → {the quick brown,
                                 quick brown fox}

   2. MinHash: hash all shingles with k independent hash
      functions; keep the MINIMUM under each.
      → a k-element signature per document

      Key property: P(minhash_i(A) == minhash_i(B))
                      == Jaccard(A, B)
      (Jaccard = shingles in common ÷ distinct shingles
       across both documents.)
      So signature agreement estimates similarity.

   3. LSH (locality-sensitive hashing) banding: split the k
      signature values into b bands of r values each.
      Two documents are CANDIDATES if any band matches exactly.

      P(candidate) = 1 − (1 − s^r)^b     for similarity s

      With b=20, r=10 (200 hashes):
                       s=0.9 → 99.98% caught
                       s=0.8 →    90% caught
                       s=0.5 →     2% caught
      → a tunable S-curve, steepest near (1/b)^(1/r) ≈ 0.74:
        pairs well above that similarity are almost always
        caught, pairs well below it almost never are

   4. Verify candidates exactly, then cluster and keep one.

This is the same family of idea as Bloom filters — accept a controlled probability of error to turn an intractable problem into a tractable one.

#Tokenization and sharding at scale

Tokenizing 15 trillion tokens is embarrassingly parallel — every document can be tokenized independently, so you just add machines — and I/O-bound, meaning reading and writing the data takes longer than the tokenizing itself. So the engineering is about output format rather than speed.

   Output: fixed-size binary shards of token IDs

     shard_00000.bin   ~500 MB   uint32 token IDs, packed
     shard_00001.bin   ~500 MB
     ...

   Why this shape:

     · uint32 (or uint16 for small vocabularies) is compact
       and needs no parsing at load time — just mmap (map the
       file straight into memory) and read
     · 500 MB shards are large enough to stream efficiently
       from object storage, small enough to distribute evenly
     · sequences are pre-packed to context length, so the
       loader never has to pad or concatenate
     · an index file records document boundaries, so you can
       stop tokens attending to a different document packed
       into the same sequence, if you want to

Document packing is the detail that matters for efficiency. Training sequences are fixed length; documents are not. Padding each document to 4,096 tokens wastes an enormous fraction of compute. So documents are concatenated with a separator and cut at the context boundary — occasionally splitting a document, which is fine. One sequence may then hold the end of a news article followed by the start of a recipe. Whether to block tokens in the recipe from attending to the article (masking at document boundaries) is a modelling choice, and the masking has a real efficiency cost.

#Mixing and curriculum

The final corpus is a weighted blend, and the weights are a tuned hyperparameter.

   A representative mixture:

     filtered web        60%    breadth
     code                15%    reasoning transfer, not just coding
     books                8%    long-form coherence
     academic / arXiv     6%    technical depth
     Wikipedia            4%    factual density
     Q&A, forums          4%    instruction-like format
     multilingual         3%    non-English capability

   Upsampling: high-quality small sources are repeated
   (2-4 epochs) while web text is seen once. Beyond ~4
   epochs on the same data, returns turn negative and
   memorisation rises.

Curriculum — changing the mixture over training — is common in the late phase: shift toward higher-quality and more instruction-like data for the final few percent of tokens. This "annealing" phase has an outsized effect on the final model's usability relative to its token count.

#The loader

The last mile, and a frequent cause of low MFU.

  • The loader must never stall the GPU. Prefetch several batches ahead, on separate threads, with pinned memory (CPU memory locked in place so the GPU can copy from it directly) for fast host-to-device transfer.
  • Shard assignment must be deterministic and resumable. Rank r at step s must read exactly the same data on a resume, or you replay or skip data silently.
  • Sequence-length balance matters. If ranks get different amounts of real work, they become stragglers. Pre-packing to fixed length solves this by construction.
  • Streaming from object storage beats staging petabytes to local disk, provided you prefetch aggressively enough to hide the latency.

#Check yourself

Why does the data pipeline matter so much?Show answer
At fixed compute, data quality moves results more than architecture. And the pipeline is mostly a filter: roughly 1% of crawled bytes survive.
Name the pipeline stages.Show answer
Acquire, extract text (boilerplate removal), filter (language, heuristics, perplexity, classifiers, safety, decontamination), deduplicate, tokenize and shard, mix.
Why does extraction quality affect deduplication?Show answer
Boilerplate — cookie banners, navigation — repeated across millions of pages becomes millions of near-duplicates the model over-learns.
How do you handle benchmark contamination?Show answer
Flag training documents sharing long n-grams (e.g. 13-grams) with evaluation sets — imperfect — and keep a private evaluation set that was never published.
How do MinHash and LSH find near-duplicates?Show answer
Shingle documents; MinHash signatures agree with probability equal to Jaccard similarity; banding makes documents candidates if any band matches (P = 1 − (1 − s^r)^b), turning O(N²) into roughly O(N).
Why pack documents into fixed-length shards?Show answer
Training sequences are fixed length; padding each document wastes compute. Concatenate with separators into ~500 MB uint32 shards that need no parsing, with an index of document boundaries.
How is the training mixture chosen?Show answer
Weighted sources (web, code, books, papers, Wikipedia, Q&A, multilingual) as tuned hyperparameters; upsample small high-quality sources up to ~4 epochs, and anneal toward high-quality data at the end.
What provenance must be built in from day one?Show answer
Content-addressed inputs and outputs per stage, versioned filters and configs, dataset snapshots with time travel, and a manifest of source IDs — needed for takedowns, contamination checks and reproduction.

#What to carry forward

  • Data quality moves results more than architecture at fixed compute.
  • ~1% of crawled bytes survive to training. The pipeline is mostly a filter.
  • Deduplication has a large measured quality effect; MinHash+LSH turns an O(N²) problem into O(N).
  • Decontaminate benchmarks, then hold out a private evaluation set you never published.
  • Pack documents to fixed-length shards — padding wastes a large fraction of compute.
  • Mixture weights are tuned hyperparameters; late-phase annealing punches above its token count.
  • Provenance must be designed in on day one. It cannot be retrofitted.
00:00
/ 11m