Sub topic 3
Pretraining on many languages: mBERT and XLM-R
This chapter assumes you know how masked language modeling (MLM) works for a single-language BERT. It also assumes you can load a model with the Hugging Face transformers library and have seen the shared subword vocabulary from the previous chapter. Here you will see how two models, mBERT and XLM-R, are pretrained on many languages at once. You will also see what they have in common and where they differ. The last section covers the errors people most often make when using them.
The core idea: one model, one objective, many languages
A multilingual encoder is trained like a monolingual one. You take a transformer encoder, mask some tokens in the input, and train the model to predict them. The only change is the data. The training corpus is a mix of text in dozens of languages, and the vocabulary is a single shared subword vocabulary.
Two things are missing from this recipe:
- There are no parallel sentences, meaning translated pairs. The model never sees "this English sentence means this German sentence".
- There are no explicit language-alignment losses. Nothing in the loss asks the model to map "cat" and "Katze" to similar vectors.
Any cross-lingual alignment the model shows is a side effect of sharing parameters and a vocabulary across languages. The next chapter looks at why that works. This chapter is about how the models are built.
mBERT
mBERT (multilingual BERT) was released by the BERT authors in 2018. It is the original multilingual pretrained encoder.
- Data: Wikipedia dumps for 104 languages.
- Vocabulary: a WordPiece vocabulary of about 110,000 subwords shared by all languages.
- Architecture: BERT-base, with 12 layers and a hidden size of 768.
- Objective: MLM plus next-sentence prediction (NSP), as in the original BERT.
- Sampling: exponentially smoothed sampling, so that large languages are downweighted and small languages are upweighted relative to their raw share of the data. The Unequal data chapter covers this in detail.
mBERT was a surprise. Fine-tuned on English task data only, it performed well on other languages, even though it had no explicit cross-lingual training signal. That result started the research area this tutorial covers.
Its limits are also clear. Wikipedia is small for many languages, and the vocabulary has to cover 104 languages with only about 110k entries. Languages with little data and unusual scripts get poor coverage, which affects tokenization quality.
XLM-R
XLM-R (XLM-RoBERTa) was released by Facebook AI in 2019. It applies the RoBERTa training recipe to a much larger multilingual corpus.
- Data: CommonCrawl text filtered into the CC-100 corpus, covering 100 languages. For many languages this is far larger than Wikipedia. Low-resource languages benefit the most.
- Vocabulary: a SentencePiece unigram model with 250,000 subwords, trained on text from all languages.
- Architecture:
xlm-roberta-basehas 12 layers, hidden size 768, and about 270M parameters.xlm-roberta-largehas 24 layers, hidden size 1024, and about 550M parameters. - Objective: MLM only. There is no NSP, and masks are generated dynamically each time a sequence is seen.
- Sampling: smoothed sampling with a smaller exponent than mBERT's, which gives low-resource languages a larger share of training batches.
Most of the parameters in the base model sit in the embedding matrix. With 250,000 vocabulary entries and a hidden size of 768, the embeddings alone hold about 192M parameters. The transformer layers hold only about 85M.
from transformers import AutoModelForMaskedLM
model = AutoModelForMaskedLM.from_pretrained("xlm-roberta-base")
total = sum(p.numel() for p in model.parameters())
embed = model.roberta.embeddings.word_embeddings.weight.numel()
print(f"total parameters: {total / 1e6:.0f}M")
print(f"word embeddings: {embed / 1e6:.0f}M")
print(f"share in embeddings: {embed / total:.0%}")Running this shows that roughly 70 percent of the model is the word embedding matrix. This detail matters later, when we discuss model capacity and adapters.
Comparing the two models
| Property | mBERT | XLM-R |
|---|---|---|
| Languages | 104 | 100 |
| Training data | Wikipedia | CommonCrawl (CC-100) |
| Tokenizer | WordPiece, about 110k | SentencePiece unigram, 250k |
| Objective | MLM and NSP | MLM only |
| Masking | Static in the original release | Dynamic |
| Typical zero-shot XNLI average | Lower | Higher, by several points |
The gap between the two comes from several changes made together: more data, a bigger vocabulary, RoBERTa-style training, and longer training. The XLM-R paper reports that its base model matches or beats mBERT on cross-lingual benchmarks, and that the large model is clearly stronger. The two models differ in many ways at once, so it is hard to credit the gain to any single change.
Looking at the tokenizer
The vocabulary is where multilingual design choices show up first. You can compare how the two tokenizers split the same sentence.
from transformers import AutoTokenizer
text = "आज मौसम अच्छा है।"
for name in ["bert-base-multilingual-cased", "xlm-roberta-base"]:
tok = AutoTokenizer.from_pretrained(name)
pieces = tok.tokenize(text)
print(name, len(pieces), pieces)Expect XLM-R to use fewer pieces for scripts such as Devanagari, because its larger vocabulary has more room for them. The exact counts depend on the tokenizer versions you load, so treat any specific numbers as something to check yourself.
Training details that matter in practice
Sequence format
Both models were pretrained on single-language chunks of text. A training sequence normally contains one language. Mixed-language sequences are rare in the data, so code-switched input (text that mixes languages within a sentence) is unusual for these models. They often handle it acceptably, but it is outside what pretraining directly covered.
No language identifier
mBERT and XLM-R do not take a language ID as input. The model must infer the language from the tokens. This is convenient because you do not need to know the language at inference time. It also means that for closely related languages that share vocabulary, the model has no explicit way to tell them apart.
This differs from the earlier XLM model (without the R), which added language embeddings and, in one variant, a translation language modeling objective on parallel data. XLM-R dropped both and still did better with more monolingual data.
Case handling
bert-base-multilingual-cased keeps case and is the recommended mBERT checkpoint. An uncased variant exists, but stripping accents and lowercasing across 100 languages removes information that matters in some of them. XLM-R's SentencePiece tokenizer is case-sensitive by default.
Sequence length
Both models use a maximum of 512 positions. This is the limit you hit when feeding long documents, and in languages where the tokenizer is less efficient, 512 tokens cover less text.
Common errors
- Assuming equal quality across all languages. Both models cover many languages, but the quality of the representations varies a great deal. Languages with large pretraining corpora such as English, German, and Russian are much stronger than those with small corpora.
- Using the wrong tokenizer for a checkpoint. The vocabulary is part of the model. If you load the XLM-R model with the mBERT tokenizer, token IDs map to the wrong embeddings and the output is meaningless. Always load both with the same name via
AutoTokenizerandAutoModel. - Forgetting the sentence-pair format. For tasks with pairs, such as natural language inference, pass both texts to the tokenizer together so it inserts the correct separator tokens. XLM-R uses
<s>and</s>and does not use token type IDs. - Expecting a
[CLS]token in XLM-R. The equivalent is<s>. Code written for BERT that hard-codes[CLS]will fail. - Judging the model by an English-only test. A multilingual model can score well in English while failing in the language you care about. Always evaluate in the target language.
- Overlooking the memory cost of the vocabulary. The 250k-entry embedding matrix makes XLM-R-base a 270M parameter model, even though its encoder is the same size as BERT-base. Plan GPU memory and checkpoint sizes accordingly.
Which one should you pick?
For almost every new project, start with XLM-R. It has stronger benchmark results, better coverage of low-resource languages, and a more capable tokenizer. mBERT remains useful when you need to reproduce earlier work, or when you need a smaller vocabulary and a faster model, since its embedding matrix is a little under half the size.
If your target language is not among the 100 or so in the pretraining data, expect weaker results. Related languages that share a script with a covered language may still work, but there is no guarantee.
Summary of the working model
- Multilingual pretraining is MLM on a mix of languages with one shared subword vocabulary and one set of weights.
- No parallel data or language IDs are used by mBERT or XLM-R.
- XLM-R improves on mBERT mainly through much more data, a larger vocabulary, and the RoBERTa recipe.
- Sampling controls how often each language appears, and the vocabulary controls how well each language is tokenized. Both shape quality per language.
Exercise
mBERT and XLM-R are both trained without parallel (translated) text and without a language ID input. Name two ways in which XLM-R's pretraining setup differs from mBERT's, and explain why more than 70 percent of xlm-roberta-base's parameters are not in its transformer layers.
Show answer
Any two of: XLM-R uses CommonCrawl (CC-100) instead of Wikipedia, a 250k SentencePiece vocabulary instead of a roughly 110k WordPiece vocabulary, MLM only without next-sentence prediction, and dynamic masking. The parameters are in the word embedding matrix: 250,000 vocabulary entries times a hidden size of 768 is about 192M parameters, while the 12 transformer layers hold about 85M, so embeddings make up roughly 70 percent of the roughly 270M total.
Exercise
You fine-tune a classifier from xlm-roberta-base but, by mistake, tokenize your data with the bert-base-multilingual-cased tokenizer. The code runs without errors. Why is the result still wrong?
Show answer
Token IDs from the mBERT vocabulary refer to different subwords than the same IDs in the XLM-R vocabulary. The model looks up the wrong embeddings, so it receives meaningless input. Shapes happen to be compatible, so nothing raises an error, but accuracy will be poor. The tokenizer must always come from the same checkpoint as the model.