Unit 3 of 11 · about 4 hours · implement, measure
Language and domain identification, and irreversible normalization decisions
A language filter decides which languages the model will ever see, and a normalization step decides which character distinctions it can ever learn. Both are applied once, at scale, and a bad choice cannot be undone from the cleaned output.
You'll be able to
- Implement language identification with fastText that returns a language and a score between 0 and 1, and choose a keep threshold from a hand-labeled sample with a stated interval, not from the score alone.
- Measure retention per language and per kind of text at a threshold, and find which languages, short texts, code and mixed pages the filter drops or mislabels.
- Choose a Unicode normalization form for each stage, state which distinctions it erases, and keep the raw text so that the choice can be revisited.
Covers
Read
In this order, only the parts listed
0 of 5 done
- CS336 Assignment 4 handoutCS336 Assignment 4 - Data
Section 2.3, Language identification, and Problem (
language_identification) parts (a) to (c) (pp. 4 to 5); in Section 3.2 the normalization list in Problem (minhash_deduplication) (p. 11) - CS336 2026 Lecture 14: Data II (executable trace)CS336 2026 - Data Lectures 13 and 14
The
filteringstep: the target-versus-raw framing, 'Language identification' (176 languages, training sites, the English threshold Dolma uses) and 'Scale-dependent effects of filtering' - Gopher, Appendix A (Rae et al., 2021)Scaling Language Models: Methods, Analysis and Insights from Training Gopher, Appendix A
Appendix A.4 'Text normalisation' (p. 46): the tokenizer's NFKC step, why it is not lossless, and the authors' recommendation
- Unicode Standard Annex #15: Unicode Normalization FormsUnicode Standard Annex #15: Unicode Normalization Forms
Section 1.1 (canonical and compatibility equivalence) and Section 1.2 (the four normalization forms, and why the compatibility forms 'may remove distinctions that are important to the semantics of the text')
- FineWeb (Penedo et al., 2024)FineWeb Paper and DataTrove Pipeline
Section 3.3 (base filtering: a fastText English score of at least 0.65)
Read only the language-filter sentence; the rest of 3.3 belongs to the quality-filter unit.
Focus on
- The off-the-shelf identifier,
lid.176.bin, returns a label and a probability for text on one line; it was trained on Wikipedia, Tatoeba and SETimes, and it knows 176 languages. A text in any other language still gets one of those labels. - A threshold such as 0.5 or 0.65 is a pipeline policy, not a property of the model. The score is not calibrated across languages, so measure retention per language on parallel or hand-labeled text before you fix the number.
- Sample and audit: read labeled examples, count errors per slice, and report the error rate with an interval. Twenty samples can only bound an error rate loosely.
- Normalization has two kinds of use. A matching key (for deduplication or contamination) may be aggressive because you keep the original. Stored training text should change only distinctions the standard says carry no meaning. NFKC does not meet that bar, which is Gopher's own conclusion.
Common mistakes · 3
- Reading the score as a probability of being right. Shan was labeled Burmese at a mean score of 0.89, and a short Norwegian Bokmål sentence (
Jeg bor i en liten by ved kysten og går til jobb hver dag.) came back Danish at 0.96 in the same setup. A high score says the model is sure, not that it is correct. - Using one threshold for every language. A cutoff that keeps 99.7% of English can keep under a third of correctly identified Swahili, so a global rule silently removes a language from the corpus.
- Cleaning the stored text with the same normalization you use for dedup keys. Lowercasing, accent stripping and whitespace collapse (the handout's MinHash step) are fine for a key; applied to the training text they erase case, diacritics and the indentation in code.
Try it yourself
Closed-book, before checking anything
identify(text) that removes newlines, calls predict(text, k=1) on lid.176.bin, and returns (code, score). Run it on the 1,012 devtest sentences of FLORES-200 (CC BY-SA 4.0) for English, Swahili, Yoruba and Shan, and tabulate top-1 accuracy, the share of sentences that are both correct and at least 0.65, and the mean score. In one run with fastText 0.9.2 (the fasttext-numpy2-wheel build) and lid.176.bin, English was 100% correct with 99.7% kept, Swahili 94.8% correct but only 28.7% kept, Yoruba 56.0% correct with 200 sentences labeled Irish, and every Shan sentence but one was labeled Burmese (mean score 0.89, since Shan is not among the 176). Then write what NFC and NFKC each do to fi (U+FB01), the full-width Hello and x², and say which result you could not undo.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.A model is right on 94.8% of Swahili sentences, yet an English-tuned cutoff of 0.65 keeps 28.7% of them. What does this tell you about choosing a threshold?Answer
The score distribution differs by language, so one number trades very different amounts of recall per language. Choose the cutoff per language, or per slice, from a labeled sample, and report retention by language.
2.You audit 300 sampled documents and find no language errors. What can you claim about the error rate?Answer
Only an upper bound: with 0 errors in 300 the two-sided 95% Clopper-Pearson upper bound is about 1.2%, and the one-sided rule of three gives about 3/300 = 1%. You cannot claim zero, and the bound holds for the population you sampled from, not for slices you did not sample.
3.Why can NFKC be used to build a deduplication key but should not be applied to the text you train on?Answer
NFKC replaces compatibility forms, for example
x²becomesx2and ligatures and full-width letters become plain letters. A key only needs to treat such variants as equal, and the original stays available. Stored text would lose distinctions that math, code and typography rely on, and the change cannot be reversed from the output.4.A four-line Python function is labeled Swedish at 0.27. What does this say about running language identification on mixed web data?Answer
The identifier was trained on prose, so code, tables and markup get arbitrary labels and low scores. A language threshold would remove them as a side effect. Decide the domain first and route code and non-prose to their own rules.
Practice
- CS336 Assignment 4:
language_identificationProblem (
language_identification) in Section 2.3; connect your function torun_identify_languageintests/adapters.pyand pass both tests intests/test_langid.pyThe tests check an English page and a Chinese sentence, so they do not test thresholds. For part (c) label 20 documents by hand and report the errors with an interval, then add the per-language FLORES table from the reproduce step. The section mini-project reuses that table. Implement it in your own repository.
You're done when
Your function passes both language tests, you have a per-language retention table at your chosen threshold with the audit interval beside it, and you can state which normalization your pipeline applies to keys and which to stored text.
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.
- 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. - 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.
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. - 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.
- 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.
- 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.
- 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.