Unit 7 of 11 · about 4 hours · measure
Tokenizer fertility, vocabulary disparities and multilingual and code audits
Every token count in a training plan is an assumption about one tokenizer. If the tokenizer needs several times more tokens for one language, that language gets less content per context window and per training token, and no later step shows it unless you measured.
You'll be able to
- Measure the tokenization premium of a tokenizer on parallel text for several languages, and report it with the corpus, split, tokenizer revision and sentence count.
- Choose a length measure that is comparable across languages and scripts, and explain why tokens per word and bytes per token are not.
- Turn a premium into a cost: the share of a context window or token budget that a language gets, and audit a code slice for the same effect.
Covers
Read
In this order, only the parts listed
0 of 3 done
- Language Model Tokenizers Introduce Unfairness Between Languages (Petrov et al., 2023)Language Model Tokenizers Introduce Unfairness Between Languages (Petrov et al., 2023)
Section 3 (parity and premium), Section 4.1 with Table 1 (English-centric tokenizers on FLORES-200) and Sections 5.1 to 5.3 (cost, latency and long-context consequences)
Skip Section 6 on mitigations; they are proposals, not tested recipes.
- FLORES-200 parallel sentencesFLORES-200 parallel sentences
The README for the dataset and its download link; use the
devtestsplit (1,012 sentences per language, the same sentences in the same order for every language) with codes such aseng_Latn,fra_Latn,hin_Devaandzho_Hans - Project: Tokenizer and Corpus PipelineTokenizer and Corpus Pipeline
Milestone E (measurement) and the 'Measurement requirements': compression and fertility by slice, and the effect of vocabulary and packing on sequence length, embedding parameters and KV memory
Focus on
- Fertility is tokens per word, and it needs a definition of word. Whitespace splitting gives 13 tokens per 'word' for Chinese in the run below, so use parallel text: the same sentences in two languages, and the ratio of token counts (Petrov's premium).
- Bytes per token is not comparable across scripts, because an unaccented Latin letter takes 1 byte, a Cyrillic letter 2 and a Devanagari or Han character 3. Under the Qwen3 tokenizer Russian shows more bytes per token than English and still needs 1.75 times the tokens.
- The premium changes the budget. A fixed context window holds of the content, a fixed training-token budget buys the same fraction, and a loss per token cannot be compared between tokenizers. Compare bits per byte of the same held-out text instead.
- FLORES-200 is translated encyclopedic and news text, so it measures that domain. Web text, code and your own domain differ, and a tokenizer trained on other languages falls back to bytes: GPT-2 averaged 1.00 bytes per token on Tamil and 1.03 on Shan in the run below.
Common mistakes · 3
- Reporting tokens per word for every language. In the same run Qwen3 gave 13.4 tokens per whitespace-separated unit for Chinese, 16.4 for Thai and 35.8 for Japanese, because those texts have few spaces. The number is a property of the splitter, not of the tokenizer.
- Comparing bytes per token across languages, or loss per token across tokenizers. Both change when the unit changes, so they can rank languages or models the wrong way round. Use token counts on parallel text for languages and bits per byte on a shared held-out set for models.
- Trusting the premium of one tokenizer for another or for another domain. The same sentences cost GPT-2 7.41 times the English tokens in Hindi and Qwen3 4.42 times. On one Python file (
tests/test_deduplication.pyfrom CS336 Assignment 4, 133 lines), GPT-2 gave 2.21 bytes per token and Qwen3 gave 4.81, against about 4.7 to 4.8 for the Englishdevtesttext in both.
Try it yourself
Closed-book, before checking anything
devtest sentences of English, French, Hindi, Tamil, Thai and Simplified Chinese, encode each sentence with encode(s, add_special_tokens=False) and compute the premium as total tokens divided by the English total, for GPT-2 and for the Qwen3-0.6B tokenizer. In one run (transformers 5.19.0, tokenizers 0.23.3, gpt2 revision 607a30d783dfa663caf39e06633721c8d4cfcd7e, Qwen/Qwen3-0.6B revision c1899de289a04d12100db370d81485cdf75e47ca) the premiums were, for GPT-2 then Qwen3: French 2.00 and 1.58, Hindi 7.41 and 4.42, Tamil 15.54 and 6.11, Thai 8.99 and 2.55, Chinese 3.15 and 1.00. Report your own table with the median of the per-sentence ratios beside each total.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.A tokenizer has a premium of 4.42 for Hindi relative to English. What does that mean for a fixed 8,192-token context and for a fixed training-token budget?Answer
The context holds about 1/4.42, or 23%, of the English content, and a budget split equally by tokens gives Hindi about 23% as much content as English. Both follow from counting in tokens.
2.Under one tokenizer, Russian shows 5.37 bytes per token and English 4.78, yet Russian needs 1.75 times the tokens for the same sentences. How?Answer
A Cyrillic letter takes two UTF-8 bytes against one for a Latin letter, so each Russian token carries more bytes but fewer letters of content. Bytes per token is not normalized by content; the premium on parallel text is.
3.Why is 'tokens per word' a poor fertility measure for Chinese, Japanese and Thai?Answer
Those scripts do not separate words with spaces, so a whitespace 'word' is a whole clause and the ratio is about the splitter. Use tokens per character, or the ratio of token counts on parallel text.
4.A model with a larger vocabulary reports a lower per-token validation loss than a baseline. Can you say it models the text better?Answer
No. The two models split the same text into different numbers of tokens, so the losses average over different units. Convert both to bits per byte (or per character) on the same held-out text, then compare.
Practice
- Petrov et al. premium on FLORES-200 for your own tokenizer
The
devtestsplit for English plus at least five other languages, including one non-Latin script and one language without spacesMeasure the premium for the tokenizer of your project and one other, add a Python file from your own repository as a code slice (bytes per token and the effect of collapsing indentation), and compare your GPT-2 numbers with Petrov Table 1. Their table uses the 2,000 sentences they describe, not only
devtest, so expect differences of a few hundredths. The section mini-project reuses the table. Implement it in your own repository.
You're done when
You have a premium table for two tokenizers over at least six languages with the split, revisions and sentence count stated, and you can say what the table means for context length and for a token-budgeted mixture.
Only when you can do this without notes.
Leads to
- Mixture weights, temperature sampling, repetition and effective tokensMixture weights are set in tokens, so the premium changes what each weight buys.
- Document packing, boundary tokens and cross-document attention leakagePacking works on token counts, so the same tokenizer sets how many documents fit a sequence.
Notes
Resources · 3 for this unit, 18 more in the section
- 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.
- Tokenizer and Corpus PipelineRoadmap-Final · support
Reuse the project correctness, lineage and contamination contracts. Extend the artifact instead of starting another tokenizer implementation.
- 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.
Also in this 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. - 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.
- 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 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.
- 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. - 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. - 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.
- 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.
- 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.