Data and Tokenizer Systems
Language-model behavior begins in the corpus. This stage makes extraction, filtering, deduplication, tokenization, mixing and batch lineage reproducible enough that a model result can be attributed to a real data intervention.
Section 1 of 11 · 11 units · about 46 hours
By the end you can Reproduce an arbitrary training batch from dataset version, seed, shard and position; bound duplicate and evaluation overlap with reviewed evidence; then show a fixed-compute model result for one filtering or mixture intervention.
Units
- Corpus purpose, target population, provenance and usage rights3h
- WARC and HTML text extraction with document boundaries preserved4h
- Language and domain identification, and irreversible normalization decisions4h
- Quality rules, learned quality classifiers and false-positive analysis5h
- Exact deduplication and MinHash near-deduplication thresholds5h
- Benchmark contamination checks, PII masking and harmful-content filtering with stored evidence5h
- Tokenizer fertility, vocabulary disparities and multilingual and code audits4h
- Document packing, boundary tokens and cross-document attention leakage3h
- Mixture weights, temperature sampling, repetition and effective tokens5h
- Deterministic shards, restart position and document-to-batch lineage5h
- Immutable dataset versions, manifests, data cards and checkpoint linkage3h
Build it
Mini project · about 16 to 22 hours
Versioned corpus with replayable token exposure
Create lmlab, the Python and PyTorch repository for your versioned language-model study. Build a bounded corpus pipeline whose filtering decisions, tokenizer costs and training batches can be independently audited on your machine, using pinned libraries from the units and no paid API.
- 1Create
lmlab:data/(corpus/tokenizer/shards),model/(decoders),train/(training/recovery),scaling/(fits),eval/(tasks/graders),adapt/(SFT/distillation),pref/(preferences),rl/(rollouts/updates),mm/(image-text),safety/(attacks/release),registry/(run manifests),tests/andreports/(evidence). Choose a bounded behavior question; retain a source-rights ledger checked against acquisition records. - 2Build a record-preserving WARC iterator and extraction, language and quality stages in
data/. Pass CS336 Assignment 4 extraction, language-ID and quality tests; reuse your language-retention table and hand-label extraction losses and per-rule false positives by slice, retaining intervals and normalization decisions. - 3Deduplicate with collision-safe exact matching and MinHash candidates verified by exact Jaccard. Audit evaluation containment, PII masking and word-list versus classifier harm decisions against planted controls and hand labels; retain clusters, reviewed spans, masked evidence, slice intervals and detector blind spots.
- 4Version the project tokenizer and reuse your FLORES-200 premium table against another tokenizer, checking sentence alignment and totals independently. Add your repository's code slice and indentation perturbation; retain revisions, language-ID retention, fertility and context-budget consequences without comparing cross-tokenizer token losses.
- 5Build packing masks and a token-weighted, epoch-capped mixture sampler. Check packed logits against separate-document execution, document swaps and position offsets; compare realized shares with analytical expectations. Retain boundary, truncation and tail rules, valid-target counts, unique and processed exposure, and assumption-labeled effective-token estimates.
- 6Publish checksummed shards and content-addressed manifests with a bidirectional batch-lineage index. Regenerate arbitrary batches in fresh processes and compare resumed order against uninterrupted iteration; inject corruption and data/tokenizer mismatches. Retain dropped tails, refusal tests and checkpoint links to data, tokenizer and sampler identity.
- 7Gate your small LLM Foundations decoder on frozen-batch loss, gradient, mask and analytical parameter/FLOP-count oracles before matched-token, equally tuned filtered-versus-unfiltered comparisons across paired seeds. Keep held-out outcomes and failed attempts; regenerate artifacts and a Data Cards Playbook card from raw inputs and stage logs.
What you hand in
- The
data/pipeline, tokenizer, checksummed shards and batch-lineage index with independent regression tests. - Source-rights ledger, filter and contamination audits, tokenizer tables and a version-bound data card.
- Matched filtering comparison with held-out records, all-attempt manifests and a clean regeneration transcript.
How to check it
- Self-grade with the rubric below
- CS336 Assignment 4 extraction tests
Pass the extraction fixture; add record-boundary and hand-reviewed main-content checks.
- CS336 Assignment 4 language identification tests
Pass label checks; retain your own per-language threshold and normalization audit.
- CS336 Assignment 4 quality tests
Pass rule and classifier fixtures; they do not establish quality or false-positive rates.
- FLORES-200 parallel-sentence audit
Use aligned sentences as the comparison reference; preserve split, tokenizer revisions and counting checks.
How it's graded
Corpus decisions
Pass: Hand labels and planted controls check pipeline decisions; rights unknowns and masked evidence remain visible. Filtering comparisons follow frozen-batch oracles, matched budgets and paired seeds, preserving held-out outcomes and failed attempts.
Great: A matched unique-data control separates filtering from scarcity; a reviewed near-miss changes a decision and becomes a privacy-preserving regression.
Token exposure correctness
Pass: Your separate-document and perturbation oracles check attention and loss boundaries; analytical shares check the capped sampler. Tokenizer audits distinguish processed, unique and assumed effective tokens.
Great: A document-weighted sampler and a leaking mask each fail targeted regressions before their repairs pass.
Lineage and regeneration
Pass: Fresh-process replay and interrupted-order tests match batch identities; content tampering and identity mismatches fail. Raw-input regeneration reproduces manifests, and checkpoints resolve to source spans.
Great: A deletion request identifies affected batches and checkpoints, while a metadata-only rewrite preserves content identity.
Resources
- CS336 Assignment 4 - DataStanford University
Implement the handout functions in Sections 2.2 to 2.7 (
extract_text,language_identification, the PII masks, the harmful-content classifiers,gopher_quality_filter,classify_quality) and Section 3 (exact_deduplication,minhash_deduplication) until the 21 tests intests/pass on CPU. The 8-GPU leaderboard run is out of reach: replace it with one small local training comparison on a filtered sample and keep the retained-token and source-mix tables as evidence. - CS336 2026 - Data Lectures 13 and 14Stanford University
Step through the Lecture 13 trace (sources: WebText, Common Crawl, CCNet, C4, The Pile, MassiveText, RefinedWeb, Dolma, DCLM, Nemotron-CC, copyright) and the Lecture 14 trace (KenLM and fastText filters, importance resampling, Bloom filters, MinHash and LSH) at
cs336.stanford.edu/lectures/?trace=lecture_13and?trace=lecture_14. Reconcile each lecture claim with your Assignment 4 implementation. - Deduplicating Training Data Makes Language Models Better (Lee et al., 2022)Google Research
Read Section 4 (exact substring matching with suffix arrays, 50-token threshold justified in Appendix B, and MinHash near-duplicate removal) Section 5 (how much each dataset loses, including train-test overlap) and Section 6 (effects on perplexity and memorization). This is the method behind Assignment 4 Section 3; the 50-token threshold is tuned to English web text.
- Dolma ToolkitAllen Institute for AI
Read
docs/data-format.md(stable source and id, attributes aligned row for row),docs/taggers.md,docs/deduplication.mdanddocs/mixer.mdafter your CS336 pipeline works. Its deduplication is a Bloom filter over document keys or paragraphs, with possible false positives, not MinHash; record which production concerns your smaller pipeline omits. - Scaling Language Models: Methods, Analysis and Insights from Training Gopher, Appendix ADeepMind
Read Appendix A.1 for the exact quality rules behind "Gopher-style" filters (50 to 100,000 words, mean word length 3 to 10, symbol ratios, bullet and ellipsis lines, the stop-word test) and A.5 for the datasheet. The rules are English-specific.
- Dolma: an Open Corpus of Three Trillion Tokens for Language Model Pretraining Research (Soldaini et al., 2024)Allen Institute for AI
Read Section 4.2 (data ablations) and Table 1 (the corpus card) as the template for your own data card. The token count depends on the tokenizer used to count.
- FineWeb Paper and DataTrove PipelineHugging Face
Read FineWeb Section 3 (each extraction, filtering and per-snapshot MinHash decision ablated on small models) and trace
examples/fineweb.pyin DataTrove at commit 1977fbb (14 bands x 8 hashes = 112 hashes, 5-gram words).LanguageFilter()with no arguments keeps every language above 0.65, so passlanguagesyourself; the cluster script is a reference, not a local run. - Resiliparse, fastText and datasketch on Four DocumentsOpen source
Build one CPU exercise: extract text with Resiliparse
extract_plain_text(it keeps navigation unless you passmain_content=True), identify language with fastTextlid.176.binandpredict(text, k=1), and find near duplicates with datasketchMinHashLSH. Check every candidate against exact shingle Jaccard: atthreshold=0.9the index uses 5 bands x 25 rows, so it is a candidate filter, not a hard cutoff. - Language Model Tokenizers Introduce Unfairness Between Languages (Petrov et al., 2023)University of Oxford
Read Section 3 (tokenization parity and premium) and Sections 4 and 5 (premiums on FLORES-200, cost and context consequences), then measure the premium of your own tokenizer on a parallel slice.
- Analysing the Impact of Sequence Composition on Language Model Pre-Training (Zhao et al., 2024)University of Edinburgh
Read Section 2 (random, same-source and retrieval packing; causal versus intra-document masking) and Table 1 (perplexity for each strategy). It is the source for testing cross-document attention leakage in your packed batches.
- Documenting Large Webtext Corpora: A Case Study on the Colossal Clean Crawled Corpus (Dodge et al., 2021)Allen Institute for AI
Read Sections 3 to 5: what C4 contains, what its filters removed, and how the blocklist removed text from and about minority groups. Use it to audit the trade-offs of your own PII and harm filters; it audits, it does not propose a recipe.
- Data Cards PlaybookGoogle Research
Follow the guide steps and use the templates to write the card for your filtered corpus: sources, rights, filters with removal rates, known gaps and intended use.
- Modern LLM Notebook - Data EngineeringWalking Labs
Work through
notebooks-en/part2-training/15-data-engineering.ipynb(extraction, quality filtering, deduplication, mixing). Reproduce its compact examples, then compare their assumptions with the stricter CS336 tests. - TensorTonic - Data Processing SetTensorTonic
Solve Perform Stable Exact Deduplication (
cs336-l14-stable-exact-deduplication), Build Deterministic MinHash Signatures (cs336-l14-minhash-signatures) and Compute Temperature-Based Data Mixtures (cs336-l14-temperature-data-mixture). Its MinHash uses SHA-256 of a seed and shingle, so outputs will not match datasketch. Public test cases check the listed edge cases, not gradients or the hidden grader, so keep your own tests beside each solution. - Tokenizer and Corpus PipelineRoadmap-Final
Reuse the project correctness, lineage and contamination contracts. Extend the artifact instead of starting another tokenizer implementation.
- Tulu 3: Pushing Frontiers in Open Language Model Post-Training, Section 3.2Allen Institute for AI
Read Section 3.2 'Prompt Decontamination' (p. 14 of arXiv:2411.15124v5): the comparison of full-string, n-gram and embedding matching, the 8-gram rule on prompts only, the 50% token-coverage test per instance and the 2% rule per dataset. Use it as a worked example of choosing the match unit and thresholds from the evaluation items.
- FLORES-200 parallel sentencesMeta AI
Use the devtest split (1,012 sentences, the same sentences in the same order for every language) to measure tokenizer premiums and per-language language-ID retention. The dataset card lists CC BY-SA 4.0 (page read 2026-10-16). The repository is archived and points to a successor; keep the original release for results you want to compare with Petrov et al.
- Scaling Data-Constrained Language Models (Muennighoff et al., 2023)Hugging Face
Read Section 3.1 (Equation 5, the effective-data term for repeated tokens), Section 6 with Figure 1 (return on compute when repeating data) and Appendix A (the derivation and the fitted constants). Use it to convert epochs into effective tokens and to see how far that fit reaches: models up to 9B parameters on C4 subsets.
- DataComp for Language ModelsDataComp-LM Team
Read Section 4.4 and Table 4 (a fastText classifier keeping the top 10% of documents beat other filters), Figure 4 (removal at each stage) and the Section 3 compute table after the bounded data experiment. The repository dedups with a Bloom-filter tool (BFF), not MinHash, and CORE scores changed between v1 and v2, so never compare them directly.
- Unicode Standard Annex #15: Unicode Normalization FormsUnicode Consortium
Read Sections 1.1 and 1.2: canonical versus compatibility equivalence, the four forms NFD, NFC, NFKD and NFKC, and why the compatibility forms can remove distinctions that matter. Use it to decide which form belongs to a matching key and which, if any, to stored text.
- Hugging Face Datasets: StreamHugging Face
Read Shard, Shuffle, Interleave, and Save a dataset checkpoint and resume iteration, including the tip that shuffle-buffer contents are lost when resuming. Use tiny local data and check resume by comparing document ids with an uninterrupted run; do not stream a web-scale corpus or upload to the Hub.