Sub topic 5
Zero-shot cross-lingual transfer in practice
This chapter assumes you can fine-tune a Hugging Face encoder for sequence classification and read accuracy numbers. It also assumes you know what a multilingual pretrained encoder such as XLM-R is, from the previous chapters on tokenization and pretraining. The goal is to run a zero-shot transfer experiment end to end and learn to interpret its results.
What zero-shot transfer means
In zero-shot cross-lingual transfer you fine-tune a multilingual model on labeled data in one language, the source language. You then evaluate it, with no further training, on other languages, the target languages. The model never sees a labeled target-language example.
This works because pretraining already put sentences from different languages into overlapping regions of the same representation space. The fine-tuned classification head reads that space, not any particular language. If the representation of a German sentence lands near the representation of its English counterpart, the head classifies both in the same way.
"Zero-shot" here refers to the task labels in the target language. The model has seen plenty of target-language text during pretraining, so it is not language-naive. If a language was absent from pretraining, transfer to it is a much harder problem, covered in the chapter on what makes transfer work or fail.
The task: XNLI
XNLI is a natural language inference benchmark. Each example has a premise and a hypothesis, and the label says whether the premise entails the hypothesis, contradicts it, or is neutral toward it. The label set has three classes, so random guessing gives about 33% accuracy.
XNLI suits transfer experiments for two reasons. Its training data is English only (a machine-translated version exists, which we use in a later chapter). Its dev and test sets are professionally translated into 15 languages, so every language is tested on the same underlying examples. Differences between languages therefore reflect the model, not the data.
Running the experiment
The script below fine-tunes xlm-roberta-base on English XNLI and evaluates on English, German and Swahili. Training on the full set of roughly 392,000 examples is slow without a GPU. For a quick CPU run, set SUBSET to a few thousand examples. The numbers will be lower, but the pattern across languages is still visible.
from datasets import load_dataset
from transformers import (
AutoModelForSequenceClassification,
AutoTokenizer,
Trainer,
TrainingArguments,
)
name = "xlm-roberta-base"
SUBSET = None # for example 5000 for a quick CPU run
tok = AutoTokenizer.from_pretrained(name)
model = AutoModelForSequenceClassification.from_pretrained(name, num_labels=3)
def encode(batch):
return tok(batch["premise"], batch["hypothesis"], truncation=True, max_length=128)
train = load_dataset("facebook/xnli", "en", split="train")
if SUBSET:
train = train.shuffle(seed=0).select(range(SUBSET))
train = train.map(encode, batched=True)
tests = {
lang: load_dataset("facebook/xnli", lang, split="test").map(encode, batched=True)
for lang in ["en", "de", "sw"]
}
def accuracy(pred):
return {"accuracy": float((pred.predictions.argmax(-1) == pred.label_ids).mean())}
args = TrainingArguments(
output_dir="xlmr-xnli-en",
per_device_train_batch_size=32,
learning_rate=2e-5,
num_train_epochs=2,
)
trainer = Trainer(
model=model,
args=args,
train_dataset=train,
processing_class=tok,
compute_metrics=accuracy,
)
trainer.train()
for lang, ds in tests.items():
print(lang, trainer.evaluate(ds)["eval_accuracy"])A few details in this script matter.
- Sentence pairs. Passing premise and hypothesis as two arguments makes the tokenizer build a pair input with the model's separator tokens. Concatenating the strings yourself would lose that structure.
- Padding. The script does not pad inside
encode. Because the tokenizer is passed toTrainer, it pads each batch dynamically to the longest sequence in that batch, which is faster than padding everything to 128. - Test sets. The German and Swahili sets are only loaded for evaluation. They never enter
trainer.train(). - Label order. XNLI uses the same label ids in every language, so the head trained on English labels applies directly.
Reading the results
With the full training set, English accuracy for XLM-R base typically lands in the mid 80s. Published results show German a few points lower and Swahili roughly ten to twenty points below English. The size of that gap is the transfer gap: the English score minus the target-language score. Your exact numbers vary with seed, epochs and learning rate.
| Language | Pretraining data (relative) | Script | Expected transfer gap |
|---|---|---|---|
| English | Very large | Latin | None (source) |
| German | Large | Latin | Small |
| Swahili | Small | Latin | Large |
Swahili uses the Latin script, so its gap is not caused by script. Much of it comes from the small amount of Swahili in the pretraining corpus and from how different Swahili is from English in structure. Later chapters separate these factors.
Practical decisions that affect results
Model selection without target data
The usual approach for model selection (picking the best checkpoint by dev accuracy) raises a problem. In a strict zero-shot setting you have no target-language labels, so you cannot select a checkpoint on target dev data. If you do, you are using target labels, and your result is no longer zero-shot.
You have two honest options.
- Select checkpoints on source-language dev data only, and report the result as zero-shot.
- Select on target dev data, and state clearly that this is an oracle setting that leaks target-language information.
Many papers use option 2 without saying so, which inflates reported numbers. Check which one a paper uses before comparing your result to it.
Hyperparameters
Zero-shot transfer is sensitive to how far fine-tuning moves the model from its pretrained state. Long training with a high learning rate on English can specialize the encoder to English and widen the gap. Common safeguards are:
- A small learning rate (2e-5 or lower) and few epochs.
- Evaluating on a held-out source-language dev set and stopping early.
- Running several seeds. Target-language accuracy can vary by one to three points between seeds even when English accuracy barely moves.
Sequence length and tokenization
The same sentence usually needs more subword pieces in a low-resource language, as you saw in the tokenization chapter. With max_length=128, truncation hits Swahili and Hindi inputs sooner than English ones. For tasks with long inputs, check how many target-language examples get truncated before blaming the model for a gap.
import numpy as np
lengths = [len(x["input_ids"]) for x in tests["sw"]]
print("share truncated:", float(np.mean([n >= 128 for n in lengths])))Common errors
- Evaluating before checking labels. If you load a target dataset with a different label mapping, accuracy looks random. Confirm that
labelids mean the same thing in every split. - Leaking target data into training. Concatenating several languages "just for validation" and then calling the result zero-shot is a common mistake. If any target example influences the weights or the checkpoint choice, it is not zero-shot.
- Treating one run as the answer. A single seed can mislead. Report a mean and a spread over at least three seeds when the differences you care about are small.
- Ignoring the English drop. After heavy fine-tuning, check that English performance is still good. A broken source result makes every transfer number meaningless.
- Reading the gap as a language ranking. Test sets are translations. Translationese (text that reads like a translation) can make some languages easier or harder than natural text in that language would be.
When zero-shot is the right choice
Zero-shot transfer is the cheapest option. It needs labeled data in one language and no translation system. It is a reasonable first baseline whenever you have a task in a language with no labels.
It is weaker than alternatives when the target language is distant from the source, poorly represented in pretraining, or when even a small number of labeled target examples is available. The chapter on translate-train, translate-test and few-shot data compares those options.
Exercise
You fine-tune XLM-R on English XNLI and get 84% on English, 77% on German and 66% on Swahili. You then pick the checkpoint with the best Swahili dev accuracy, and the Swahili test result rises to 69%. Can you still call the Swahili result zero-shot? What would you report?
Show answer
Not strictly. Choosing the checkpoint with Swahili dev labels uses target-language supervision, so the 69% is an oracle-selection number, not a zero-shot one. The strictly zero-shot result is the one from a checkpoint chosen on English dev data only (66% if that is the checkpoint you had before). Report the English-selected number as the zero-shot result, and if you also give the 69%, label it as selected with target dev data.
Exercise
A colleague says the Swahili gap in your run must come from Swahili using a different script from English. Which fact from this chapter contradicts that, and what two factors does the chapter give as likelier causes?
Show answer
Swahili uses the Latin script, the same as English, so script cannot explain the gap. The chapter points to the small amount of Swahili in the pretraining corpus and to Swahili's structural differences from English. Longer tokenized inputs and truncation at 128 pieces can also contribute.