Sub topic 6
What makes transfer work or fail
This chapter assumes you can fine-tune a transformer encoder with the Hugging Face Trainer and that you know how masked language modeling and accuracy work. It also assumes you have seen zero-shot cross-lingual transfer: you fine-tune a multilingual model on one language (the source) and test it on others (the targets) without any target-language labels.
Transfer is not uniform. The same XLM-R checkpoint can lose a few points on German and more than ten on Swahili. This chapter covers the factors that predict that gap, and how to check them for your own language pair before you rely on transfer.
The working model
Zero-shot transfer works when the model's internal representations of the source and target languages occupy similar regions of the embedding space. A classifier trained on source-language representations then sees target-language inputs as familiar. Anything that pulls the two languages apart, or leaves the target language poorly represented, widens the gap.
Five factors explain most of the variation:
- How much target-language text was in pretraining.
- How similar the source and target languages are (family, word order, morphology).
- Whether the languages share a script, and how well the tokenizer covers the target script.
- How much vocabulary and model capacity each language gets.
- How hard the task is, and whether it depends on surface form or on meaning.
Pretraining data size
The target language must be well represented in the pretraining corpus. A language that appears in a few megabytes of text gets few gradient updates and weak representations, so there is little to align. XLM-R's CC-100 corpus has hundreds of gigabytes for English and Russian, but only tens of megabytes for languages such as Swahili or Urdu in its smaller portions. mBERT's Wikipedia-based corpus varies in the same way.
Pretraining size usually matters more than any other single factor. Studies of mBERT transfer found that, for a given source language, target-language pretraining size predicted performance better than typological similarity alone. Treat it as the first thing to check.
Two practical consequences follow:
- A language missing from pretraining entirely often transfers badly, even if it is closely related to a covered language. Check the model card's language list before anything else.
- If the target language is low-resource, continued pretraining on target-language text (or adapters, covered in a later chapter) can help more than collecting labels.
Language similarity
Languages that share genealogy, word order and morphology transfer better. Syntactic features matter in particular. Transfer between English and German, both Germanic with similar clause structure, is strong. Transfer to Japanese or Turkish, which put verbs at the end of the clause and use agglutinative morphology, is weaker on syntax-heavy tasks such as dependency parsing.
Some typological features worth checking:
| Feature | Example contrast | Typical effect |
|---|---|---|
| Word order | English SVO vs. Japanese SOV | Hurts parsing and tagging more than classification |
| Morphology | English (little) vs. Finnish (rich) | One word form maps to many tokens or many rare forms |
| Script | Latin vs. Devanagari | Fewer shared subwords, less lexical anchoring |
| Resource level | English vs. Yoruba | Weaker target representations regardless of typology |
You can look up typological features in the WALS database or compute distances with the lang2vec package. These distances are weak predictors alone. A distant language with plenty of pretraining data often beats a close language with very little.
Script and tokenizer coverage
A shared subword vocabulary gives the model anchor points: strings such as numbers, names, and loanwords that appear in several languages and appear with similar meaning. Languages sharing a script share more of these. Hindi and Urdu are nearly the same spoken language but use different scripts, so their tokenizations share almost nothing, and transfer between them is weaker than the linguistic similarity would suggest.
Script also affects how finely the tokenizer splits text. A language the vocabulary covers poorly gets split into many short pieces, which are hard for the model to compose into meaning. You can measure this directly with a token-per-word ratio.
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained("xlm-roberta-base")
samples = {
"en": "The weather is nice today.",
"de": "Das Wetter ist heute schön.",
"hi": "आज मौसम अच्छा है।",
"sw": "Hali ya hewa ni nzuri leo.",
}
for lang, text in samples.items():
words = text.split()
pieces = tok.tokenize(text)
ratio = len(pieces) / len(words)
print(f"{lang}: {len(words)} words, {len(pieces)} pieces, {ratio:.2f} pieces/word")A ratio near 1 to 1.5 usually means the vocabulary fits the language. A ratio of 3 or more suggests the language is fragmented, and you should expect weaker results. Whitespace splitting is a crude word count and does not work for Chinese, Japanese or Thai, so compare those languages by characters per piece instead.
Capacity and vocabulary per language
A fixed number of parameters and a fixed vocabulary must be shared among all languages. As the number of languages grows, each language gets a smaller share. This is the curse of multilinguality, which a later chapter covers in full. For transfer, the key point is that adding more languages helps low-resource languages up to a point, then hurts everyone. A larger model (XLM-R large rather than base) reduces this pressure and generally narrows the gap between high- and low-resource languages.
Task type
Different tasks transfer differently:
- Sentence-level classification (XNLI, sentiment) transfers well, because it relies on meaning.
- Structured prediction (named entity recognition, part-of-speech tagging) transfers reasonably for related languages.
- Syntax-heavy and generation tasks, and tasks needing fine-grained span extraction (question answering, parsing), show larger drops, especially across distant languages.
So a transfer result on one task tells you little about another. Measure the task you care about.
Common failure modes
- Unseen language. The model never saw the language, and the tokenizer falls back to bytes or
<unk>. Accuracy approaches the majority-class rate. - Script mismatch. A related language written in a different script transfers worse than its relatedness suggests. Transliterating into the source script sometimes recovers part of the gap.
- Catastrophic forgetting of alignment. Long fine-tuning on the source language can specialize the model to that language's surface features and reduce transfer. Fewer epochs or a lower learning rate often help.
- Evaluating on translated test sets. Benchmarks such as XNLI are translated from English, so they may contain artifacts that make transfer look better than it is on natively written text. Native-language test data gives a more honest number.
- Reporting one average. An average across languages hides the languages that fail. Report per-language results.
Checking transfer for your language pair
The following script gives a first estimate. It assumes you have already fine-tuned an XLM-R model on English XNLI and saved it to xlmr-xnli-en. It compares per-language accuracy to the English accuracy and prints the gap.
from datasets import load_dataset
from transformers import (
AutoModelForSequenceClassification,
AutoTokenizer,
Trainer,
TrainingArguments,
)
path = "xlmr-xnli-en"
tok = AutoTokenizer.from_pretrained(path)
model = AutoModelForSequenceClassification.from_pretrained(path)
def encode(batch):
return tok(batch["premise"], batch["hypothesis"], truncation=True, max_length=128)
def accuracy(pred):
return {"accuracy": float((pred.predictions.argmax(-1) == pred.label_ids).mean())}
trainer = Trainer(
model=model,
args=TrainingArguments(output_dir="eval-tmp", per_device_eval_batch_size=64),
processing_class=tok,
compute_metrics=accuracy,
)
scores = {}
for lang in ["en", "de", "ru", "hi", "sw"]:
ds = load_dataset("facebook/xnli", lang, split="test").map(encode, batched=True)
scores[lang] = trainer.evaluate(ds)["eval_accuracy"]
for lang, acc in scores.items():
print(f"{lang}: {acc:.3f} gap vs en: {scores['en'] - acc:+.3f}")Typical results for XLM-R base trained on English show a gap of a few points for German and Russian, and a larger gap for Hindi and Swahili. Your exact numbers depend on the checkpoint, the seed and the training length. Run several seeds before drawing conclusions from differences of one or two points.
Choosing a source language
English is the default source language because labeled data is plentiful, but it is not always the best one. Research on mBERT and XLM-R found that other source languages, such as German or Russian, sometimes transfer better to a given target. If you have labeled data in several languages and a related high-resource option exists for your target, test it. Training on several source languages at once also tends to help, because the model sees more variety in how the task is expressed.
Quick diagnostic checklist
- Is the target language in the pretraining list? If not, expect poor results.
- How large is the target-language share of pretraining data?
- What is the token-per-word ratio for the target language?
- Does the target share a script with the source?
- Is the task semantic (classification) or syntax-heavy (parsing, span extraction)?
- Is there a closer or larger source language you could fine-tune on?
If the answers are bad, move to translate-train, translate-test, or a small amount of labeled target data, which the next chapters cover.
Exercise
You fine-tune XLM-R on English sentiment data and test on two languages. Language A is Dutch, with a token-per-word ratio of 1.4. Language B is Urdu, with a ratio of 2.9, and Urdu appears in far less pretraining text than Dutch. Which language do you expect to transfer better, and give two reasons from this chapter?
Show answer
Dutch. First, it has much more pretraining data and a close genealogical relationship to English (both Germanic), so its representations are stronger and closer to English. Second, its low token-per-word ratio shows the shared vocabulary fits it well and the same script as English gives more shared subwords, while Urdu's fragmented tokenization and different script give the model less to anchor on.
Exercise
A colleague reports "average accuracy across 15 languages is 74%, so transfer works." What is wrong with relying on this number, and what should be reported instead?
Show answer
The average can hide languages where transfer fails, because strong high-resource languages offset weak low-resource ones. Report accuracy for each language, show the gap to the source language, and use several seeds so small differences are not over-read.