Building a Pipeline to Curate Math Training Data from Web Crawls
System DesignModel answerLast updated
Design a daily batch pipeline that turns 100 TB of noisy HTML, PDF and image crawl data into a deduplicated, safe, high-rigor mathematical text corpus for LLM pretraining.
Scenario
Your team trains large language models and wants more high-quality mathematical text: definitions, theorems, proofs, worked derivations and solved problems. The source is a stream of web crawl output that arrives every day as HTML pages, PDF files and standalone images. Most of it is not math. What is math is often badly extracted, repeated across mirrors, or of low quality (broken OCR, symbol soup, thin content).
What you need to build
A batch system that ingests the daily crawl and publishes a clean, versioned, training-ready math corpus.
Functional goals
- Extraction. Convert the different formats into one normalized text representation, with equations preserved in a usable form.
- Quality scoring. Detect mathematical content and rank it by rigor and value, favoring documents with real definitions, arguments and derivations.
- Safety and deduplication. Remove exact and near-duplicate documents, and filter out copyrighted material.
Scale and constraints
- About 100 TB of raw data per day.
- The pipeline is batch, not real time, but it must keep up with daily volume at a sensible cost.
- The final corpus must have a high signal-to-noise ratio. Precision matters more than recall, so borderline documents may be dropped.
What to cover in your answer
- Data pipeline: the stages from raw crawl to final corpus, and how you control cost at this scale.
- Modeling: how you would approach document classification, OCR/extraction of math, and quality scoring, including how you get training labels.
- Storage and indexing: how documents, metadata and versions are stored so that any model's training set can be reproduced.
- Monitoring: how you detect drift and protect training-set quality over time.
State your assumptions and do some back-of-envelope sizing.
Hints
Hint 1
Do the arithmetic first: 100 TB/day is on the order of a billion documents. Expensive steps like GPU OCR or LLM scoring cannot run on all of them, so think of a funnel where each stage is costlier and sees far fewer documents.
Hint 2
Extraction is where math pipelines quietly lose quality. Generic boilerplate removers drop MathML, MathJax and KaTeX content, and PDF text layers are often garbled. Plan format-specific paths and a fallback to math-aware OCR only for documents likely to be worth it.
Hint 3
Labels and thresholds: use a strong LLM with a rubric to label a sample, check it against a small set of human expert labels, and distill into cheap classifiers. Pick filter thresholds by training small proxy models and measuring downstream math benchmarks, and do not forget benchmark decontamination and a persistent cross-day near-duplicate index.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify and size
Assumptions to confirm
- Output is text with math kept as LaTeX, plus metadata.
- Precision beats recall, so we accept losing borderline documents.
- "Copyrighted" is defined by a legal policy: domain and license rules plus fingerprints of known works.
Sizing
- 100 TB/day is about 1.2 GB/s sustained. At roughly 100 KB per document, that is about 1B documents/day.
- Real math content is perhaps 1-2% of a crawl, so about 10-20M candidates/day, and after quality filtering maybe 2-5M survive.
- Math OCR costs about 1 s/page on a GPU and LLM scoring hundreds of ms per document, so neither can touch 1B documents. The design principle is a cost funnel: each stage is about 10x more expensive per document and sees about 10x fewer documents.
2. Pipeline
Raw crawl (object store)
-> 0. Exact dedup (URL + content hash) ~1B
-> 1. Cheap CPU prefilter (high recall) ~1B -> ~100M
-> 2. Format-specific extraction (HTML / PDF / OCR) ~100M
-> 3. Small "is-math" classifier ~100M -> ~15M
-> 4. Near-dup removal (MinHash LSH, global index) ~15M -> ~8M
-> 5. Quality scorer (distilled transformer) ~8M -> ~3M
-> 6. Copyright, PII, benchmark decontamination
-> 7. Mixing/sampling -> versioned training shards
Run as a daily DAG (Airflow or similar) on Spark or Ray. Every stage is idempotent and keyed by doc_id, so failures retry safely and a stage can be re-run with a new model without re-crawling.
Prefilter signals (stage 1): language ID, math markers (\frac, \int, MathJax/KaTeX tags, "Theorem", "Lemma", "Proof."), symbol density, URL and domain priors. Tune for high recall because later stages provide precision.
3. Extraction
- HTML: generic boilerplate removers (trafilatura-style) strip math nodes. Write a custom extractor that converts MathML to LaTeX, reads MathJax/KaTeX source annotations into
$...$, and turns image alt text containing LaTeX into inline math. Preserve code blocks and paragraph structure. - PDF: first check the embedded text layer and score its quality (garbled glyphs, missing operators). If a LaTeX source exists (arXiv-like), prefer it. Otherwise use a math-aware OCR model (Nougat/Marker-style encoder-decoder emitting Markdown + LaTeX). Gate OCR on stage 1 signals from metadata or the first page, so the GPU budget goes to likely-math PDFs.
- Images: low yield. OCR them only when attached to a page already judged mathematical.
- Unified schema:
text,source_format,extractor_version,extraction_confidence. Low-confidence extractions can be dropped or down-weighted later.
4. Classification and quality scoring
| Heuristics | Model-based | |
|---|---|---|
| Cost | microseconds, CPU | ms (small model) to hundreds of ms (LLM) |
| Strength | high-recall prefilter, interpretable | captures rigor, coherence, pedagogy |
| Weakness | gamed by symbol soup, misses prose proofs | costly, can drift, label bias |
Use a cascade: heuristics first (recall), models later (precision).
Labels via LLM-as-judge + distillation
- Sample about 500K stage-3 survivors.
- A strong LLM scores each on a rubric: math content, rigor (definitions, proofs, derivations), correctness signals, coherence, extraction quality (broken LaTeX).
- Calibrate against about 5K expert human labels and measure agreement.
- Distill into a fastText "is-math" classifier (stage 3, iterated by mining more positives and retraining) and a ~100M-parameter transformer regressor (stage 5) outputting a quality score in [0, 1] and a sub-field label.
Threshold choice: do not guess. Train small proxy models (about 1B parameters) on corpora cut at different thresholds and compare on math evals. Optimize downstream training value, not classifier accuracy.
5. Dedup, copyright, contamination
- Exact: hash of normalized text, run first to avoid wasted work.
- Near-duplicate: MinHash LSH over 5-gram shingles with normalized LaTeX (canonical whitespace, so equivalent formulas hash alike). About 128 permutations, ~16 bands x 8 rows, targeting Jaccard of roughly 0.8. Keep a persistent global index across days, since mirrored lecture notes recur and per-day dedup misses them. From each cluster keep the member with the best extraction confidence and quality.
- Copyright/safety: legal allow/deny domain lists, robots.txt and opt-outs, license detection (CC tags, arXiv license field), fingerprints of known commercial textbooks with n-gram overlap removal, and PII scrubbing.
- Decontamination: run long n-gram (e.g. 13-gram) overlap against eval sets such as MATH, GSM8K and AIME, then drop or mask matches. Skipping this makes benchmark numbers meaningless.
6. Storage and versioning
- Raw zone: immutable WARC/PDF files, partitioned by crawl date.
- Curated zone: a lakehouse table (Iceberg/Delta, Parquet), one row per
(doc_id, pipeline_version)withcontent_hash,crawl_date,source_format,extractor_version,lang,math_score,quality_score,subfield,cluster_id,license,decontam_flags,text_uri. - Versioning: time travel lets you reproduce exactly which documents trained a given model. Re-scoring writes new versions or columns and never overwrites.
- Training snapshots: a manifest (query + versions + sampling weights) that materializes into tokenized shards.
- Secondary indexes: the LSH index in a key-value store, plus a doc-to-cluster mapping.
7. Monitoring
- Per-stage funnel metrics: pass rates, counts and latency. A sudden shift in a pass rate often means a crawler or extractor bug.
- Distribution drift: track score histograms, domain mix, sub-field mix, language mix, document length and LaTeX parse-failure rate against a reference window.
- Golden set: a fixed human-labeled set re-scored on every model or extractor change, with alerts on precision regressions.
- Periodic human audit: sample the final corpus weekly and measure the share of low-quality items.
- Downstream signal: regularly train a small proxy model on recent data and track math eval scores.
- Contamination and legal checks: track flagged-document rates and take-down requests.
Trade-offs and common mistakes
- Running OCR or an LLM on everything: cost explodes. Use gating.
- Using a generic HTML extractor: it silently deletes equations.
- Per-day-only dedup: misses cross-day mirrors.
- Tuning thresholds on classifier accuracy instead of downstream training value.
- Overwriting scores in place, which destroys reproducibility.
- Skipping benchmark decontamination.
- Heuristics alone: easily gamed by symbol-heavy junk, and they miss prose-style proofs.