🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

LLM Data Pipelines: Collection, Cleaning, and Dedup

LLMOps in ProductionLLM Data PipelinesđŸŸĸ Free Lesson

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.

python
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.

python
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.

python
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.

python
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 stageTypical removalCost per 1M docsFailure mode if skipped
Exact dedup5–15%~1 msMemorization of repeated pages
Language / encoding filter2–10%~0.5 msMultilingual drift in a monolingual run
Quality scoring20–50%~5 msBoilerplate dominates gradients
Fuzzy dedup (MinHash)5–20%~50 msNear-duplicates inflate effective epoch count
Toxicity / PII scrubbing1–5%~10 msCompliance exposure, unsafe outputs
Length and packingpadding only~2 msWasted 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.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert AI Ops & LLM Ops Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement