CS336: Language Modeling from Scratch Lecture 14 — Data II:
Filtering, Deduplication, Mixing, and Post-Training Data

Stanford University
Autumn 2026

The End-to-End LLM Data Pipeline

Crawl / Dump (Lecture 13) Pretraining Data Pipeline (this lecture) 1. Transform HTML/PDF → text 2. Filter lang / qual / tox 3. Dedup exact & fuzzy 4. Mix source weights 5. Post-Training mid-train, SFT, synthetic Pretraining corpora now span tens of trillions of tokens → every stage must scale cleanly

Part 1: Transformation — Raw Data Is Not Plain Text

Source FormatTypical OriginWhat Gets Lost / Hardest Challenge
HTML (main volume)Common Crawl web pagesBoilerplate (nav, ads, footers), tables, inline math, scripts
PDFarXiv, web documents, booksMulti-column layout, equations, figures, truncated crawls
Code RepositoriesGitHub dumps / archivesDirectory hierarchy, cross-file dependencies, commit history

Garbage in, garbage out: extraction quality measurably shifts downstream model accuracy (DCLM).

HTML-to-Text Extraction

Raw HTML Page Nav / Header Main Article+ tables / code Ads Cookie / Footer Images / Captions? Parse Extracted Text DCLM Empirical Finding Re-extracting from raw Common Crawl WARC (HTML) beats using pre-extracted WET plain-text files
  • Core task: strip boilerplate (menus, ads, sidebars) while keeping true article prose
  • Rule-based tools dominate web scale for speed:
    • trafilatura, resiliparse, jusText, lynx
  • Hard edge cases: tables, code blocks, math markup, and image captions often break or vanish
  • Extractor choice matters: DCLM showed better HTML extraction yields measurably stronger models on the same raw crawl

PDF Extraction at Scale: FinePDFs

Common Crawl raw PDF links Recrawl Full File fix truncated PDFs OCR / Parsing RolmOCR (VLM) or Docling Cleanup & Filter post-processing Clean Text training corpus

Next: once raw documents are text, how do we decide what to keep?

Part 2: Filtering as Target Extrapolation

Target Data T small, clean examples Raw Data R huge, noisy web pool Fit score(x) on (T, R) Keep x ∈ R score(x) ≥ τ T' ⊆ R large, similar to T

Scoring Functions: Generative vs. Discriminative

General two-step recipe: (1) fit a fast model from $T$ and $R$ to get $\text{score}(x)$; (2) keep $x \in R$ with $\text{score}(x) \ge \tau$ (deterministically or stochastically).

Generative Model of $T$
$$\text{score}(x) = p_T(x)$$ Example: KenLM ($n$-gram language model) trained on $T$; keep documents with low perplexity.
Discriminative Classifier
$$\text{score}(x) = p(T \mid x)$$ Example: fastText or linear bag-of-words classifier trained with $T$ positive and $R$ negative.

Application 1: Language Identification

Application 2: Domain Filtering — OpenMathText

Goal: curate a large corpus of mathematical writing from Common Crawl via a multi-stage cascade.

Common Crawl raw web pages 1. Heuristic Rules e.g., contains LaTeX commands 2. KenLM (ProofPile) keep if perplexity < 15,000 3. fastText Classifier τ = 0.17 if math-tagged τ = 0.80 otherwise

Historical Baselines: GPT-3 and LLaMA Quality Filters

System (Historical Baseline)Target Positives $T$Negatives $R$Selection Rule
GPT-3 (2020)Wikipedia, WebText2, Books1, Books2Common CrawlLinear word-feature classifier + stochastic Pareto sampling
LLaMA / RedPajama (earlier)Web pages referenced by WikipediaCommon CrawlKeep documents classified positive

GPT-3 stochastic filtering keeps mostly high-scoring pages while letting some lower-scoring pages survive for diversity:

def keep_document(score: float) -> bool:
    return np.random.pareto(9) > 1 - score

LLM-Labeled Quality Filtering: phi-1

Raw R: Python subset of The Stack sample 100K files for labeling LLM Judge (GPT-4) → Target T "educational value for a student learning basic coding concepts" Fast Student Classifier Random forest on pretrained CodeGen embeddings Filtered Subset T' ⊆ R run cheap classifier across all of The Stack
  • Earlier milestone (phi-1): "textbooks are all you need" philosophy for a 1.5B model (mixing GPT-3.5/GPT-4 synthetic data + filtered code)
  • Key pattern: use an expensive LLM to label a small seed ($100\text{K}$), then distill the judge into a cheap classifier
  • HumanEval (1.3B LM):
    • Unfiltered Python Stack: 12.19% after 96K steps
    • Filtered subset: 17.68% after 36K steps

Application 3: Toxicity Filtering (Dolma)

toxic  ·  severe_toxic  ·  obscene  ·  threat  ·  insult  ·  identity_hate

Scale-Dependent Effects of Filtering

Training token budget (log scale) Downstream performance Strict filter (less, higher quality) Looser filter (more data) crossover budget
  • No single optimal filtering threshold exists
  • Short training runs: prefer a strict threshold (less data, higher average quality)
  • Long training runs: need volume—strict filtering shrinks the pool too far and forces excessive epoching
  • Takeaway: choose filtering stringency jointly with total training tokens

Filtering summary: define target $T$ ("what good looks like"), extrapolate to $R$, and tune threshold to your token budget.

Part 3: Why Deduplicate? Exact vs. Near Duplicates

  • Exact duplicates
    • Mirror sites (e.g., Project Gutenberg mirrors)
    • Unmodified GitHub repository forks
  • Near duplicates (differ by a few tokens)
    • Licenses (MIT license) & terms of service
    • Formulaic templates & minor copy-paste edits
Repeated 61,036 times in C4 (historical baseline):
"...by combining fantastic ideas, interesting arrangements, and follow the current trends in the field of that make you more inspired and give artistic touches. We'd be honored if you can apply some or all of these design in your wedding..."

The Deduplication Design Space

  1. What is an item?
    • Sentence, multi-sentence span, paragraph, or full document
  2. How do we define a match?
    • Exact string match, shared sub-item, or fraction of shared sub-items (similarity)
  3. What action do we take on duplicates?
    • Remove all copies, or remove all but one
Core algorithmic challenge: deduplication compares items against all other items. Pairwise comparison costs $O(N^2)$—at web scale we need linear-time algorithms using hashing.

Hash Functions: Speed vs. Collision Resistance

FamilyExamplesCollision ResistanceSpeed & Typical Use
CryptographicSHA-256Adversarially collision resistantSlow — security, Bitcoin
Non-cryptographicDJB2, MurmurHash, CityHashNot adversarially resistantVery fast — hash tables, data pipelines
import mmh3
h = mmh3.hash("hello")   # fast 32-bit MurmurHash3

For deduplication over trillions of tokens, throughput dominates: non-cryptographic hashes are the standard choice.

Exact Deduplication & The MapReduce Pattern

Spec: item = string, match = exact hash match, action = keep one per hash group.

import itertools, mmh3

items = ["Hello!", "hello", "hello there", "hello", "hi", "bye"]
hash_items = itertools.groupby(sorted(items, key=mmh3.hash), key=mmh3.hash)
deduped_items = [next(group) for h, group in hash_items]

Near-Duplicate Similarity: Jaccard Similarity

Set A Set B "4" "1" "2" "3" "5" |A ∩ B| = 3, |A ∪ B| = 5

$$\text{Jaccard}(A, B) = \frac{|A \cap B|}{|A \cup B|}$$

  • Represent each document as a set of sub-items (e.g., $n$-grams / shingles)
  • Near duplicates: $\text{Jaccard}(A, B) \ge \tau$
  • Example: $A = \{1,2,3,4\}$, $B = \{1,2,3,5\} \implies \frac{3}{5} = 0.6$
def compute_jaccard(A, B):
    return len(A & B) / len(A | B)

Challenge: how do we find all document pairs with $\text{Jaccard}(A, B) \ge \tau$ in linear time?

MinHash: Collision Probability Equals Similarity

Characteristic matrix

Item$A$$B$If min?
111match
211match
311match
410differ
501differ
MinHash property: random hash $h$ satisfies $$\Pr[h(A) = h(B)] = \text{Jaccard}(A, B)$$
def minhash(S: set[str], seed: int):
    return min(mmh3.hash(x, seed) for x in S)
  • Normally we minimize collisions; here we want collision probability to track similarity
  • Proof: a random hash induces a uniform permutation over $A \cup B$; every element is equally likely to appear first (the min)
  • First element in $A \cap B$ ($\{1,2,3\}$) $\iff$ $h(A) = h(B)$ (3 of 5 = $0.6$)

Locality-Sensitive Hashing (LSH): Banding MinHash

Band 1 (r = 4 hashes) h₁ h₂ h₃ h₄ Band 2 (r = 4 hashes) h₅ h₆ h₇ h₈ Band 3 (r = 4 hashes) h₉ h₁₀ h₁₁ h₁₂ ALL r match (AND) ALL r match (AND) ALL r match (AND) Candidate Pair if ANY band matches (OR)

The AND-OR composition sharpens the linear collision probability into an S-shaped threshold curve.

LSH Collision Probability Derivation

Let $s = \text{Jaccard}(A, B)$ with $b$ bands of $r$ independent MinHash functions ($n = b \cdot r$):

  1. Probability a single hash matches: $s$
  2. Probability a fixed band matches (all $r$ hashes match): $p_{\text{band}} = s^r$
  3. Probability a fixed band does not match: $1 - s^r$
  4. Probability no band matches across all $b$ bands: $(1 - s^r)^b$
$$\Pr[A \text{ and } B \text{ collide}] = 1 - (1 - s^r)^b$$
def get_prob_collision(sim: float, b: int, r: int) -> float:
    prob_match = sim ** r
    return 1 - (1 - prob_match) ** b

Check: for $s = 0.8, b = 5, r = 10$, we get $p_{\text{band}} = 0.8^{10} \approx 0.107$ and $\Pr[\text{collision}] \approx 0.433$.

Tuning the S-Curve: Effects of $b$ and $r$

Jaccard similarity s Pr[collision] 0 0.5 0.8 1.0 0 0.5 1.0 b=1, r=1 b=10, r=10 b=20, r=20 b=10, r=20
  • Increasing $r$ sharpens the transition and shifts it right (harder to match)
  • Increasing $b$ shifts the curve left (easier to match)
$s$$10,10$$10,20$$20,20$
0.700.2490.0080.016
0.800.6790.1090.207
0.850.8880.3270.546
0.900.9860.7260.925
0.951.0000.9881.000

LSH Phase Transition & Web-Scale Setting

$$t = \left(\frac{1}{b}\right)^{1/r}$$

Part 4: Data Mixing — Balancing Multiple Sources

Example Mixture p(s) CC: 0.50 Wikipedia: 0.30 GitHub: 0.20 Real corpora span dozens of sources (historical: The Pile; open: Marin)
  • Question: what sampling distribution $p(s)$ over sources should we train on?
  • Simple baselines:
    • Vibes / manual: hand-tuned weights (very common)
    • Uniform: $p(s) \propto 1$
    • Proportional: $p(s) \propto \text{tokens}(s)$
  • Why not just upweight high-quality sources?
    • Need diversity across incomparable domains (literature, code, papers)
    • Every source is finite → too much weight forces heavy epoching

The Epoching Trap: Finite High-Quality Reservoirs

Abundant ("low"): 10T tokens p(low) = 0.5 → 500B drawn Scarce ("high"): 10B tokens p(high) = 0.5 → 500B drawn Training Run Ntrain = 1T tokens low epochs = 0.5T / 10T = 0.05 epochs high epochs = 0.5T / 10B = 50× epochs! (overfit)

Controlling Epochs: Power-Law Scaling & UniMax

UniMax prevents runaway repetition, but still treats all uncapped sources symmetrically—can we optimize weights directly?

Regression-Based Data Mixing (RegMix)

1. Sample Mixtures p⁽ⁱ⁾ ~ Dirichlet 2. Small Proxy Runs train & eval target 3. Fit Surrogate L̂(p) linear / boosted trees 4. Optimize p* = argmin L̂(p) 5. Full Run train at scale

When Hope 2 Breaks: Scale-Dependent Epoching

Consider the same two pools: low = 10T tokens (abundant), high = 10B tokens (scarce).

Run ScaleMixture $p = (\text{low}, \text{high})$Tokens Drawn from highEpochs on highOutcome
Small proxy ($10\text{B}$ tokens)$(0.1,\; 0.9)$$9\text{B}$0.9 epochsLooks great (no repetition)
Large target ($1\text{T}$ tokens)$(0.1,\; 0.9)$$900\text{B}$90 epochsSevere overfitting!

Fix: Simulated Epoching

Naive Small Proxy (10B run, full pools) low: 10T | high: 10B p = (0.1, 0.9) → only 0.9 epochs on high Hides overfitting → bad optimum for 1T run Simulated Epoching (downsample by ρ = 0.01) low: 100B | high: 100M p = (0.1, 0.9) → 90 epochs (matches 1T run!) Proxy prefers balanced mix: p = (0.7, 0.3)
  • Core principle: make small-scale runs faithfully mirror large-scale dynamics
  • Method: downsample every source by $\rho = N_{\text{small}} / N_{\text{large}}$
ratio = 10e9 / 1e12  # 0.01
downsampled = {
    s: count * ratio
    for s, count in counts.items()
}
  • Over-epoching now hurts the proxy run itself, shifting the optimum toward realistic large-scale weights

Part 5: Post-Training & Synthetic Data

1. Define Environments math, code repos, sandboxes 2. Define Tasks / Prompts real, semi-synthetic, synthetic 3. Collect Teacher Data rollouts, trajectories, filtering

Reasoning Distillation: OpenThoughts

Lesson: never assume a recipe transfers without ablating teacher choice, sampling multiplicity, and filtering.

Semi-Synthetic Coding Tasks: SWE-smith

Real GitHub Repo working environment tests pass ✓ LM Injects Bug edits functions / logic to synthesize a defect Run Test Suite keep only edits that break existing tests ✗ Verifiable Task buggy repo + gold fix & tests

Scaling Real Interactive Environments: SWE-rebench

450K GitHub PRs GitHub + GitHub Archive Automated Setup & Screening Qwen 2.5-72B-Instruct (earlier baseline) installs dependencies & judges PR quality 21K Python SWE Tasks across 3.4K GitHub repos

Decoupling Execution: SWE-Zero

SWE-Zero (No Repo Execution) 150K GitHub PRs → 300K trajectories OpenHands scaffold (future git commits stripped) Teacher: Qwen3-Coder-480B + post-hoc filtering (try executing anyway) Rely on model's internal "world model" of code SWE-Hero (With Execution Feedback) 13K agent trajectories Targeted tasks where live test execution is essential
  • Key insight: strong coding models hold an internal "world model" of code semantics and solve many issues without running tests
  • Data hygiene matters: removing future git commits prevents "git hacking" (agents peeking at the fix in git history)
  • Hybrid strategy: generate bulk trajectories execution-free (SWE-Zero), then supplement with execution-verified runs (SWE-Hero)

Scaling Trajectories: SWE-ZERO-12M-trajectories

Tradeoff: high-volume sampling from a small, fast generator turns non-executable repositories into millions of training trajectories—provided filtering catches low-quality traces.

Post-Training Data: Design Taxonomy & Tradeoffs

Prompt / Task ParadigmExamplesStrengthsMain Bottlenecks
Fully syntheticSynthetic slices of OpenThoughtsUnlimited scale, full topic controlDiversity collapse, teacher bias
Semi-syntheticSWE-smith (128 repos → 50K tasks)Real codebases + verifiable testsSynthetic bugs may differ from real PRs
Real tasksSWE-rebench (21K), SWE-Zero (300K), SWE-ZERO-12MAuthentic developer distributionContainer setup, git hacking, noisy PRs

Lecture 14 Recap

  1. Transformation: raw HTML, PDFs, and repos are inherently lossy to linearize; extractor quality (trafilatura/resiliparse, FinePDFs OCR/Docling) directly moves model quality
  2. Filtering: formulate as extrapolating target $T$ onto raw $R$ with fast scorers (KenLM, fastText, LLM-distilled classifiers); optimal threshold depends on training token budget
  3. Deduplication: hashing scales matching to linear time; MinHash + LSH ($b$ bands of $r$ hashes) sharpens Jaccard matching around $t = (1/b)^{1/r}$
  4. Data Mixing: balance quality, diversity, and finite pool sizes using epoch caps (UniMax) or regression + simulated epoching so small-scale optima transfer
  5. Post-Training Data: combine environments, tasks (real / semi-synthetic / synthetic), and capable teachers—scaling to multi-teacher distillation in late-2026 frontier models

Above all: data work is domain-specific—there is no substitute for inspecting real examples at every stage.