Multilingual NLP: Cross-lingual Transfer and Zero-Shot Learning
What You'll Learn
- 1Explain why one shared vocabulary and objective produce cross-lingual representations
- 2Measure tokenizer fertility and its effect on sequence length and cost
- 3Compute language sampling probabilities under temperature rebalancing
- 4Design a zero-shot transfer evaluation that isolates language effect
Most of the world's languages lack labeled data, so multilingual NLP trains one model on many languages and transfers from high resource ones to the rest. The bet is that a shared encoder learns structure that survives translation: sentiment, entities, and entailment behave the same whether the text is English, Turkish, or Swahili. This lesson covers the shared model designs, the tokenization costs they carry, and how sampling and evaluation decide whether transfer actually works.
Shared Multilingual Models
Multilingual BERT trains a single masked language model on the Wikipedia dumps of 104 languages with a 119,547 token vocabulary, while XLM-R trains on filtered CommonCrawl text for 100 languages and reaches roughly 2.5 terabytes of text. The loss is simply the sum of masked language modeling losses across languages:
Data volume drives most of the improvement. XLM-R large reaches an average of 79.1 on XNLI across 15 languages, against 75.1 for the earlier XLM system, 66.3 for XLM-R base, and 62.1 for multilingual BERT, and the largest per language jumps show up on the languages that were rare in pretraining rather than on English.
| Model | Pretraining corpus | Vocabulary | XNLI average |
|---|---|---|---|
| mBERT | Wikipedia, 104 languages | 119,547 word pieces | 62.1 |
| XLM | News crawls, 100 languages | 95,000 sentence pieces | 75.1 |
| XLM-R base | CommonCrawl, 100 languages | 250,000 sentence pieces | 66.3 |
| XLM-R large | CommonCrawl, 100 languages | 250,000 sentence pieces | 79.1 |
Vocabulary and Tokenization Cost
A shared vocabulary is a compromise: every language draws from one table, so high resource languages take most of the slots and low resource ones fragment into long subword chains. Fertility measures the damage directly:
Fertility near 1.3 is comfortable for English, while agglutinative languages such as Turkish or Finnish commonly sit above 2, which means longer sequences, more attention work, and fewer words per context window. SentencePiece mitigates this with unigram sampling over a script aware corpus, and byte or character fallback guarantees that any input decodes to something instead of an unknown token.
Two mitigations matter in practice. First, cap input length per language rather than per dataset, so fertility does not silently truncate half a sentence of a morphologically rich language. Second, measure downstream cost in tokens per document, not tokens per word, because serving budgets are priced in tokens.
Sampling and Alignment
Multilingual pretraining is unbalanced by construction, so batches must be sampled deliberately. Temperature sampling keeps empirical frequencies but flattens them, drawing language with probability:
At you sample by raw corpus size and the largest language dominates every batch. As rises, probabilities flatten toward uniform and low resource languages get enough gradient signal to learn anything at all.
Alignment keeps transfer working. Because the encoder never sees a language tag, sentences that mean the same thing are pushed toward similar representations, and downstream heads trained in English read the target language through the same geometry:
Evaluating Across Languages
Three designs separate language effect from task effect. Zero-shot trains on English and tests elsewhere; few shot adds a small target language sample and plots accuracy against label count; translation transfer translates target text into English and runs an English system, which is a strong but expensive baseline.
Report per language scores and the average over languages, since averaging over examples lets English sized datasets dominate. XNLI solves this with 7,500 test examples in each of 15 languages, and machine translated benchmarks such as XTREME and FLORES-200 extend the same idea across tagging, retrieval, and translation quality.
Worked Examples
Worked Code
"""Measure tokenizer fertility across languages, romanized to stay ASCII."""
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained("xlm-roberta-base")
samples = {
"en": "The weather in London was unusually warm today",
"sw": "Angalau hewa mjini London ilikuwa ya joto leo",
"ur": "London ka mausam aaj gair mamooli garam tha",
}
for lang, text in samples.items():
ids = tok(text).input_ids
print(lang, "tokens", len(ids), "words", len(text.split()),
"fertility", round(len(ids) / len(text.split()), 2))
"""Temperature based language sampling for a multilingual corpus."""
import random
from collections import Counter
def language_probs(counts, temperature=2.0):
weights = {l: n ** (1.0 / temperature) for l, n in counts.items()}
total = sum(weights.values())
return {l: w / total for l, w in weights.items()}
counts = {"en": 1_000_000, "tr": 100_000, "sw": 20_000, "ur": 10_000}
probs = language_probs(counts, temperature=2.0)
print({k: round(v, 3) for k, v in probs.items()})
sampled = random.choices(list(probs), weights=list(probs.values()), k=8)
print(Counter(sampled))
Real-World Applications
- Global support desks - One classifier routes tickets in a dozen languages, trained with labels mostly from English and Spanish.
- Search - Entity and intent models transfer to languages where labeling budgets never existed, then get a few hundred local examples.
- Content moderation - Toxicity detectors cover low resource languages through transfer, which is cheaper than annotating each one.
- Localization QA - Product teams compare per language accuracy to decide where human review is mandatory.
đĄAverages hide language failures
Common Mistakes
Copying English thresholds to other languages
Fix: Recalibrate similarity and confidence cutoffs per language, since score distributions shift.
Ignoring fertility when sizing context
Fix: Budget tokens per language, otherwise agglutinative text truncates first.
Averaging scores over examples
Fix: Average over languages so large datasets do not dominate the headline number.
Best Practices
- Report per language results plus the language macro average
- Track fertility and tokens per document for every supported language
- Include a translation transfer baseline to bound how much the multilingual model buys
Key Takeaways
- mBERT trains one masked model over 104 Wikipedia languages while XLM-R uses 100 CommonCrawl languages
- Fertility is subwords per word and it drives sequence length, cost, and truncation
- Temperature sampling flattens language frequencies so minority languages receive gradient
- XNLI scores 62.1 for mBERT and 79.1 for XLM-R large, so data scale matters more than the objective
Frequently Asked Questions
Why does transfer work at all?
Because syntax and semantics partially align across languages, and the shared vocabulary forces similar strings together. Fine tuned heads then read a representation space that the source language already organized.
When does translation transfer beat a multilingual model?
For high resource language pairs with strong machine translation, translating into English and running the best English system is hard to beat. It loses on latency, cost, and languages with poor translation coverage.
How do you handle languages with no pretraining data?
Add them to the corpus and retrain, or fall back to character and byte models with language specific tokenizers. Transfer alone cannot invent representations for scripts the model never saw.
Interview Questions
Q1: How would you evaluate a multilingual classifier before shipping to six languages?
Train on English, run zero-shot per language on a balanced test set, add a few hundred labeled examples to plot the low resource curve, and compare against translating into English.
Q2: Why does temperature sampling help multilingual training?
It flattens the empirical distribution without going uniform, so the minority languages get a meaningful share of batches while the head of the distribution still dominates appropriately.