Multilingual Tokenization and Vocabulary Allocation › Where the vocabulary budget goes

Michael BrenndoerferNovember 25, 202613 min read
Language AI HandbookAll chapters
Part 26 of 67Multilingual Language Models and Cross-Lingual Transfer
Chapter 184Multilingual Tokenization and Vocabulary Allocation › Where the vocabulary budget goes
Reading section 3 of 11 · Where the vocabulary budget goes · 13 minSection 3 of 11 · 13 min

Section 3 of 11 · 13 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

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.

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!

Newsletter

Stay up to date

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

Unsubscribe at any time. Privacy policy