The quality ceiling of a language model is set long before training starts. A model trained on duplicated, boilerplate-heavy, or badly chunked text will memorize junk and hallucinate confidently, no matter how good your optimizer is. This lesson walks through the pipeline that turns raw web crawls, books, code, and proprietary corpora into a versioned, tokenized training set â the same stages used by open pretraining efforts, scaled down to something a small team can run.
You will learn why text pipelines at billions-of-tokens scale behave differently from classical ETL, how to score document quality without a neural classifier, how exact and near-duplicate removal actually work, and how to pack tokenized documents into training examples that respect context windows.
Why LLM data pipelines differ from classical ETL
A traditional ETL job processes structured rows where every record has a schema, a known cardinality, and a small blast radius when it fails. Pretraining data breaks all three assumptions. You are ingesting unstructured text that may arrive hundreds of billions of tokens at a time, the "schema" is only as strong as your heuristics, and a single poisoned source â a scraped forum full of SEO spam, a mirror of the same FAQ repeated ten thousand times â can degrade the finished model for every downstream user.
Three properties dominate the design. First, volume forces streaming: you cannot hold a full web crawl in memory, so every stage must work as a sharded map-reduce style pass over files on object storage. Second, quality is statistical: there is no ground-truth label for "good text," so filters are proxies â length, symbol ratios, perplexity under a small reference model, dedup keys. Third, reproducibility is non-negotiable: if you cannot reconstruct exactly which documents and which filter version produced a checkpoint, you cannot debug a regression three weeks later.
The practical consequence is that pipeline code needs the same rigor as application code: deterministic ordering, per-stage metrics, and dataset snapshots that training jobs reference by immutable ID rather than by a folder path someone might overwrite.
Ingesting from many sources without losing provenance
Every document should carry its origin with it forever. Source name, retrieval timestamp, license hints, and a content hash are cheap to store and invaluable when legal, quality, or debugging questions arrive. The ingestion layer below normalizes heterogeneous inputs into a single RawDocument shape and drops exact repeats at the door using a SHA-256 content hash, so a crawl refresh that re-serves the same pages costs almost nothing downstream.
import hashlib
from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path
from typing import Dict, List, Optional
@dataclass
class RawDocument:
doc_id: str
source: str
content: str
metadata: Dict[str, str] = field(default_factory=dict)
ingested_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
@property
def content_hash(self) -> str:
return hashlib.sha256(self.content.encode("utf-8")).hexdigest()
class IngestionPipeline:
def __init__(self):
self.documents: List[RawDocument] = []
self.seen_hashes = set()
self.dropped_by_hash = 0
def ingest_text(self, text: str, source: str,
metadata: Optional[Dict[str, str]] = None) -> Optional[RawDocument]:
doc = RawDocument(
doc_id=hashlib.md5(text.encode("utf-8")).hexdigest(),
source=source,
content=text,
metadata=metadata or {},
)
if doc.content_hash in self.seen_hashes:
self.dropped_by_hash += 1
return None
self.seen_hashes.add(doc.content_hash)
self.documents.append(doc)
return doc
def ingest_directory(self, root: str, source: str) -> int:
added = 0
for path in sorted(Path(root).rglob("*.txt")):
text = path.read_text(encoding="utf-8", errors="ignore")
if self.ingest_text(text, source, {"path": str(path)}):
added += 1
return added
def source_distribution(self) -> Dict[str, int]:
counts: Dict[str, int] = {}
for doc in self.documents:
counts[doc.source] = counts.get(doc.source, 0) + 1
return counts
In production this runs per-shard with the hash set backed by a compact filter â a Bloom filter for the first pass and an exact on-disk set for verification â because a Python set of hundreds of millions of hashes will not fit comfortably in one process.
Quality filtering: cheap heuristics that catch most garbage
Quality filters do not need to be smart; they need to be cheap and conservative. Most low-value web text announces itself through surface statistics: extremely short pages, walls of punctuation, degenerate repetition, or alphabetic characters outside the expected language range. The scorer below combines four such signals into a single 0â1 quality score and records the rejection reason, which matters enormously when you are tuning thresholds against a downstream eval.
import re
class QualityScorer:
def __init__(self, min_chars: int = 200, max_chars: int = 500_000):
self.min_chars = min_chars
self.max_chars = max_chars
self.sentence_re = re.compile(r"[.!?]")
def score(self, text: str) -> float:
if not (self.min_chars <= len(text) <= self.max_chars):
return 0.0
words = text.split()
if not words:
return 0.0
alpha = sum(c.isalpha() for c in text) / len(text)
if alpha < 0.65:
return 0.0
sentences = self.sentence_re.split(text)
avg_sent = sum(len(s.split()) for s in sentences) / max(len(sentences), 1)
unique_ratio = len(set(w.lower() for w in words)) / len(words)
stop_hit = sum(w.lower() in {"the", "and", "of", "to", "in"} for w in words[:200])
score = 0.0
score += 0.25 if alpha > 0.85 else 0.1
score += 0.3 if 8 <= avg_sent <= 32 else 0.0
score += 0.25 if unique_ratio > 0.4 else unique_ratio
score += 0.2 if stop_hit >= 5 else 0.0
return min(score, 1.0)
def filter_corpus(self, docs, min_score: float = 0.55):
kept, rejected = [], {}
for doc in docs:
s = self.score(doc.content)
if s >= min_score:
kept.append(doc)
else:
bucket = rejected.get("below_threshold", 0)
rejected["below_threshold"] = bucket + 1
return kept, rejected
Teams shipping serious pipelines add a perplexity filter: run a small fixed language model over each document and reject text with implausibly low perplexity (spam and template filler) or implausibly high perplexity (encoding corruption, wrong language). Keep the reference model frozen and versioned, or your filter silently changes meaning between runs.
Deduplication: exact hashes first, near-duplicates second
Exact dedup catches mirrors; near-duplicate dedup catches the harder problem â the same article scraped with different headers, dates, or sidebars. The standard technique is MinHash over shingled text: convert each document into a set of word n-grams, compute many independent minimum hashes, and treat the resulting signature vector as a compact stand-in for the set. Two documents whose signatures agree in most positions have a high estimated Jaccard similarity, and you can then use locality-sensitive hashing to find candidate pairs without comparing everything to everything.
import hashlib
import random
def shingles(text: str, n: int = 5):
words = text.lower().split()
return {" ".join(words[i:i + n]) for i in range(len(words) - n + 1)}
class MinHashDeduplicator:
def __init__(self, num_perm: int = 128, threshold: float = 0.8):
self.num_perm = num_perm
self.threshold = threshold
self.seen = []
self.rng = random.Random(1337)
self._hash_fns = [
(self.rng.getrandbits(64), self.rng.getrandbits(64))
for _ in range(num_perm)
]
def signature(self, text: str) -> list:
sh = shingles(text)
sig = []
for a, b in self._hash_fns:
sig.append(min((a * hash(s) + b) % (1 << 61) - 1 for s in sh) if sh else 0)
return sig
def is_duplicate(self, text: str) -> bool:
sig = self.signature(text)
for other in self.seen:
agree = sum(x == y for x, y in zip(sig, other))
if agree / self.num_perm >= self.threshold:
return True
self.seen.append(sig)
return False
This in-memory version scales linearly and is fine up to a few hundred thousand documents. Beyond that, bucket signatures into bands (the classic LSH trick), store bands on disk, and only run the full Jaccard check inside candidate buckets. Published results show fuzzy dedup removing 5â20 percent of web crawls while measurably improving downstream loss â that is compute you would otherwise waste teaching the model the same paragraph twice.
Tokenization and packing into training examples
Once the corpus is clean, documents become token id sequences, and sequences must be cut into fixed-length training examples. Naively truncating each document wastes context: a 900-token document in a 4,096-token window leaves 3,196 positions of padding. Concatenating tokenized documents with end-of-document separators and slicing uniformly â document packing â raises data efficiency substantially, at the cost of occasionally placing unrelated topics side by side. Most modern runs pack; the small incoherence cost is outweighed by eliminating padding.
class TokenPacker:
def __init__(self, tokenizer, seq_len: int = 4096, eod_id: int = 50256):
self.tok = tokenizer
self.seq_len = seq_len
self.eod_id = eod_id
self.buffer = []
def add_document(self, text: str) -> None:
ids = self.tok.encode(text) + [self.eod_id]
self.buffer.extend(ids)
def drain(self):
while len(self.buffer) >= self.seq_len:
chunk = self.buffer[:self.seq_len]
self.buffer = self.buffer[self.seq_len:]
yield {
"input_ids": chunk[:-1],
"labels": chunk[1:],
}
def flush(self):
leftover = len(self.buffer)
self.buffer = []
return leftover
Watch the label shift: with causal language modeling, labels are the input shifted one position, and the end-of-document token teaches the model where topics end. Keep document boundaries as metadata on every packed example so you can later diagnose cross-document contamination.
Versioning datasets so experiments stay reproducible
A dataset snapshot should be immutable and addressable. Every run trains against a snapshot ID, and every snapshot records the raw source manifest, filter versions and thresholds, dedup parameters, tokenizer version, and resulting token count. Then a regression investigation becomes an archaeology exercise with receipts instead of guesswork.
| Pipeline stage | Typical removal | Cost per 1M docs | Failure mode if skipped |
|---|---|---|---|
| Exact dedup | 5â15% | ~1 ms | Memorization of repeated pages |
| Language / encoding filter | 2â10% | ~0.5 ms | Multilingual drift in a monolingual run |
| Quality scoring | 20â50% | ~5 ms | Boilerplate dominates gradients |
| Fuzzy dedup (MinHash) | 5â20% | ~50 ms | Near-duplicates inflate effective epoch count |
| Toxicity / PII scrubbing | 1â5% | ~10 ms | Compliance exposure, unsafe outputs |
| Length and packing | padding only | ~2 ms | Wasted compute on empty context |
Log the removal percentage at every stage as a first-class metric and alert when it shifts more than a few points between crawls â a sudden jump usually means a source changed format or a filter version drifted, both of which silently poison training.
Common Mistakes
Fuzzy-deduplicating before exact dedup
Fix: Run cheap exact hashing first; MinHash is orders of magnitude more expensive per document.
Tuning filter thresholds without a downstream eval
Fix: Hold out a small validation suite and sweep thresholds against it, not against intuition.
Storing datasets as mutable folders like data/train
Fix: Write immutable, content-addressed snapshots and pin training jobs to snapshot IDs.
Discarding rejected documents entirely
Fix: Keep rejected text with reason codes so you can audit false positives and reprocess later.
Packing documents without recording boundaries
Fix: Store document offsets on each packed example to debug cross-document artifacts.
Best Practices
- Track per-stage keep rates and token counts in a dashboard; drift there is the earliest warning of a bad crawl.
- Fix the tokenizer version alongside the dataset version, since changing either invalidates comparisons.
- Sample and read a few hundred random kept and rejected documents before every big training run; humans catch garbage patterns metrics miss.
- Separate safety filtering from quality filtering so each can be re-run independently on an existing snapshot.
- Measure dedup at the paragraph level as well as the document level; boilerplate footers and nav blocks recur everywhere.
Key Takeaways
- LLM data pipelines are streaming, statistical, and versioned: every stage is a sharded pass with metrics, and every training run references an immutable snapshot.
- Quality filters are deliberately cheap proxies â character composition, sentence length, vocabulary richness, and perplexity â that catch most junk at millisecond cost.
- Exact dedup by content hash removes mirrors; MinHash plus locality-sensitive hashing removes near-duplicates, typically 5â20 percent of a crawl.
- Document packing converts ragged token streams into dense fixed-length examples and usually beats naive padding-based truncation.
- Reproducibility comes from recording source manifests, filter versions, thresholds, and tokenizer versions with every dataset release.