Multilingual Tokenization and Vocabulary Allocation

Michael BrenndoerferNovember 25, 202635 min read

Compare multilingual tokenizers with fertility, bytes per token, and tokenization premiums, and see how script coverage and byte fallback shape vocabulary use.

Language AI HandbookAll chapters
Part 26 of 67Multilingual Language Models and Cross-Lingual Transfer
Chapter 184Multilingual Tokenization and Vocabulary Allocation
Reading the full chapter · 11 sections · 35 min11 sections · 35 min

All 11 sections · 35 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

Multilingual Tokenization and Vocabulary Allocation

Fertility, script coverage, shared vocabularies, byte models, and unequal token costs across languages.

Suppose a tokenizer encodes cat as one token and बिल्ली as six. The Hindi word occupies six input positions and, at the same per-token input rate, costs six times as much to send. That count does not tell you how much slower the request will be. The model can process input tokens together during prefill, and the work depends on the architecture and the full sequence. Better language modeling can improve what the system does with those six tokens. For a fixed input and tokenizer, the six positions are still occupied.

In Part V we built subword tokenizers from byte pair encoding, WordPiece, unigram language models, and SentencePiece. A multilingual training corpus gives their vocabulary learners evidence from several languages at once. When the corpus is skewed, frequently observed patterns from heavily sampled languages have an advantage. The details depend on the tokenizer and the pieces that languages share.

This chapter explains three ways to diagnose that allocation. Fertility counts tokens relative to words when word boundaries are defined. Bytes per token describes how much text fits in each token, and a tokenization premium compares the token counts of translations. We train two small tokenizers and measure held-out token counts, bytes per token, translation premiums, and token overlap. Those measurements help explain differences in context budgets and per-token costs. The evaluation section shows how to compare loss across tokenizers.

Choose the measurement from the question you are trying to answer. A documentation team deciding how many translated help articles fit in a retrieval context needs token counts on those translations. A tokenizer engineer deciding which part of the corpus needs attention also wants to know how many bytes the tokenizer can encode per position. A language-model researcher comparing the probability assigned by two systems needs a unit of loss that the two systems can both report.

The cost of a single token

The English word cat occupies three ASCII bytes. Its Hindi equivalent बिल्ली contains six Unicode code points. Each is a three-byte Devanagari code point in UTF-8, for eighteen bytes total.

Measure the two encodings directly to see where the difference comes from:

cat:  3 ASCII characters  =  3 UTF-8 bytesबिल्ली:  6 code points×3 bytes per code point  =  18 UTF-8 bytes\begin{aligned} \text{cat} &: \; 3 \text{ ASCII characters} \;=\; 3 \text{ UTF-8 bytes} \\ \text{बिल्ली} &: \; 6 \text{ code points} \times 3 \text{ bytes per code point} \;=\; 18 \text{ UTF-8 bytes} \end{aligned}

The six units in the Hindi string are code points, including attached signs. They are distinct from user-perceived characters. Python's len(text) counts code points, and len(text.encode("utf-8")) counts the bytes in the UTF-8 encoding. To find the average number of bytes per code point, divide the byte count by the code-point count. To compare how compactly tokenizers encode the same losslessly represented text, use bytes per token.

With one token per code point for both strings, the token ratio is 6/3=26/3=2. With one token per byte for both strings, it is 18/3=618/3=6. A mixed tokenizer could keep cat as one piece and encode the Hindi string as eighteen bytes. A tokenizer without a way to represent the Hindi code points can instead collapse a run into an unknown ID, which makes its token count look small while losing text.

Fertility

Fertility is the average number of subword tokens the tokenizer produces per word:

Fℓ=number of tokens produced on language ℓnumber of words in that textF_\ell = \frac{\text{number of tokens produced on language } \ell}{\text{number of words in that text}}

Fertility is a property of a tokenizer applied to a text sample under a specified word segmentation convention. Rust et al. (2021) use subword fertility in their analysis of multilingual tokenizers.

English and several other languages often mark word boundaries with spaces. Chinese, Japanese, and Thai generally do not use spaces between every word. A whitespace split can count a whole Thai sentence as one word. Its resulting fertility would compare incompatible units with an English whitespace count.

Use an explicit language-specific word segmenter when the word is the unit of interest. If the question is how densely the tokenizer encodes text, count UTF-8 bytes instead. This avoids word segmentation and keeps the measurement sensitive to the script and sample.

Bℓ=UTF-8 bytes in the textnumber of tokensB_\ell = \frac{\text{UTF-8 bytes in the text}}{\text{number of tokens}}

where:

  • BℓB_\ell: bytes per token for language ℓ\ell
  • UTF-8 bytes in the text\text{UTF-8 bytes in the text}: the total number of bytes the text occupies in UTF-8 encoding
  • number of tokens\text{number of tokens}: the total number of subword tokens the tokenizer produces on that text

A higher BℓB_\ell means fewer tokens for the same byte count. It can be large for text with many long, learned pieces. Pure byte encoding has Bℓ=1B_\ell=1 when there are no additional tokens. Code-point encoding uses one token per code point and each scalar occupies at least one byte. A value below one needs another explanation, such as extra tokens or preprocessing that changes the text being counted.

The comparison still depends on the material. The UTF-8 width of code points varies, and a translated message can contain more bytes than the original. The metric measures average encoded bytes per position for the sample. It does not measure how predictable the text is.

A high bytes-per-token value can coexist with a high premium. Imagine a translation that is twice the source's byte length, encoded at eight bytes per token while the source is encoded at five. The translation compresses more bytes into each position and still occupies 2×5/8=1.252\times 5/8=1.25 times as many positions. These illustrative numbers explain why neither column in a tokenizer comparison substitutes for the other.

Tokenization premium

The tokenization premium of language ℓ\ell relative to English is the ratio of token counts on the same content, which you obtain by using a parallel corpus where each sentence appears translated into every language:

Pℓ=∑iT ⁣(si(ℓ))∑iT ⁣(si(en))P_\ell = \frac{\sum_{i} T\!\left(s_i^{(\ell)}\right)}{\sum_{i} T\!\left(s_i^{(\text{en})}\right)}

where:

  • PℓP_\ell: the tokenization premium of language ℓ\ell relative to English
  • T(⋅)T(\cdot): the token count produced by the tokenizer for a given string
  • si(ℓ)s_i^{(\ell)}: the ii-th sentence translated into language ℓ\ell
  • si(en)s_i^{(\text{en})}: the ii-th sentence in English
  • ∑i\sum_i: the sum over all ii parallel sentences in the corpus

Pℓ=3P_\ell=3 means the translations occupy three times as many token positions in aggregate. The input charge is three times as high for these tokens when the input rate is fixed and identical.

Holding content approximately constant with translations makes the premium relevant to a user-facing workload. The ratio of total token counts includes both translation length and compression. In fact, the premium equals the ratio of the two texts' UTF-8 byte totals times the English bytes-per-token divided by the target language's bytes-per-token. Keep the byte counts and the compression measurements together if you want to see how the two factors contributed. This chapter uses a ratio of totals across pairs. Each of the three diagnostics requires a positive denominator. Petrov et al. (2023) define the premium on sentence pairs and evaluate tokenizers on a much larger parallel corpus.

Where the vocabulary budget goes

A shared multilingual tokenizer has one table of size VV. Its starting symbols and reserved IDs consume slots alongside learned pieces. A piece that occurs in several languages occupies one slot and can be used by all of them. Each extra entry competes with other candidates for space.

Consider one step of BPE. The trainer counts candidate pairs in the current symbol stream, after applying merges selected in earlier steps. If Cℓ,t(m)C_{\ell,t}(m) is the number of occurrences of pair mm in language ℓ\ell at step tt, the total is

Ct(m)=∑ℓCℓ,t(m).C_t(m) = \sum_\ell C_{\ell,t}(m).

The sum adds every language's raw count once. Let Nℓ,tN_{\ell,t} be the number of eligible pair positions in language ℓ\ell at step tt, and let NtN_t be the total across languages. If Nt>0N_t>0, a language with Nℓ,t>0N_{\ell,t}>0 contributes its within-language pair rate fℓ,t(m)=Cℓ,t(m)/Nℓ,tf_{\ell,t}(m)=C_{\ell,t}(m)/N_{\ell,t}, weighted by its share qℓ,t=Nℓ,t/Ntq_{\ell,t}=N_{\ell,t}/N_t. A language with no eligible positions contributes no pair occurrences, so the sum omits it.

Ct(m)Nt=∑ℓ: Nℓ,t>0qℓ,tfℓ,t(m).\frac{C_t(m)}{N_t} = \sum_{\ell:\,N_{\ell,t}>0} q_{\ell,t} f_{\ell,t}(m).

A share measured in eligible positions multiplies a rate per eligible position. A share measured in sentences or original UTF-8 bytes would require a rate defined with that matching denominator. Because NtN_t is common to all candidate pairs at one step, ranking by rate or by count gives the same ordering at that step.

Suppose an English-exclusive pair occurs in 0.1% of English positions, and English contributes 30% of all positions. A pair exclusive to a language with a 0.5% share needs a within-language rate of 6% to tie it. A sufficiently common pair in the smaller language can therefore win. A pair found in both languages pools evidence. The next merge changes the symbol stream, so the shares and rates describe one step of the process.

For example, a merge of a b removes occurrences of that adjacent pair where the merge applies and can introduce a new candidate such as ab c. The trainer does not reserve a slice of the merge list for each language. Across steps, even the same corpus can produce a different distribution of candidate positions as each language's sequences compress. This is one reason to measure the resulting encoding instead of trying to read an exact vocabulary allocation from the training shares alone.

Script can affect which pairs pool evidence. A learned Latin-letter sequence gives a character-based trainer little direct help with a Devanagari sequence. Punctuation, digits, loanwords, and mixed-script text can still travel across those boundaries. Byte-based schemes can also reuse fragments of unrelated code points that happen to share bytes.

We will train two small SentencePiece BPE tokenizers with equal final vocabulary sizes and different training mixtures. In this implementation the mixture influences both the training character alphabet and subsequent merges. We keep both models lossless on the evaluation sample so their token counts measure representations of the same text.

PythonIn [2]
CollapseExpand
import tempfile
import unicodedata
from collections import Counter
from pathlib import Path

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import sentencepiece as spm

The corpus contains 14 approximately aligned messages in nine languages and eleven extra English rows. We keep the 14 aligned rows and split them by message into ten training rows and four held-out rows per language for the tokenizer comparison. To reuse the code, set one cutoff for all aligned languages and leave at least one row in each partition. The examples cover six primary script families when Latin, Arabic, Devanagari, Hangul, Thai, and Han are counted separately. The constructed corpus illustrates the method and is too small to estimate a language-level premium.

PythonIn [3]
CollapseExpand
CORPUS = {
    "eng": [
        "The cat is sleeping on the chair.",
        "She bought three apples at the market.",
        "We are going to the library tomorrow.",
        "He does not like cold weather.",
        "My brother works in a hospital.",
        "The children are playing in the garden.",
        "I need to buy a new phone.",
        "The train leaves at seven in the morning.",
        "Please open the window.",
        "They have two dogs and one cat.",
        "The book on the table is mine.",
        "She speaks four languages fluently.",
        "We ate rice and vegetables for dinner.",
        "The weather is very hot today.",
        "He reads the newspaper every morning.",
        "The restaurant serves excellent soup.",
        "Our neighbors have a small garden.",
        "She finished her homework before dinner.",
        "The meeting starts at ten o'clock.",
        "I forgot my keys at the office.",
        "They are building a new school.",
        "The river flows through the old city.",
        "My sister studies mathematics at university.",
        "We should leave before it gets dark.",
        "The doctor asked him to rest.",
    ],
    "spa": [
        "El gato está durmiendo en la silla.",
        "Ella compró tres manzanas en el mercado.",
        "Vamos a la biblioteca mañana.",
        "A él no le gusta el clima frío.",
        "Mi hermano trabaja en un hospital.",
        "Los niños están jugando en el jardín.",
        "Necesito comprar un teléfono nuevo.",
        "El tren sale a las siete de la mañana.",
        "Por favor, abre la ventana.",
        "Ellos tienen dos perros y un gato.",
        "El libro sobre la mesa es mío.",
        "Ella habla cuatro idiomas con fluidez.",
        "Comimos arroz y verduras para la cena.",
        "Hace mucho calor hoy.",
    ],
    "fin": [
        "Kissa nukkuu tuolilla.",
        "Hän osti kolme omenaa torilta.",
        "Menemme huomenna kirjastoon.",
        "Hän ei pidä kylmästä säästä.",
        "Veljeni työskentelee sairaalassa.",
        "Lapset leikkivät puutarhassa.",
        "Minun täytyy ostaa uusi puhelin.",
        "Juna lähtee seitsemältä aamulla.",
        "Avaa ikkuna, ole hyvä.",
        "Heillä on kaksi koiraa ja yksi kissa.",
        "Pöydällä oleva kirja on minun.",
        "Hän puhuu sujuvasti neljää kieltä.",
        "Söimme riisiä ja vihanneksia päivälliseksi.",
        "Tänään on erittäin kuuma.",
    ],
    "swh": [
        "Paka amelala juu ya kiti.",
        "Alinunua matunda matatu sokoni.",
        "Tutakwenda maktaba kesho.",
        "Yeye hapendi hali ya hewa ya baridi.",
        "Kaka yangu anafanya kazi hospitalini.",
        "Watoto wanacheza bustanini.",
        "Ninahitaji kununua simu mpya.",
        "Treni inaondoka saa moja asubuhi.",
        "Tafadhali fungua dirisha.",
        "Wana mbwa wawili na paka mmoja.",
        "Kitabu kilicho juu ya meza ni changu.",
        "Anazungumza lugha nne kwa ufasaha.",
        "Tulikula wali na mboga kwa chakula cha jioni.",
        "Leo kuna joto sana.",
    ],
    "ara": [
        "القطة نائمة على الكرسي.",
        "اشترت ثلاث تفاحات في السوق.",
        "سنذهب إلى المكتبة غدا.",
        "لا يحب الطقس البارد.",
        "أخي يعمل في المستشفى.",
        "الأطفال يلعبون في الحديقة.",
        "أحتاج إلى شراء هاتف جديد.",
        "يغادر القطار الساعة السابعة صباحا.",
        "من فضلك افتح النافذة.",
        "لديهم كلبان وقطة واحدة.",
        "الكتاب على الطاولة لي.",
        "تتحدث أربع لغات بطلاقة.",
        "أكلنا الأرز والخضروات على العشاء.",
        "الطقس حار جدا اليوم.",
    ],
    "hin": [
        "बिल्ली कुर्सी पर सो रही है।",
        "उसने बाज़ार में तीन सेब खरीदे।",
        "हम कल पुस्तकालय जा रहे हैं।",
        "उसे ठंडा मौसम पसंद नहीं है।",
        "मेरा भाई अस्पताल में काम करता है।",
        "बच्चे बगीचे में खेल रहे हैं।",
        "मुझे नया फ़ोन खरीदना है।",
        "ट्रेन सुबह सात बजे निकलती है।",
        "कृपया खिड़की खोलिए।",
        "उनके दो कुत्ते और एक बिल्ली है।",
        "मेज़ पर रखी किताब मेरी है।",
        "वह चार भाषाएँ धाराप्रवाह बोलती है।",
        "हमने रात के खाने में चावल और सब्ज़ियाँ खाईं।",
        "आज मौसम बहुत गर्म है।",
    ],
    "kor": [
        "고양이가 의자 위에서 자고 있다.",
        "그녀는 시장에서 사과 세 개를 샀다.",
        "우리는 내일 도서관에 갈 것이다.",
        "그는 추운 날씨를 좋아하지 않는다.",
        "내 형은 병원에서 일한다.",
        "아이들이 정원에서 놀고 있다.",
        "나는 새 휴대폰을 사야 한다.",
        "기차는 아침 일곱 시에 출발한다.",
        "창문을 열어 주세요.",
        "그들은 개 두 마리와 고양이 한 마리를 키운다.",
        "탁자 위에 있는 책은 내 것이다.",
        "그녀는 네 개의 언어를 유창하게 구사한다.",
        "우리는 저녁으로 밥과 채소를 먹었다.",
        "오늘 날씨가 아주 덥다.",
    ],
    "tha": [
        "แมวนอนอยู่บนเก้าอี้",
        "เธอซื้อแอปเปิลสามลูกที่ตลาด",
        "พรุ่งนี้เราจะไปห้องสมุด",
        "เขาไม่ชอบอากาศหนาว",
        "พี่ชายของฉันทำงานในโรงพยาบาล",
        "เด็กๆ กำลังเล่นอยู่ในสวน",
        "ฉันต้องซื้อโทรศัพท์เครื่องใหม่",
        "รถไฟออกตอนเจ็ดโมงเช้า",
        "กรุณาเปิดหน้าต่าง",
        "พวกเขามีสุนัขสองตัวและแมวหนึ่งตัว",
        "หนังสือบนโต๊ะเป็นของฉัน",
        "เธอพูดได้สี่ภาษาอย่างคล่องแคล่ว",
        "เรากินข้าวกับผักเป็นอาหารเย็น",
        "วันนี้อากาศร้อนมาก",
    ],
    "zho": [
        "猫在椅子上睡觉。",
        "她在市场上买了三个苹果。",
        "我们明天去图书馆。",
        "他不喜欢寒冷的天气。",
        "我哥哥在医院工作。",
        "孩子们在花园里玩。",
        "我需要买一部新手机。",
        "火车早上七点出发。",
        "请打开窗户。",
        "他们有两只狗和一只猫。",
        "桌上的书是我的。",
        "她能流利地说四种语言。",
        "我们晚饭吃了米饭和蔬菜。",
        "今天天气很热。",
    ],
}

LANG_INFO = {
    "eng": ("English", "Latin"),
    "spa": ("Spanish", "Latin"),
    "fin": ("Finnish", "Latin"),
    "swh": ("Swahili", "Latin"),
    "ara": ("Arabic", "Arabic"),
    "hin": ("Hindi", "Devanagari"),
    "kor": ("Korean", "Hangul"),
    "tha": ("Thai", "Thai"),
    "zho": ("Chinese", "Han"),
}

LANG_NAME = {code: info[0] for code, info in LANG_INFO.items()}
ConsoleOut [4]
CollapseExpand
Languages: 9
Aligned rows per language: 14
Held-out messages per language: 4

The mixed training file contains ten lines from each language. The English-only file repeats its ten English lines nine times so both files contain 90 lines. Equal row counts do not imply equal amounts of text, so the mixed condition is balanced by sentence count only.

PythonIn [5]
CollapseExpand
tmpdir = Path(tempfile.mkdtemp(prefix="multilingual-tokenizer-"))


def write_corpus(lines, path):
    path.write_text("\n".join(lines) + "\n", encoding="utf-8")
    return path


english_lines = train_by_language["eng"] * len(train_by_language)
mixed_lines = [text for texts in train_by_language.values() for text in texts]
english_path = write_corpus(english_lines, tmpdir / "english_only.txt")
balanced_path = write_corpus(mixed_lines, tmpdir / "balanced.txt")

Both trainers request 600 slots and reserve byte pieces for out-of-alphabet characters. The minimum is set by the reserved pieces plus the required character alphabet. hard_vocab_limit=False allows a model to finish below its vocabulary target when it runs out of candidates. It does not allow a target below the minimum alphabet size. We use identity normalization and preserve whitespace to make a round-trip check possible on this sample.

PythonIn [6]
CollapseExpand
def train_tokenizer(
    corpus_path, prefix, vocab_size=600, character_coverage=1.0
):
    """Train a small BPE tokenizer and return a loaded processor."""
    spm.SentencePieceTrainer.train(
        input=str(corpus_path),
        model_prefix=str(prefix),
        vocab_size=vocab_size,
        model_type="bpe",
        character_coverage=character_coverage,
        pad_id=0,
        unk_id=1,
        bos_id=-1,
        eos_id=-1,
        hard_vocab_limit=False,
        byte_fallback=True,
        normalization_rule_name="identity",
        add_dummy_prefix=False,
        remove_extra_whitespaces=False,
        num_threads=1,
        minloglevel=2,
    )
    return spm.SentencePieceProcessor(model_file=f"{prefix}.model")


tok_english = train_tokenizer(english_path, tmpdir / "tok_english")
tok_balanced = train_tokenizer(balanced_path, tmpdir / "tok_balanced")
ConsoleOut [7]
CollapseExpand
English-only vocabulary: 600 pieces
Balanced vocabulary:     600 pieces

Both vocabularies reach 600 pieces with SentencePiece 0.2.2. The two fits use the same trainer settings. We vary the training mixture, then count tokens for the same held-out translations.

The split is by message. If we put the English version of one message in training and its translation in evaluation, the evaluation texts would still be distinct strings, but the split would mix messages. Keeping the versions together makes the boundary easy to reproduce. The code shows the chosen split explicitly so a reader can substitute a larger aligned corpus and repeat the same comparison. A different train/test split may change the direction or size of an individual language's difference.

For each language and each tokenizer, we record tokens per sentence, bytes per token, and code points per token. The round-trip assertion checks every held-out sentence before its token count enters these comparisons.

PythonIn [8]
CollapseExpand
def token_stats(tokenizer, sentences):
    """Token counts and byte/character ratios for a list of sentences."""
    token_lists = [tokenizer.encode(sentence) for sentence in sentences]
    for sentence, token_ids in zip(sentences, token_lists):
        assert tokenizer.decode(token_ids) == sentence
    n_tokens = sum(len(tokens) for tokens in token_lists)
    n_bytes = sum(len(sentence.encode("utf-8")) for sentence in sentences)
    n_chars = sum(len(sentence) for sentence in sentences)
    n_sents = len(sentences)
    return {
        "tokens_per_sentence": n_tokens / n_sents,
        "bytes_per_token": n_bytes / n_tokens,
        "chars_per_token": n_chars / n_tokens,
    }


rows = []
for code, sentences in test_by_language.items():
    for tokenizer_name, tokenizer in [
        ("English-only vocab", tok_english),
        ("Balanced vocab", tok_balanced),
    ]:
        row = {
            "lang": code,
            "language": LANG_NAME[code],
            "tokenizer": tokenizer_name,
        }
        row.update(token_stats(tokenizer, sentences))
        rows.append(row)

stats_df = pd.DataFrame(rows)

english_rate = stats_df[stats_df["lang"] == "eng"].set_index("tokenizer")[
    "tokens_per_sentence"
]
stats_df["premium"] = stats_df["tokens_per_sentence"] / stats_df[
    "tokenizer"
].map(english_rate)
ConsoleOut [9]
CollapseExpand
UTF-8 bytes per token:
tokenizer  Balanced vocab  English-only vocab
language                                     
Arabic               2.03                1.00
Chinese              1.42                1.00
English              1.25                1.73
Finnish              1.29                1.21
Hindi                2.45                1.00
Korean               1.61                1.00
Spanish              1.25                1.47
Swahili              1.24                1.36
Thai                 2.78                1.00

Read each row across the two vocabularies. A value of one for a held-out language in the English-only condition means it used one piece per byte overall. Its text survives the round trip because the tokenizer can emit byte pieces. English's compression falls under the mixed tokenizer, while compression improves for every non-Latin sample in this split.

The grouped bars show token counts per held-out sentence under both vocabularies. Languages are ordered by their counts under the English-only tokenizer, from largest to smallest.

VisualizationOut [11]
CollapseExpand
Grouped bars compare the two tokenizers. Thai and Hindi see the largest reductions under equal-row mixed training.
Mean tokens per held-out sentence under English-only and equal-row mixed training, ordered by the English-only count. The mixed tokenizer uses fewer tokens for the five non-Latin samples and more for some Latin-script samples.

Thai and Hindi see the largest reductions in mean token count for these held-out sentences. English, Spanish, and Swahili use more tokens under the equal-row training condition. Equalizing the number of training rows changes the allocation without making the held-out counts equal.

ConsoleOut [12]
CollapseExpand
Tokenization premium relative to English (1.0 = same token count):
tokenizer  Balanced vocab  English-only vocab
language                                     
Hindi                1.27                4.30
Thai                 1.03                3.94
Korean               1.06                2.34
Arabic               0.83                2.32
Finnish              1.08                1.57
Chinese              0.75                1.48
Swahili              1.03                1.29
Spanish              0.96                1.13
English              1.00                1.00

The premium bars divide each held-out total by the English total under the same tokenizer. Every language has four test rows, so dividing the mean counts gives the same result as dividing the totals.

VisualizationOut [14]
CollapseExpand
Grouped bars show held-out token counts relative to English, with a reference line at one. The largest English-only premiums occur for Hindi and Thai.
Tokenization premium relative to English on the four held-out messages. The equal-row training condition reduces the largest ratios in this sample. Its English denominator is also larger.

The largest premiums fall under the mixed vocabulary. In this run the ratios fall both because several non-English texts use fewer tokens and because English uses more. Compare the absolute counts before diagnosing a change in the ratio. The remaining spread describes the particular translations and fitted vocabularies.

Script coverage and the character tail

SentencePiece's character_coverage sets a target share of character occurrences used to form the training alphabet after normalization. Without byte fallback, characters outside that alphabet may map to the unknown ID. Required characters can reserve entries in addition to those selected by occurrence mass. SentencePiece model schema

The default is 0.9995, or a target of 99.95% of observed occurrences. This setting determines occurrence mass, not the fraction of distinct types kept. A language with little data in the corpus can contribute many rare code points to the global tail. Losing a code point can erase a distinction even when the unknown ID is rare overall.

For a separate descriptive check, use all 14 aligned rows per language, including the four held out of tokenizer training. Sort code points within each language by frequency and keep the smallest number of distinct code points whose cumulative mass reaches the threshold. These counts describe the constructed data before SentencePiece-specific preprocessing or exclusions.

PythonIn [15]
CollapseExpand
def character_tail(sentences):
    """Return the cumulative uncovered fraction as characters are kept by rank."""
    counts = Counter("".join(sentences))
    frequencies = np.array(sorted(counts.values(), reverse=True), dtype=float)
    covered = np.cumsum(frequencies) / frequencies.sum()
    ranks = np.arange(1, len(covered) + 1)
    return ranks, 1.0 - covered


tails = {
    code: character_tail(sentences)
    for code, sentences in parallel_corpus.items()
}
ConsoleOut [16]
CollapseExpand
         distinct characters  characters for 99.95% coverage
Korean                    91                              91
Chinese                   87                              87
Thai                      53                              53
Hindi                     46                              46
Spanish                   39                              39
Arabic                    35                              35
Finnish                   33                              33
Swahili                   33                              33
English                   31                              31

The bar chart compares the number of distinct code points needed to reach the same within-language threshold across all 14 aligned rows.

VisualizationOut [18]
CollapseExpand
Coverage counts differ by language, with Korean and Chinese highest in the toy corpus.
Distinct code points needed to cover 99.95 percent of occurrences within each language across all 14 aligned rows. Every observed code point is required in these short samples.

Each sample is small enough that even one omitted occurrence would exceed the 0.05% allowance. Each bar therefore equals that sample's inventory size. The chart does not measure how the threshold divides a corpus pooled across languages.

Setting character_coverage=1.0 asks SentencePiece to cover the full occurrence mass it counts during training. The realized alphabet depends on trainer preprocessing and on how the coverage threshold is calculated. SentencePiece 0.2.2 rounds the computed coverage ratio to a float. The ratio can round up to 1.0 before a rare observed character is included. Check the realized alphabet and test round-trip recovery separately on held-out text from each language. Byte fallback can preserve normalized code points that the learned pieces cannot spell directly.

How normalization changes encoded length

SentencePiece normalizes text before learning and encoding pieces. Its default nmt_nfkc uses a variant of Unicode NFKC and includes whitespace handling. Standard NFC and NFKC prefer composed forms where possible. NFD and NFKD use decomposed forms, and the compatibility forms also fold distinctions such as some fullwidth characters and ligatures. The toy training example uses identity normalization so input preservation can be checked directly. SentencePiece normalization

PythonIn [19]
CollapseExpand
syllable = "한"
nfc = unicodedata.normalize("NFC", syllable)
nfd = unicodedata.normalize("NFD", syllable)

print(
    f"NFC form: {len(nfc)} code point(s), {len(nfc.encode('utf-8'))} UTF-8 bytes"
)
print("  " + ", ".join(f"U+{ord(ch):04X}" for ch in nfc))
print(
    f"NFD form: {len(nfd)} code point(s), {len(nfd.encode('utf-8'))} UTF-8 bytes"
)
print("  " + ", ".join(f"U+{ord(ch):04X}" for ch in nfd))
ConsoleOut [19]
CollapseExpand
NFC form: 1 code point(s), 3 UTF-8 bytes
  U+D55C
NFD form: 3 code point(s), 9 UTF-8 bytes
  U+1112, U+1161, U+11AB

The syllable 한 occupies one code point in NFC and three in NFD. A syllable without a final consonant, such as 가, decomposes into two. A pipeline that keeps the decomposed form can spend three times as many byte or code-point tokens on 한. A learned tokenizer may merge the jamo and use a different number of tokens. A normalizer that composes both inputs to the same syllable gives the tokenizer the same representation in both cases.

PythonIn [20]
CollapseExpand
non_nfc = [
    (code, sentence)
    for code, sentences in parallel_corpus.items()
    for sentence in sentences
    if unicodedata.normalize("NFC", sentence) != sentence
]
print(f"Sentences in this corpus that are not NFC: {len(non_nfc)}")
ConsoleOut [20]
CollapseExpand
Sentences in this corpus that are not NFC: 0

The audit found zero strings that change under NFC among the 126 aligned strings. Run the same check on your own corpus because normalization can affect which distinctions remain available to the model. For example, NFKC maps the fullwidth Latin letter A to A. If the source distinction matters, use an appropriate normalizer before comparing tokenizer outputs.

Bytes as an escape hatch

A finite vocabulary can represent unfamiliar text by keeping a complete smaller alphabet beneath its learned pieces.

SentencePiece's byte_fallback=True includes 256 byte pieces and decomposes unknown normalized characters into UTF-8 bytes. Common text can still use learned pieces. Byte fallback preserves the remaining normalized text, so any distinctions that the normalizer removes stay lost. SentencePiece special symbols

A pure byte model encodes every UTF-8 byte directly. ByT5's paper describes 256 byte values with three additional IDs for padding, end-of-sentence, and an unused unknown marker. Its architecture dispenses with a learned subword vocabulary. It still has to process every byte in its input. ByT5

PythonIn [21]
CollapseExpand
script_samples = {
    "ASCII U+0061": "a",
    "Latin U+00E9": "é",
    "Cyrillic U+0434": "д",
    "Arabic U+0642": "ق",
    "Devanagari U+092C": "ब",
    "Hangul U+D55C": "한",
    "Han U+732B": "猫",
    "Thai U+0E21": "ม",
    "Emoji U+1F408": "🐈",
}

byte_lengths = {
    label: len(sample.encode("utf-8"))
    for label, sample in script_samples.items()
}

The bars show byte lengths for nine selected Unicode scalar values, labeled by script or category and code-point number.

VisualizationOut [23]
CollapseExpand
The ASCII sample occupies one byte, three samples occupy two, four occupy three, and the emoji occupies four.
UTF-8 byte lengths of selected code points. Each bar measures one example rather than the length of a translated message.

A Unicode scalar value uses one to four UTF-8 bytes. That range applies to one scalar at a time. Translations can contain different numbers of scalars, so their byte counts can differ by more than a factor of four. Petrov et al. (2023) report examples of this difference.

A byte-level model fixes the count for a given input to its byte length, apart from additional markers. Byte-level BPE starts from the same byte alphabet and learns merges that can reduce that count. SentencePiece byte fallback uses bytes for unsupported normalized characters and learned pieces elsewhere. All three designs can cover valid UTF-8, but the resulting sequence lengths differ.

A sentence of twenty Han code points that each occupy three bytes gives sixty pure-byte tokens before special tokens. With standard dense self-attention, the number of query-key interactions grows quadratically with sequence length. The actual runtime also depends on the model, kernel, and hardware. ByT5 reports both sequence-length costs and robustness gains on some noisy-text evaluations. ByT5

Key Parameters

The key parameters for multilingual tokenizer training are:

  • vocab_size sets the target number of pieces, including reserved IDs. If training ends below that target, use the realized vocabulary size to count the embedding rows needed for its token IDs.
  • character_coverage sets the occurrence mass used to select the training alphabet. Inspect the final alphabet and held-out coverage for each language.
  • model_type selects the SentencePiece tokenizer family. BPE merges frequent adjacent pairs, and unigram training uses a probabilistic segmentation objective.
  • byte_fallback keeps 256 byte pieces available to represent unsupported characters after normalization.
  • normalization_rule_name controls which text distinctions survive before encoding.

Shared and exclusive tokens

How much of the vocabulary used by each held-out language is shared? Shared IDs make the same embedding entry available to several languages in a model trained with that tokenizer. Token overlap is a property of an encoding sample. It does not reveal how a trained model transfers knowledge.

Collect the set of token IDs used by each language within one tokenizer and divide the size of the intersection by the size of the union. This Jaccard overlap is zero for disjoint sets with a nonempty union and one for identical nonempty sets. The code returns zero when both sets are empty. Each distinct ID counts once, including IDs for whitespace and individual UTF-8 bytes.

PythonIn [24]
CollapseExpand
def used_token_sets(tokenizer):
    """Set of token IDs each language actually uses on the sample corpus."""
    return {
        code: {
            token_id
            for sentence in sentences
            for token_id in tokenizer.encode(sentence)
        }
        for code, sentences in test_by_language.items()
    }


lang_codes = list(test_by_language)


def jaccard_matrix(tokenizer):
    """Pairwise Jaccard overlap of used token sets."""
    sets = used_token_sets(tokenizer)
    matrix = np.zeros((len(lang_codes), len(lang_codes)))
    for i, a in enumerate(lang_codes):
        for j, b in enumerate(lang_codes):
            union = sets[a] | sets[b]
            matrix[i, j] = len(sets[a] & sets[b]) / len(union) if union else 0.0
    return matrix


overlap_english = jaccard_matrix(tok_english)
overlap_balanced = jaccard_matrix(tok_balanced)
ConsoleOut [25]
CollapseExpand
language  tokens used  used only here  shared with another language
  Korean           61              37                            24
    Thai           42              35                             7
   Hindi           39              32                             7
 Chinese           48              30                            18
  Arabic           32              29                             3
 English           43               6                            37
 Spanish           38               5                            33
 Finnish           37               5                            32
 Swahili           38               5                            33

The first heatmap shows pairwise overlap for the English-only tokenizer. Each ID refers to the same tokenizer on both axes. Raw byte pieces can be shared by code points in otherwise different scripts.

VisualizationOut [27]
CollapseExpand
English-only token overlap heatmap has ones on the diagonal and several off-diagonal cells with shared IDs.
Pairwise Jaccard overlap of held-out token ID sets under English-only training. Darker cells indicate higher overlap, including overlap in raw byte pieces.

The second heatmap uses the same language order and definition for the mixed vocabulary.

VisualizationOut [28]
CollapseExpand
Mixed-vocabulary token overlap shows lower Hindi–Thai overlap and higher English–Spanish overlap than in the English-only heatmap.
Pairwise Jaccard overlap under equal-row mixed training. Some pairs share fewer IDs as learned pieces replace raw bytes, while others share more.

The Hindi–Thai overlap declines under the mixed fit, while English–Spanish overlap rises. The examples illustrate that overlap can change in either direction. The English-only model spells much of the non-Latin held-out text with byte pieces. An ID for a continuation byte can occur in unrelated scripts, so a shared byte does not imply a shared morpheme. Common punctuation and digits can also contribute overlap without establishing transfer.

To see which tokens drive an overlap score, inspect the intersection with the tokenizer's ID-to-piece lookup. Count raw byte pieces separately if the question is about learned pieces. For the question asked here, both kinds count because either can occupy a deployed input position. For a vocabulary redesign, you could also weight by how often the tokens occur. Then a rarely used shared piece would contribute less than a shared piece that occurs in most messages. Keep both the weighting choice and the unit of input explicit when comparing overlap across designs.

The economics of an unequal vocabulary

The measurements above are interesting on their own, but the reason multilingual tokenization is a first-class engineering concern is that token counts propagate into everything downstream.

Pre-training budgets

Training budgets often count tokens. Chinchilla studied compute-optimal scaling under a particular training setup, in which roughly twenty training tokens per parameter describes one model-data point. If a collection consumes three times as many tokens for the same number of translated messages, a fixed per-language token budget holds about one third as many such messages, assuming the observed ratio transfers. That arithmetic says how much text fits. It does not establish whether a model is undertrained.

Two models at the same token budget can see different amounts of text. Report bytes seen alongside tokens seen when comparing training exposure across tokenizers. State the encoding and preprocessing used for the byte counts.

Evaluation

Perplexity exponentiates average negative log-likelihood per scored token, with the exponential matched to the logarithm's base. The token unit changes across tokenizers and can represent very different amounts of text across languages even with one tokenizer. A higher token count makes each scoring decision cover a smaller unit on average. The model's probability of that unit is an empirical question.

For comparisons that score the same text span under compatible preprocessing, compute the total sequence loss in bits per UTF-8 byte:

bits per byte=bits per scored token×TscoredUTF-8 bytes scored.\text{bits per byte} = \frac{\text{bits per scored token} \times T_{\text{scored}}}{\text{UTF-8 bytes scored}}.

Here TscoredT_{\text{scored}} counts the token targets that enter the average, and the multiplication recovers the total bits assigned to those targets. Count the UTF-8 bytes in the same span those targets represent. If preprocessing drops or changes text, compare both models on the same retained text and byte span. A raw byte count would include bytes that the model did not score. Match the held-out inputs, conditioning, boundary conventions, and special-token treatment. This per-byte loss scores the token sequence the tokenizer chose. The probability of the decoded text sums the probabilities of all valid token sequences that decode to it. Geh et al. (2024).

Consider the same 100-byte passage scored in two representations. A model that scores 25 targets at four bits per target assigns 100 bits to the passage. Another that scores 50 targets at two bits per target also assigns 100 bits. Both give one bit per byte, despite a twofold difference in average loss measured in bits per token. This equality assumes that the model scores the same complete passage under the same conditioning convention.

Context windows and cost

An 8,192-token context holds about the same number of translated messages as 2,048 English tokens if the measured premium is four and applies to the document in question. That estimate assumes all 8,192 positions are available for the text. Conversation history, system instructions, and generation can take some of those positions. At the same per-token input price, the same document-length ratio also applies to the input charge for those tokens.

When training frequency and deployment goals differ

Greedy BPE selects frequent pairs in the training sample. A deployment workload might instead care about the tail latency of multilingual messages or the cost of serving a fixed number of requests in each language. Those goals can give much more weight to a language than its raw training frequency provides.

Reweighting the tokenizer training mixture can move the allocation. In our example the mixed fit spends more positions on English and fewer on Hindi. Other vocabulary learners can also change their objective. Xu et al. (2021), for example, formulate finding a vocabulary and size for machine translation as an optimal transport problem. That work illustrates explicit vocabulary design in a different setting. VOLT

Limitations and impact

The paired measurements use four held-out messages per language. Changing the split, topic, or trainer can change the results. For a larger example, Petrov et al. measure premiums on FLORES-200 and find substantial disparities even across deliberately multilingual tokenizers. The exact range depends on the language pair, corpus, and tokenizer. Petrov et al.

Token count measures tokenizer behavior. Model performance also depends on the training data and the learned model. Isolating tokenization's contribution to task performance requires controls beyond the two tokenizer fits used here.

Vocabulary size also has a parameter cost. With a conventional embedding width of 1,024, a 250,000-piece vocabulary requires 250,000×1,024=256250{,}000\times1{,}024=256 million embedding parameters. A separate dense output projection can add another table of the same shape up to transposition. Weight tying shares those parameters, while factorized embeddings can reduce the parameter count when the intermediate embedding width is small enough. Replacing a trained model's tokenizer can change the IDs, shapes, and segmentation to which it is adapted. Treat the change as a model adaptation problem and evaluate it accordingly.

This chapter's two fits make the practical decision visible. If long prompts in a target language are expensive, measure the costs on aligned text, record absolute token counts, and check how often the tokenizer relies on byte pieces. That tells you how much of the current context and input budget the encoding consumes.

The next chapter, Multilingual Pre-training and Data Balancing, covers how to distribute training data once a tokenizer is in place. Cross-Lingual Transfer and Alignment looks at what learned representations carry across languages. Low-Resource and Endangered Languages examines the settings with the least training data. All three chapters are in Part XXVI.

Summary

  • Fertility measures tokens per word under a stated word segmentation convention. Bytes per token describes compression, and the tokenization premium compares token counts on parallel text.
  • BPE adds each language's eligible pair occurrences to the global count at the current step. Corpus weighting changes candidates' relative counts, and later merges change the symbol stream.
  • Coverage targets character occurrence mass. Byte fallback adds 256 reserved pieces and preserves otherwise unsupported characters after normalization.
  • Unicode normalization can change code-point and byte sequences. One Hangul syllable can decompose into two or three code points. The final token count depends on how the tokenizer represents them.
  • Raw UTF-8 requires one to four bytes per scalar value. Translations can have different numbers of scalars, so the per-scalar bound gives no fixed cross-language premium.
  • A fixed context or input rate makes absolute token counts matter. To compare losses on the same text across tokenizers, report bits per byte with the scoring, preprocessing, and boundary conventions stated.
  • Token ID overlap measures shared vocabulary usage within a tokenizer. Any overlap can include byte fragments, punctuation, and whitespace.

Quiz

Ready to test your understanding? Take this quick quiz to reinforce what you've learned about multilingual tokenization and vocabulary allocation.

Multilingual Tokenization and Vocabulary Allocation

Question 1 of 80 of 8 completed
According to the chapter, what does fertility measure?
Join the discussionAsk a question or share what you learned.

Comments

Add to the conversation

A question, a correction, or an example from your own work.

No comments yet. Be the first to share your thoughts!

A different angle
All writing
Language AI Handbook · Vol. 8

Code-Switching and Mixed-Language Text

Learn how code-switching breaks language ID, tokenization, and generation pipelines. Covers switch-point F1, mixed scripts, Unicode traps, and evaluation.

45 min read
Language AI Handbook · Vol. 8

Cross-Lingual Transfer and Alignment

Learn how cross-lingual transfer works: shared representations, zero-shot and translate-train designs, alignment objectives, adapters, diagnostics, and evaluation.

43 min read
Language AI Handbook · Vol. 8

Cultural and Multilingual Evaluation

Measure what multilingual benchmarks miss: translationese, construct validity, cultural knowledge, local harms, and native-speaker-led evaluation design.

54 min read

About the author

Reference

Citation details

Cite or share this article.

BIBTEXAcademic
@misc{brenndoerfer2026multilingualtokenization, author = {Michael Brenndoerfer}, title = {Multilingual Tokenization and Vocabulary Allocation}, year = {2026}, url = {https://mbrenndoerfer.com/writing/multilingual-tokenization-vocabulary-allocation}, organization = {mbrenndoerfer.com}, note = {Accessed: 2026-12-03} }
APAAcademic
Michael Brenndoerfer (2026). Multilingual Tokenization and Vocabulary Allocation. Retrieved from https://mbrenndoerfer.com/writing/multilingual-tokenization-vocabulary-allocation
MLAAcademic
Michael Brenndoerfer. "Multilingual Tokenization and Vocabulary Allocation." 2026. Web. December 3, 2026. <https://mbrenndoerfer.com/writing/multilingual-tokenization-vocabulary-allocation>.
CHICAGOAcademic
Michael Brenndoerfer. "Multilingual Tokenization and Vocabulary Allocation." Accessed December 3, 2026. https://mbrenndoerfer.com/writing/multilingual-tokenization-vocabulary-allocation.
HARVARDAcademic
Michael Brenndoerfer (2026) 'Multilingual Tokenization and Vocabulary Allocation'. Available at: https://mbrenndoerfer.com/writing/multilingual-tokenization-vocabulary-allocation (Accessed: December 3, 2026).
SimpleBasic
Michael Brenndoerfer (2026). Multilingual Tokenization and Vocabulary Allocation. https://mbrenndoerfer.com/writing/multilingual-tokenization-vocabulary-allocation
Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy