Unit 4 of 11 · about 5 hours · implement, measure
Quality rules, learned quality classifiers and false-positive analysis
Quality filters are the first data intervention that moves model results, and also the first that removes whole kinds of text by accident. Counting only what survives hides the false positives, so the audit of removed text is the measurement.
You'll be able to
- Implement the Gopher-style rules from the handout so that each decision returns the name of the rule that failed, and say which rules of the original paper you left out.
- Train a fastText quality classifier from a reference set and a raw set, and choose its threshold from a held-out labeled sample using precision and recall with intervals.
- Find the false positives of each filter by slice (language, kind of text, length), report how many documents and tokens it removes, and say which removals you would reverse.
Covers
Read
In this order, only the parts listed
0 of 5 done
- CS336 Assignment 4 handoutCS336 Assignment 4 - Data
Section 2.6, Quality Rules, with Problem (
gopher_quality_filters) (pp. 7 to 8), then Section 2.7, Quality Classifier, with Problem (quality_classifier) (pp. 8 to 9) - Gopher, Appendix A (Rae et al., 2021)Scaling Language Models: Methods, Analysis and Insights from Training Gopher, Appendix A
Appendix A.1, the 'Quality Filtering' paragraph (p. 40) and the 'Repetition Removal' paragraph with Table A1 (pp. 40 to 41)
- CS336 2026 Lecture 14: Data II (executable trace)CS336 2026 - Data Lectures 13 and 14
The
filteringstep: the target-versus-raw framing, the generative (KenLM) and discriminative (fastText) classifiers, 'Model-based filtering?', the GPT-3, LLaMA and textbook-quality code-model examples, and 'Scale-dependent effects of filtering' - Dolma (Soldaini et al., 2024)Dolma: an Open Corpus of Three Trillion Tokens for Language Model Pretraining Research (Soldaini et al., 2024)
Section 5.2 'Quality Filtering' with its footnote 4 on why 'quality' is an ideological label, and Section 4.2 for the ablation method
- DataComp-LM (Li et al., 2024)DataComp for Language Models
Section 4.4 with Table 4 (filter comparison) and Table 5 (reference data and threshold)
Optional, after your own filtered-versus-unfiltered comparison. Read the numbers as that paper's results on its pool and recipe; do not compare its CORE scores with other papers' scores.
Focus on
- Each rule is a guess about what bad text looks like, written for English prose. The handout implements four of Gopher's rules: word count, mean word length, lines ending in an ellipsis, and the share of words with a letter. The paper also has a stop-word test, a symbol-to-word ratio, a bullet-line rule and the repetition thresholds of Table A1.
- A learned filter is a classifier of 'looks like the reference set', not of quality. The reference set decides what it learns: in DCLM Table 5 the choice of positive data moved CORE by more than five points at the same top-10% threshold (7B-1x scale, that paper's setup).
- The threshold trades quantity for quality, and the right value depends on the token budget. The lecture's scale-dependent effects slide and the DCLM top-10% result both belong to one recipe, so a threshold from one run does not transfer.
- The audit is the result. For every filter, keep the removed documents, sample them, and report the false-positive rate with an interval for each slice.
Common mistakes · 3
- Reading a passing test as evidence of quality. The handout's tests use constructed strings that each break one rule, so they check the thresholds and say nothing about false positives on real pages.
test_classify_qualitychecks only two fixture texts. - Calling the handout's four rules 'the Gopher filter'. State the rules you ran. The stop-word test is the one that removes non-English text and code, so leaving it out changes what the filter does to a multilingual corpus.
- Judging a filter on twenty examples, or scoring the classifier on pages it was trained on. One false positive in twenty gives an interval of about 0.1% to 25% (Clopper-Pearson), so the sample cannot tell a harmless filter from a harmful one. Audit more, per slice, and keep the audit sample out of training and out of threshold tuning.
Try it yourself
Closed-book, before checking anything
gopher_reason(text) that returns pass or the name of the first failed rule: fewer than 50 or more than 100,000 words, mean word length outside 3 to 10, more than 30% of lines ending in ..., fewer than 80% of words containing a letter, and fewer than two of the eight stop words the be to of and that have with. Run it on "The city is on the banks of the river and has more than a hundred thousand people. " * 8 and on "La ville est située au bord de la rivière et compte plus de cent mille habitants. " * 8, then on "def add(a, b):\n return a + b\n\n" * 30. Split words on whitespace: the English text passes, and the French text and the code fail only the stop-word rule. With nltk.word_tokenize, which the handout suggests, the code also fails the mean-word-length and alphabetic-share rules, so state your word split with the rules.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Why can the rule 'at least 80% of words contain an alphabetic character' remove good text?Answer
It assumes prose. Tables of numbers, math, data listings and symbol-heavy code fail it although they can be valuable training text. It is a statement about the kind of text you want, which should match the corpus purpose.
2.A classifier is trained with pages linked from Wikipedia as positives and random crawl pages as negatives. What does it learn, and where will it fail?Answer
It learns what separates those two samples: style, topic and source type. It will score low on good text unlike the references (forum answers, code, other languages) and can score high on reference-shaped text that is wrong. Its score has meaning only after you check it against labeled samples.
3.You audit 20 removed documents and 1 was a false positive. What can you report?Answer
An observed rate of 5%, with a 95% interval of roughly 0.1% to 25%. Twenty documents cannot separate 1% from 20%, so sample more and report per slice.
4.A top-10% threshold gave the best model in one paper. Why is that not a rule for your pipeline?Answer
The threshold trades data quantity for quality, so the best value depends on the token budget, the pool and the reference set. A longer run wants more, lower-scoring data. Tune it on your own comparison at your own budget.
Practice
- CS336 Assignment 4: Gopher filters and the quality classifier
Problems (
gopher_quality_filters) and (quality_classifier); connectrun_gopher_quality_filterandrun_classify_qualityintests/adapters.pyand pass the seventest_gopher_*tests andtest_classify_qualityintests/test_quality.pyThe list of positive URLs in part 2.7 comes from a full Wikipedia dump. Replace it with a few hundred pages that articles you choose link to, fetched with the handout's
wgetcommand, and use random records from the example WET file as negatives. Do part (b) ofgopher_quality_filterswith a per-rule false-positive count. The small filtered-versus-unfiltered training comparison belongs to the section mini-project. Implement it in your own repository.
You're done when
Your code passes the seven Gopher tests and test_classify_quality, and you have a table of removals per rule and per slice with a sampled false-positive rate and its interval for each.
Only when you can do this without notes.
Leads to
Notes
Resources · 5 for this unit, 16 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. - 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. - 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.
- 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.
Also in this section
- 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.
- 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.
- 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.
- 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.
- 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.