Sub topic 1
Why build one model for many languages
Prerequisites
This chapter assumes basic Python and experience with the Hugging Face transformers library. You should understand transformer encoders and masked language modeling at a conceptual level. Familiarity with tokenizers helps but is not required.
Why one model can replace many
Training a separate model for each language is costly. Many languages have little labeled data, so a model trained only on one of them often performs poorly. A single multilingual model shares what it learns across languages. A task learned from English examples can often transfer to German or Swahili with little extra work.
The cost is capacity. A fixed set of parameters must serve every language, which can lower accuracy for each one.
One vocabulary for many scripts: shared subword tokenization
A tokenizer splits text into pieces called tokens. XLM-R uses a SentencePiece subword tokenizer with one vocabulary built from text in all of its pretraining languages. Frequent words stay whole, and rarer words split into smaller pieces. Because the vocabulary covers many scripts, one tokenizer handles Latin, Devanagari and other writing systems.
Run this script to compare how the shared vocabulary splits three sentences:
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)> Tokenization cost varies by language.
Pretraining on many languages: mBERT and XLM-R
mBERT (multilingual BERT) was pretrained with masked language modeling on Wikipedia text from 104 languages. XLM-R (XLM-RoBERTa) was pretrained on filtered CommonCrawl text in 100 languages, about 2.5 terabytes in total. Both models hide some tokens and predict them from context. This step needs no parallel translations. To help low-resource languages, sampling is weighted so they appear more often than their raw share of the data would give.
Why representations line up across languages
Pretraining on many languages with a shared vocabulary pushes words with similar meanings toward similar vectors, even across languages. Shared subwords such as names, numbers and loanwords act as anchor points. The model learns a common space for meaning, but the alignment is imperfect. It is strongest for languages with more pretraining data and related scripts.
Exercise
Why might a Hindi sentence produce more tokens than an English sentence with the same meaning?
Show answer
The shared vocabulary may contain fewer whole words or subwords for Hindi, so the tokenizer splits its text into more, smaller pieces.