Sub topic 2
One vocabulary for many scripts: shared subword tokenization
This chapter assumes you know basic Python and the Hugging Face transformers tokenizer API. It also assumes you know what a token ID is and why transformer models need a fixed vocabulary. You will see how one vocabulary can serve more than 100 languages and writing systems. You will also see what that costs each language.
Why a multilingual model needs one tokenizer
A transformer encoder maps token IDs to embedding vectors. If a model is to read English, German, Hindi and Swahili, it needs one ID space that covers all of them. Otherwise the embedding table, the output layer and the attention layers cannot share anything across languages.
There are three ways to build that ID space:
- Word-level vocabulary. Every word form gets an ID. Morphologically rich languages such as Finnish, Turkish and Swahili produce huge numbers of word forms. A vocabulary that covers all of them is far too large, and unseen words become unknown tokens.
- Character-level vocabulary. There are no unknown characters, but sequences get very long. Attention cost grows with the square of sequence length. Single characters also carry little meaning.
- Subword vocabulary. Frequent words stay whole, and rare words are split into smaller reusable pieces. This is the standard compromise.
Multilingual models use a subword vocabulary that is trained once on text from all languages together. That vocabulary is the first place where languages start to share parameters.
How subword vocabularies are built
Two algorithms dominate multilingual models.
- WordPiece is used by mBERT. Training starts from characters and merges pairs that most improve the likelihood of the training data. mBERT's vocabulary has about 120,000 entries and covers 104 languages. Continuation pieces carry a
##prefix. - SentencePiece with a unigram language model is used by XLM-R. Training starts from a large candidate set of pieces and prunes pieces that contribute least to the likelihood. XLM-R's vocabulary has 250,000 entries and covers 100 languages. SentencePiece treats the input as a raw character stream, with no pre-tokenization on spaces. It marks a word start with the
▁symbol. This matters for scripts that do not put spaces between words, such as Chinese, Japanese and Thai.
Both approaches choose pieces by how often they occur in the training text. Text volume therefore decides which languages get long, whole-word pieces and which get fragments. We return to this below.
Pieces are shared in two ways:
- Identical strings. Digits, punctuation, names, URLs, Latin-script loanwords and shared prefixes such as
interappear in many languages and map to the same ID. - Identical IDs for different meanings. A piece such as
dieis a common word in German and a verb in English. The tokenizer cannot tell them apart. The model has to use context to separate them.
Shared pieces are called anchors. They give the model some overlap between languages from the start. Later chapters cover how much this overlap contributes. Studies find that transfer still works between languages with different scripts and almost no shared pieces, so anchors help but are not the whole explanation.
Looking at the splits
The following script tokenizes the same meaning in English, German and Hindi using the XLM-R tokenizer.
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained("xlm-roberta-base")
texts = {
"en": "The weather is nice today.",
"de": "Das Wetter ist heute schön.",
"hi": "आज मौसम अच्छा है।",
}
for lang, text in texts.items():
pieces = tok.tokenize(text)
print(lang, len(pieces), pieces)Things to look for in the output:
- Short, frequent words in English and German usually appear as single pieces with a leading
▁, for example▁The. - The Hindi sentence has fewer words, but the number of pieces is not proportionally smaller. Devanagari text was a smaller share of the training data than English, so fewer whole words earned their own piece.
- The sentence-final danda
।is a character of its own. Punctuation specific to one script is often a separate piece.
Exact counts depend on the tokenizer version, so run the script yourself instead of relying on numbers from this page.
Measuring tokenization cost: fertility
A useful measure is fertility, the average number of pieces produced per word. A fertility near 1 means most words are single pieces. A fertility of 3 means each word is split into about three pieces. Fertility is only a rough measure, because the definition of a word is not the same for every language. It does give a quick comparison across languages for parallel text.
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained("xlm-roberta-base")
parallel = {
"en": "The children are playing in the garden after school.",
"de": "Die Kinder spielen nach der Schule im Garten.",
"hi": "बच्चे स्कूल के बाद बगीचे में खेल रहे हैं।",
}
for lang, text in parallel.items():
words = text.split()
pieces = tok.tokenize(text)
print(f"{lang}: words={len(words)} pieces={len(pieces)} "
f"fertility={len(pieces) / len(words):.2f}")A single sentence is only an anecdote. For a real comparison, use a few hundred parallel sentences, such as the FLORES-200 devtest set, and average the results.
Why this matters: sequence length and cost
Every model has a maximum sequence length, often 512 pieces for XLM-R. Languages with higher fertility use more of that budget for the same content. This has three practical effects.
- Truncation. With
max_length=128, a high-fertility language loses more of its text than a low-fertility one. In tasks such as natural language inference, truncation can remove the hypothesis, which would turn a fair comparison across languages into an unfair one. - Compute and latency. Cost grows with the number of pieces. The same document costs more in a high-fertility language.
- Usage cost. Hosted models that charge per token charge more for the same text in high-fertility languages. Chapter 14 returns to this under fairness.
What happens to characters outside the vocabulary
The XLM-R SentencePiece model has no byte fallback. A character that is not in the vocabulary becomes the <unk> token and its content is lost. This is rare for the 100 pretraining languages. It is more likely with unusual scripts, emoji, rare symbols and some historical characters. Models with byte-level vocabularies avoid this, at the cost of longer sequences for non-Latin text.
You can count unknown tokens directly:
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained("xlm-roberta-base")
def unk_rate(text):
ids = tok(text, add_special_tokens=False)["input_ids"]
return sum(i == tok.unk_token_id for i in ids) / max(len(ids), 1)
print(unk_rate("Hello world"))
print(unk_rate("नमस्ते दुनिया"))For languages you plan to support, run this check on a sample of real data before you choose a model.
Balancing languages in the tokenizer
If the tokenizer were trained on raw text, English and a few other large languages would dominate the vocabulary. Low-resource languages would get mostly single characters and short fragments, which leads to high fertility. XLM-R's authors reduce this by sampling text with a smoothed distribution that gives small languages a larger share than their raw size. Chapter 9 explains this temperature-based sampling in detail. The same idea applies to model pretraining.
Balancing helps but cannot remove the problem. A vocabulary of 250,000 pieces is shared by 100 languages. Every piece given to one language is not available to another. This competition for vocabulary slots is one reason for the "curse of multilinguality" covered in chapter 10.
Common errors
- Using a monolingual tokenizer with a multilingual model. Token IDs only mean something with the vocabulary the model was trained with. Always load the tokenizer and the model from the same checkpoint.
- Lowercasing or stripping accents.
bert-base-multilingual-uncasedremoves accents, which changes the meaning of words in many languages. Prefer the cased model unless you have a reason not to. - Splitting on spaces yourself. Do not pre-split text for Chinese, Japanese or Thai. Pass the raw string to the tokenizer.
- Comparing piece counts across tokenizers. Fertility from different tokenizers is not comparable, because the vocabularies differ.
- Ignoring Unicode normalization. The same visible text can use different code point sequences, for example
éas one character or aseplus a combining accent. Normalizing to NFC before tokenizing gives consistent splits.
Summary of trade-offs
| Choice | Benefit | Cost |
|---|---|---|
| Larger vocabulary | Lower fertility, more languages get whole words | Larger embedding and output matrices |
| Smoothed language sampling | Fairer splits for small languages | Slightly longer splits for large languages |
| No byte fallback | Shorter sequences | Unknown characters are lost |
| Byte-level vocabulary | No unknown characters | Much longer sequences for non-Latin scripts |
Exercise
You fine-tune XLM-R for classification with max_length=128. English accuracy is 88% and Thai accuracy is 79%. Give two tokenizer-related checks you would run before you conclude that the model understands Thai worse, and say what each check would show.
Show answer
First, compute the fraction of Thai examples that exceed 128 pieces, and compare it with English. If many more Thai examples are truncated, the gap may come from lost text. Second, compute the unknown-token rate and the fertility for Thai and English on the same parallel text. A high Thai fertility means each word is split into many fragments, which carry less meaning per piece and use more of the length budget. A high unknown rate means some characters are lost completely. If either check shows a large difference, re-run the evaluation with a longer max_length before you draw conclusions about understanding.