TAI BUI
Back to curriculum
BuildPython

Multilingual NLP

One model, 100+ languages, and most of them never saw a single labeled example. Cross-lingual transfer is the closest NLP gets to a free lunch, and it actually works.

TIME: ~45 minutesPREREQUISITES: Phase 5 · 04 (GloVe, FastText, Subword), Phase 5 · 11 (Machine Translation)

Learning Objectives

  • Explain zero-shot and few-shot cross-lingual transfer, and why fine-tuning on 100-500 target-language examples is the single most cost-effective lever for closing the accuracy gap.
  • Pick a fine-tuning source language using language-similarity evidence (qWALS, LANGRANK) instead of defaulting to English by habit.
  • Diagnose the tokenization tax: fertility, variant recovery, and capacity spillover, which let a low-resource fine-tune look healthy in training while it ships broken output to production.
  • Evaluate a multilingual model per language instead of by aggregate accuracy, using entity-level tests and cross-lingual consistency checks.

The Problem

English has billions of labeled examples. Urdu has thousands. Maithili has almost none. Any system that has to serve a global audience runs straight into that long tail: most of the world's languages never had, and never will have, a labeled dataset built for your specific task.

Multilingual models get around this with zero-shot cross-lingual transfer: train one model across many languages at once, so a representation it learns from a high-resource language carries over to a low-resource one, then fine-tune on a task in whatever language you have labeled data for and run it on a language you don't. Fine-tune on English sentiment analysis, and the same model, with no Urdu training data at all, produces solid sentiment predictions on Urdu. That's the whole trick, and it's the reason NLP ships to the whole world instead of just the languages with big labeled datasets.

The tradeoffs and the canonical models are below. The one decision that trips up almost every team new to this: which language to fine-tune on. Most default to English without checking whether that's actually the right call.

Warm-up0/3
1. A company has thousands of labeled English support tickets but zero labeled tickets in Swahili. Before learning any specific NLP technique, what is the most promising general strategy for classifying the Swahili tickets reasonably well?Warm-up
2. A subword tokenizer splits a rare word like 'unhappiness' into pieces such as 'un', 'happi' and 'ness'. Why do subword tokenizers do this instead of keeping one entry per whole word?Warm-up
3. Two sentence embeddings are normalized to unit length and point in almost the same direction. What does their cosine similarity (the dot product) come out as?Warm-up
Check: The Problem0/1
1. What is cross-lingual transfer?Define

The Concept

Cross-lingual transfer via shared multilingual embedding space

Shared vocabulary. Multilingual models use a SentencePiece or WordPiece tokenizer trained on text from every target language at once, so the same subword unit represents the same morpheme across related languages: anti- in English and Italian gets the same token.

Shared representation. A transformer pretrained on masked language modeling across many languages learns that semantically similar sentences in different languages produce similar hidden states. mBERT, XLM-R, and NLLB all show this. Embeddings for "cat" in English cluster near "chat" in French and "gato" in Spanish, and full-sentence embeddings do the same thing.

Zero-shot transfer. Fine-tune the model on labeled data in one language, usually English, then run it at inference on any other language the model supports. No target-language labels needed. Results are strong for typologically related languages and weaker for distant ones.

Few-shot fine-tuning. Add 100-500 labeled examples in the target language and accuracy jumps to 95-98% of the English baseline on classification tasks. Of everything in this lesson, this is the single most cost-effective lever you have.

Check: The Concept0/5
1. What is a multilingual model?Define
2. What does zero-shot cross-lingual transfer mean?Define
3. How many target-language examples does few-shot fine-tuning typically need to reach 95-98% of the English baseline on classification?Define
4. Why does training one SentencePiece or WordPiece tokenizer on text from every target language help a multilingual model?Explain
5. Why can a model fine-tuned only on English sentiment data still predict Urdu sentiment reasonably well?Explain

The models

ModelYearCoverageNotes
mBERT2018104 languagesTrained on Wikipedia. First practical multilingual LM. Weak on low-resource.
XLM-R2019100 languagesTrained on CommonCrawl (much larger than Wikipedia). Sets the cross-lingual baseline. Base 270M, Large 550M.
XLM-V2023100 languagesXLM-R with 1M-token vocabulary (vs 250k). Better on low-resource.
mT52020101 languagesT5 architecture for multilingual generation.
NLLB-2002022200 languagesMeta's translation model; includes 55 low-resource languages.
BLOOM202246 languages + 13 programmingOpen 176B LLM trained multilingually.
Aya-23202423 languagesCohere's multilingual LLM. Strong on Arabic, Hindi, Swahili.

Pick by use case, not by whichever model is trending. XLM-R-base is the sane default for classification. For generation, reach for mT5 or NLLB depending on whether you're translating or generating open text. For LLM-style work, pair Aya-23 or Claude with explicit multilingual prompting.

Check: The models0/4
1. What is mBERT?Define
2. Which model is the 100-language RoBERTa pretrained on CommonCrawl that serves as the cross-lingual baseline?Define
3. What is NLLB-200, and how many languages does it cover?Define
4. Why does the lesson treat XLM-R, not mBERT, as the cross-lingual baseline?Explain

The source-language decision (2026 research)

Most teams default to English as the fine-tuning source, mostly because English is where the labeled data already sits. Research from 2026 says that default is wrong more often than people assume.

Language similarity predicts transfer quality better than raw corpus size does. For Slavic targets, German or Russian often beat English. For Indic targets, Hindi often beats English. The qWALS similarity metric (2026, based on World Atlas of Language Structures features) quantifies this directly. LANGRANK (Lin et al., ACL 2019) is a separate, earlier method that ranks candidate source languages using a combination of linguistic similarity, corpus size, and genetic relatedness.

Practical rule: if your target language has a typologically close high-resource relative, fine-tune on that one first and compare it against the English fine-tune before you commit to either.

Check: The source-language decision (2026 research)0/4
1. What are qWALS and LANGRANK?Define
2. Why does English as the fine-tuning source not always give the best transfer for a non-English target?Explain
3. A team fine-tunes on English for a Slavic target, gets weak accuracy and plans to collect more English data. Which assumption is most likely wrong?Analyze
4. You must build a Ukrainian classifier. You have plenty of English and Russian labeled data and about 300 Ukrainian examples. Which plan fits the lesson?Design

Build It

Step 1: zero-shot cross-lingual classification

There's no labeled sentiment data in any of the three languages below, and the model was never fine-tuned on sentiment at all. It was fine-tuned on NLI (natural language inference: given a premise and a hypothesis, decide whether the premise entails, contradicts, or stays neutral toward the hypothesis). The zero-shot trick is to turn each candidate label into a hypothesis, "This text is about {label}.", and ask the model how strongly the input text entails it. Whichever label's hypothesis scores highest wins. logits[2] below reads out the entailment class in this checkpoint's label order (contradiction=0, neutral=1, entailment=2), so softmax-ing the logits and taking index 2 is exactly that entailment score.

python
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch
 
tok = AutoTokenizer.from_pretrained("joeddav/xlm-roberta-large-xnli")
model = AutoModelForSequenceClassification.from_pretrained("joeddav/xlm-roberta-large-xnli")
 
 
def classify(text, candidate_labels, hypothesis_template="This text is about {}."):
    scores = {}
    for label in candidate_labels:
        hypothesis = hypothesis_template.format(label)
        inputs = tok(text, hypothesis, return_tensors="pt", truncation=True)
        with torch.no_grad():
            logits = model(**inputs).logits[0]
        entail_score = torch.softmax(logits, dim=-1)[2].item()
        scores[label] = entail_score
    return dict(sorted(scores.items(), key=lambda x: -x[1]))
 
 
print(classify("I love this product!", ["positive", "negative", "neutral"]))
print(classify("मुझे यह उत्पाद पसंद है!", ["positive", "negative", "neutral"]))
print(classify("J'adore ce produit !", ["positive", "negative", "neutral"]))

One model, three languages, one API, and zero target-language labels: the entailment trick is what turns an NLI-tuned XLM-R into a zero-shot classifier for any language it covers.

Step 2: multilingual embedding space

If the model's shared representation actually holds, the same sentence translated into different languages should land close together in embedding space, and an unrelated sentence should land farther away regardless of language. The check below encodes one English sentence, its translations into French, Spanish, and German, and one unrelated English sentence, then compares each pair with cosine similarity.

python
from sentence_transformers import SentenceTransformer
import numpy as np
 
model = SentenceTransformer("sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2")
 
pairs = [
    ("The cat is sleeping.", "Le chat dort."),
    ("The cat is sleeping.", "El gato está durmiendo."),
    ("The cat is sleeping.", "Die Katze schläft."),
    ("The cat is sleeping.", "The dog is barking."),
]
 
for eng, other in pairs:
    emb_eng = model.encode([eng], normalize_embeddings=True)[0]
    emb_other = model.encode([other], normalize_embeddings=True)[0]
    sim = float(np.dot(emb_eng, emb_other))
    print(f"  {eng!r} <-> {other!r}: cos={sim:.3f}")

Translations land close together in embedding space. A different English sentence lands farther away. That gap is what makes cross-lingual retrieval, clustering, and similarity search work at all.

Step 3: few-shot fine-tuning strategy

Zero-shot gets a model in the door; a small pile of labeled examples in the target language is what actually closes the remaining gap to English-level accuracy. The function below runs that fine-tune given a base model, its tokenizer, and a short list of {text, label} examples.

python
from transformers import TrainingArguments, Trainer
from datasets import Dataset
 
 
def few_shot_finetune(base_model, base_tokenizer, examples):
    ds = Dataset.from_list(examples)
 
    def tokenize_fn(ex):
        out = base_tokenizer(ex["text"], truncation=True, max_length=128)
        out["labels"] = ex["label"]
        return out
 
    ds = ds.map(tokenize_fn)
    args = TrainingArguments(
        output_dir="out",
        per_device_train_batch_size=8,
        num_train_epochs=5,
        learning_rate=2e-5,
        save_strategy="no",
    )
    trainer = Trainer(model=base_model, args=args, train_dataset=ds)
    trainer.train()
    return base_model

For 100-500 target-language examples, num_train_epochs=5 and learning_rate=2e-5 are safe defaults. Push the learning rate any higher and the multilingual alignment collapses, and you're left with a model that's effectively English-only.

Check: Build It0/5
1. The `classify` function runs with the text 'मुझे यह उत्पाद पसंद है!' and the candidates ['positive', 'negative', 'neutral']. How many forward passes of the NLI model does that single call make?Apply
2. In `classify`, the NLI model returns logits in the order contradiction, neutral, entailment. For label 'positive' the softmax is [0.05, 0.15, 0.80], and for 'negative' it is [0.70, 0.20, 0.10]. What does the function put first in its returned dictionary?Apply
3. Using the cosine check in the embedding step, which pair should have the lowest cosine similarity?Apply
4. `few_shot_finetune` is run on 200 examples with `per_device_train_batch_size=8` and `num_train_epochs=5` on one device. How many optimizer steps does training take?Apply
5. You fine-tune a multilingual model on 300 Hindi examples using a learning rate of 5e-4, far above the usual 2e-5. English accuracy holds steady, but other languages get noticeably worse. What most likely happened?Analyze

Evaluation that actually works

  • Per-language accuracy on held-out sets. Not aggregated. The aggregate hides the long tail.
  • Benchmark against monolingual baseline. For languages with enough data, a monolingual model trained from scratch sometimes beats the multilingual one. Test.
  • Entity-level tests. Named entities in the target language. Multilingual models often have weak tokenization for scripts far from Latin.
  • Cross-lingual consistency. Same meaning in two languages should produce the same prediction. Measure the gap.
Check: Evaluation that actually works0/5
1. What does a cross-lingual consistency check measure?Define
2. When is a monolingual model trained from scratch worth trying instead of a multilingual one?Explain
3. Why does the lesson recommend entity-level tests for named entities in non-Latin scripts?Explain
4. Your multilingual sentiment classifier reports 91% aggregate accuracy averaged across 40 languages. What should you check before shipping it?Analyze
5. You are about to launch a classifier in 12 languages, including three non-Latin-script ones. Which evaluation plan fits the lesson best?Design

Use It

The 2026 stack:

TaskRecommended
Classification, 100 languagesXLM-R-base (~270M) fine-tuned
Zero-shot text classificationjoeddav/xlm-roberta-large-xnli
Multilingual sentence embeddingssentence-transformers/paraphrase-multilingual-MiniLM-L12-v2
Translation, 200 languagesfacebook/nllb-200-distilled-600M (see lesson 11)
Generative multilingualClaude, GPT-4, Aya-23, mT5-XXL
Low-resource language NLPXLM-V or a domain-specific fine-tune on related high-resource language

Always budget for fine-tuning in the target language if performance matters. Zero-shot is a starting point, not a final answer.

The tokenization tax (what goes wrong for low-resource languages)

Multilingual models share one tokenizer across all their languages. That vocabulary is trained on a corpus dominated by English, French, Spanish, Chinese, German. For any language outside the dominant set, three taxes compound silently:

  • Fertility tax. Low-resource language text tokenizes into far more tokens per word than English. A Hindi sentence can need 3-5x the tokens of an equivalent English sentence. That 3-5x eats your context window, training efficiency, and latency.
  • Variant recovery tax. Every typo, diacritic variant, Unicode normalization mismatch, or case variation becomes a cold-start unrelated sequence in embedding space. The model cannot learn orthographic correspondences that a native speaker takes as obvious.
  • Capacity spillover tax. Taxes 1 and 2 consume context positions, layer depth, and embedding dimensions. What remains for actual reasoning is systematically smaller than what a high-resource language gets from the same model.

The practical symptom: your model trains normally on Hindi, the loss curve looks right, eval perplexity looks reasonable, and production outputs are subtly wrong. Morphology collapses mid-sentence. Rare inflections stay unrecoverable. You cannot data-scale your way out of a broken tokenizer.

Mitigations: pick a tokenizer with good coverage for your target language (XLM-V's 1M-token vocabulary is a direct fix); verify tokenization fertility on held-out target text before training; use byte-level fallback (SentencePiece byte_fallback=True, GPT-2-style byte-level BPE) for truly long-tail scripts so nothing is ever OOV.

Check: Use It0/10
1. What is the 'fertility tax' for low-resource languages?Define
2. What is the 'variant recovery tax' described in the tokenization tax section?Define
3. What is the 'capacity spillover tax' in the tokenization tax section?Define
4. A Hindi fine-tune shows a normal loss curve and reasonable eval perplexity, yet production outputs have broken morphology. Why did the usual metrics miss it?Explain
5. Why can't you data-scale your way out of a broken tokenizer for a low-resource language?Explain
6. Which mitigation does the lesson recommend when the shared tokenizer covers a target language poorly and splits its words into far too many tokens?Explain
7. An English sentence tokenizes to 30 tokens. Using the lesson's range for a Hindi sentence of equivalent meaning, about how many tokens should you budget?Apply
8. You have no labeled data in any of your target languages and need text classification across about 100 languages with fixed candidate labels. Which choice from the lesson's stack fits?Apply
9. A fine-tuned Hindi classifier works on clean text, but the same sentence with a missing diacritic or a different Unicode normalization gets a completely different prediction. Which tokenization tax explains this?Analyze
10. You must support Amharic, a script with low tokenization coverage, and your first fine-tune on a standard multilingual model looks healthy in training. What should you do before trusting it?Design

Ship It

Save as outputs/skill-multilingual-picker.md:

markdown
---
name: multilingual-picker
description: Pick source language, target model, and evaluation plan for a multilingual NLP task.
version: 1.0.0
phase: 5
lesson: 18
tags: [nlp, multilingual, cross-lingual]
---
 
Given requirements (target languages, task type, available labeled data per language), output:
 
1. Source language for fine-tuning. Default English; check LANGRANK or qWALS if target language has a typologically close high-resource language.
2. Base model. XLM-R (classification), mT5 (generation), NLLB (translation), Aya-23 (generative LLM).
3. Few-shot budget. Start with 100-500 target-language examples if available. Zero-shot only if labeling is infeasible.
4. Evaluation plan. Per-language accuracy (not aggregate), cross-lingual consistency, entity-level F1 on non-Latin scripts.
 
Refuse to ship a multilingual model without per-language evaluation — aggregate metrics hide long-tail failures. Flag scripts with low tokenization coverage (Amharic, Tigrinya, many African languages) as needing a model with byte-fallback (SentencePiece with byte_fallback=True, or byte-level tokenizer like GPT-2).
Author's Note

The default-to-English trap is the one I see most often, and it's not really an NLP mistake, it's an org-chart mistake. Whoever writes the fine-tuning code speaks English, the labeled data was collected in English, so English becomes the source language by default and nobody ever runs the comparison against a closer relative. Run the qWALS or LANGRANK check once, even informally, before you spend engineering time on a source-language choice you never actually tested.

The tokenization tax is the other one worth losing sleep over, because it doesn't show up where you're looking. Your Hindi fine-tune will look completely healthy in training: the loss curve behaves, eval perplexity looks reasonable, and it still ships broken morphology to production. Fertility and OOV problems live somewhere your standard metrics never check. Look at tokenizer fertility on real target-language text before you trust anything built on top of it.

Exercises

  1. Easy. Run the zero-shot classification pipeline on 10 sentences per language across English, French, Hindi, and Arabic. Report accuracy on each. You should see strong French, decent Hindi, variable Arabic.
  2. Medium. Use paraphrase-multilingual-MiniLM-L12-v2 to build a cross-lingual retriever over a small mixed-language corpus. Query in English, retrieve documents in any language. Measure recall@5.
  3. Hard. Compare English-source and Hindi-source fine-tuning for a Hindi classification task. Use 500 target-language examples for few-shot fine-tuning under both regimes. Report which source produces better Hindi accuracy and by how much. This is the LANGRANK thesis in miniature.

Key Terms

TermWhat people sayWhat it actually means
Multilingual modelOne model, many languagesShared vocabulary and parameters across languages.
Cross-lingual transferTrain on one language, run on anotherFine-tune on source, evaluate on target without target-language labels.
Zero-shotNo target-language labelsTransfer without fine-tuning on the target language.
Few-shotSmall target labels100-500 target-language examples used for fine-tuning.
mBERTFirst multilingual LM104-language BERT pretrained on Wikipedia.
XLM-RStandard cross-lingual baseline100-language RoBERTa pretrained on CommonCrawl.
NLLBMeta's 200-language MTNo Language Left Behind. Includes 55 low-resource languages.

Further Reading

Code

Ships With