{"type": "session", "harness": "opencode", "id": "i18n-0001", "name": "Why BPE needs multilingual training data"} {"type": "message", "message": {"role": "system", "content": "You are an expert NLP engineer. You explain tokenization clearly and give correct, minimal Python examples."}} {"type": "message", "message": {"role": "user", "content": "I trained a BPE tokenizer on English-only text and now non-English text uses far more tokens. Why, and how do I fix it?"}} {"type": "message", "message": {"role": "assistant", "content": "The tokenizer still works (byte fallback never fails), but it suffers from **over-segmentation**: merges learned from English never cover other scripts, so they fall back to single bytes. The standard measure is **fertility** = tokens per word (or per character). Higher fertility means longer sequences, higher cost, and usually worse quality.\n\nIllustrative fertility with a typical 32k English-trained byte-level BPE:\n\n| input | tokens (approx) |\n|---|---|\n| hello | 1 |\n| xin chào (Vietnamese) | 5-7, diacritics split off |\n| 你好世界 (Chinese) | ~12, i.e. 3 byte-tokens per character |\n| مرحبا (Arabic) | ~10, 2 byte-tokens per character |\n\nEnglish text stays near 1 token per word while CJK text costs ~3 tokens per character. This imbalance is called the **tokenizer parity** problem.\n\n**Fixes:**\n1. Train on a **balanced multilingual corpus** (temperature sampling so small languages are upsampled).\n2. Verify **script coverage**: every target script should appear in whole-token merges, not just bytes.\n3. Consider a larger vocabulary (64k-256k) when supporting many scripts.\n4. Evaluate fertility **per language** before shipping the tokenizer:\n\n```python\ndef fertility(tokenizer, words):\n \"\"\"Average tokens per word; compare across languages.\"\"\"\n return sum(len(tokenizer.encode(w)) for w in words) / max(1, len(words))\n\nlangs = {\n \"en\": [\"hello\", \"world\", \"tokenizer\"],\n \"vi\": [\"xin\", \"chào\", \"thế\", \"giới\"],\n \"zh\": [\"你好\", \"世界\", \"分词\"],\n \"ar\": [\"مرحبا\", \"بالعالم\"],\n}\nfor lang, words in langs.items():\n print(lang, round(fertility(tokenizer, words), 2))\n```\n\nAim for fertility within ~2x across supported languages; if one script is an outlier, its training share was too small."}}