Unit 6 of 11 · about 5 hours · implement, measure
Benchmark contamination checks, PII masking and harmful-content filtering with stored evidence
A contaminated benchmark makes a data intervention look better than it is, and a careless PII or harm filter removes useful text from the people the corpus was meant to serve. Both need a stored record of what matched, so that someone else can check the decision.
You'll be able to
- Implement a train-versus-evaluation overlap check whose match unit, normalization and threshold you can justify for the evaluation task, and store each match with both ids and the matched span for review.
- Implement regex masks for emails, phone numbers and IPv4 addresses, review their false positives and false negatives on real text, and keep the evidence without keeping the personal data itself.
- Compare a word-list and a classifier harmful-content filter by what they remove, at which thresholds and from which groups, using a sampled audit with intervals.
Covers
Read
In this order, only the parts listed
0 of 6 done
- CS336 Assignment 4 handoutCS336 Assignment 4 - Data
Section 2.4, Personally identifiable information, with Problem (
mask_pii) (pp. 5 to 6); Section 2.5, Harmful content, with Problem (harmful_content) (pp. 6 to 7); and the rule in Section 4 that validation text must not be copied into training data (p. 12) - Gopher, Appendix A (Rae et al., 2021)Scaling Language Models: Methods, Analysis and Insights from Training Gopher, Appendix A
Appendix A.1, 'Document Deduplication' and 'Test-set Filtering' (p. 41): 13-gram Jaccard above 0.8 between whole documents
- Tulu 3 (Lambert et al., 2024)Tulu 3: Pushing Frontiers in Open Language Model Post-Training, Section 3.2
Section 3.2 'Prompt Decontamination' (p. 14): why n-gram matching beat full-string and embedding matching, the 8-gram rule on prompts only, the 50% token-coverage test per instance, and the 2% rule per dataset
- Documenting Large Webtext Corpora (Dodge et al., 2021)Documenting Large Webtext Corpora: A Case Study on the Colossal Clean Crawled Corpus (Dodge et al., 2021)
Section 4.2 (benchmark contamination: input versus input-and-label) and Sections 5.1 to 5.3 (what the word-list blocklist removed, and from whom)
- Dolma (Soldaini et al., 2024)Dolma: an Open Corpus of Three Trillion Tokens for Language Model Pretraining Research (Soldaini et al., 2024)
Section 5.3 'Content Filtering': the toxicity thresholds and what each removed, and the regex PII filter for emails, IP addresses and phone numbers
- DataComp-LM (Li et al., 2024)DataComp for Language Models
Section 4.6 'Decontamination' and Table 7
Optional. Read how the match is defined (the question text plus one answer option, and only the last sentence of long MMLU questions) and the authors' remark that this still gives many false positives.
Focus on
- Contamination is overlap between one named evaluation set and your training text, and the unit of overlap depends on the task. A 13-gram test on whole documents cannot see a six-word question. Compare the designs: Gopher (whole-document 13-gram Jaccard), Tulu 3 (8-grams, prompts only, token coverage), DCLM (question plus an answer option).
- Use containment, not Jaccard, when a short item may sit inside a long page: Jaccard divides by the union and the page dominates it. Count the share of the item's tokens or n-grams found in the training text.
- A detector reports what it can see. Paraphrases and answer-only text have no shared n-grams with the question, and an item with fewer than n tokens cannot match at all. Report 'no verbatim overlap at n = 8', not 'clean', and review every match by hand.
- PII and harm filters are precision-recall trades. Dolma masks only emails, IP addresses and phone numbers because regexes find those with high precision; its two toxicity thresholds removed 5.5% to 7.3% of content or 29.1% to 34.9%. Dodge shows a word list removing text from and about minority groups at unequal rates, so report removal by slice.
Common mistakes · 3
- Choosing the match unit from the dataset you have read about instead of from the evaluation items. With the Maria item inside a page of 200 filler sentences, 13-gram Jaccard is below 0.01 while containment is 1.0, so a Jaccard-above-0.8 rule would miss a verbatim copy; and an item of fewer than n tokens never matches any n-gram at all, so add an exact normalized full-string check.
- Reading zero matches as 'not contaminated'. The detector sees surface overlap only: the paraphrase scored 0.0 in the reproduce step, an answer-only passage shares no n-gram with its question, and the changed-number copy fell below the 50% rule at n = 8. State what the detector cannot establish, and review a sample of matches and of near-misses.
- Storing the evidence in a way that recreates the harm. An audit file of raw emails and phone numbers is itself a PII leak, so store the type, offsets, a keyed hash and a masked excerpt. Also keep the unmasked counts: a mask string such as
|||EMAIL_ADDRESS|||can already occur in the text, and only real emails should be counted.
Try it yourself
Closed-book, before checking anything
coverage(test, train, n) that returns the share of the test item's lowercase \w+ tokens lying inside at least one n-gram that also occurs in the training text. Use n = 8 on Maria has 12 apples and buys 15 more at the market. She gives 9 apples to her neighbour. How many apples does Maria have now? against four training texts: the item inside a longer page, a copy with 12, 15 and 9 changed to 14, 17 and 11, a copy with local inserted before market, and a paraphrase. You should get 1.0, 0.44, 1.0 and 0.0. Say which of the four a rule 'more than 50% covered' flags, and what the numbers become at n = 4 (1.0, 0.68, 1.0, 0.0) and n = 13 (1.0, 0.0, 0.6, 0.0).Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.A training page contains an evaluation question verbatim among 200 other sentences. Why does a 'Jaccard above 0.8 on 13-grams' rule miss it, and what would catch it?Answer
The union of n-grams is dominated by the page, so the Jaccard similarity is tiny (below 0.01 for the Maria item in a 200-sentence page). The share of the question's n-grams that appear in the page, its containment, is 1.0 and would catch it.
2.An evaluation item has six words and you check 8-grams. What happens, and what do you do?Answer
The item has no 8-grams, so it can never be flagged and the check passes silently. Add an exact match on the normalized full item, or a smaller n with manual review, for items shorter than n.
3.With n = 8, a copy of a math problem with three changed numbers has 44% token coverage. Does a 50% rule flag it, and does it matter?Answer
No, it is just below the rule. It matters because the problem structure and its solution pattern are still in the training text. Use a lower coverage threshold or a number-masked comparison and review the matches; the right threshold depends on the item length and the number of edits.
4.Why does Dolma mask only emails, IP addresses and phone numbers?Answer
Those can be matched with regular expressions at high precision and web-scale speed. Names and addresses need a model-based detector, which is slower and less precise. The cost is recall: anything the patterns miss stays in the data, so the card should say so.
5.A word-list filter removes 6.2% of one group's documents and 42% of another's, as estimated by a dialect model. What does an overall removal rate of, say, 8% hide?Answer
It hides the unequal removal by group. The corpus would underrepresent the second group's text, which counts as a loss if that group is in the population stated in the corpus purpose. Report removal by slice and review a sample of removed text per slice.
Practice
- CS336 Assignment 4: PII masks and harmful-content classifiers
Problems (
mask_pii) and (harmful_content); connectrun_mask_emails,run_mask_phone_numbers,run_mask_ips,run_classify_nsfwandrun_classify_toxic_speechintests/adapters.pyand pass the five tests intests/test_pii.pyand the two intests/test_toxicity.pyThe toxicity tests are sanity checks on two Jigsaw examples, as the handout says; they do not validate the classifier. Do the review parts (e) and (d) on 20 masked or flagged documents each and report error rates with intervals. Implement it in your own repository.
- CS336 Assignment 4: keep the validation text out of training
Section 4 (p. 12): you may use the validation data to build filters but must not copy any of it into training data
Write the check that proves it for your filtered set, with stored matches: n-gram containment of the validation tokens in your training tokens, the matched spans, and a decision after review. The section mini-project covers the audit on your own corpus and an evaluation set of your choice.
You're done when
Your mask and classifier code passes the seven tests, and for one evaluation set you have a stored table of overlap matches with the n, the rule, the reviewed decision and a statement of what the detector cannot see.
Only when you can do this without notes.
Leads to
- Immutable dataset versions, manifests, data cards and checkpoint linkageRecord the match rules, thresholds and removal counts in the data card and manifest.
- Contamination and memorization, benchmark saturation and capability versus elicitationThe evaluation section treats contamination from the benchmark side.
Notes
Resources · 6 for this unit, 15 more in the section
- CS336 Assignment 4 - DataStanford University · primary
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. - Scaling Language Models: Methods, Analysis and Insights from Training Gopher, Appendix ADeepMind · support
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 · support
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.
- Documenting Large Webtext Corpora: A Case Study on the Colossal Clean Crawled Corpus (Dodge et al., 2021)Allen Institute for AI · support
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.
- DataComp for Language ModelsDataComp-LM Team · depth
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.
- Tulu 3: Pushing Frontiers in Open Language Model Post-Training, Section 3.2Allen Institute for AI · support
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.
Also in this section
- CS336 2026 - Data Lectures 13 and 14Stanford University · required
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 · required
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 · required
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. - FineWeb Paper and DataTrove PipelineHugging Face · support
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 · support
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 · support
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 · support
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.
- Data Cards PlaybookGoogle Research · support
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 · support
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 · support
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 · support
Reuse the project correctness, lineage and contamination contracts. Extend the artifact instead of starting another tokenizer implementation.
- Unicode Standard Annex #15: Unicode Normalization FormsUnicode Consortium · reference
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.
- FLORES-200 parallel sentencesMeta AI · support
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 · support
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.
- Hugging Face Datasets: StreamHugging Face · reference
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.