🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Cross-Lingual Transfer: Training Once, Serving Many Languages

Natural Language ProcessingCross-Lingual Transfer: Training Once, Serving Many LanguagesđŸŸĸ Free Lesson

Cross-Lingual Transfer: Training Once, Serving Many Languages

Module: Natural Language Processing | Difficulty: Advanced

What You'll Learn

  • 1Quantify the zero-shot transfer gap between English and target languages
  • 2Allocate a shared SentencePiece vocabulary fairly across 100 languages
  • 3Build and evaluate a dictionary-augmented cross-lingual classifier
  • 4Decide when continued target-language pre-training pays off

Cross-lingual transfer trains a single model on a high-resource language, usually English, and applies it to languages with little or no labeled data. The enabling design choices are a shared subword vocabulary that lets every language token map into a common embedding table, and a pre-training objective that aligns representations across languages without parallel sentences. This lesson measures the transfer gap, derives how to split a vocabulary budget across languages, and implements zero-shot evaluation in Python.

The Transfer Gap

Multilingual BERT covers 104 languages in 110M or 340M parameters, while XLM-RoBERTa (Conneau et al., 2020) is pre-trained with a shared SentencePiece vocabulary of 250,000 pieces on 2.5 terabytes of filtered CommonCrawl covering 100 languages. On XNLI, which provides 7,500 test examples in each of 15 languages, English reaches about 88.6 accuracy under XLM-R large and the zero-shot average across the other languages sits near 79.4.

ModelLanguagesParametersXNLI EnglishZero-shot average
mBERT base104110M81.465.4
XLM-R base100270M84.174.1
XLM-R large100550M88.679.4

Sharing a fixed vocabulary

XLM-R splits 250,000 pieces across 100 languages, which averages only 2,500 pieces per language, yet the actual allocation follows corpus frequency. If a language receives pieces out of budget in proportion to its token share , then its coverage depends on how quickly its vocabulary need saturates.

above 0 up-weights rare languages; setting would give every language an equal slice, which starves large languages, while matches the corpus distribution and pushes low-resource languages to near-zero coverage.

Alignment Objectives

Masked language modelling alone aligns languages only weakly, because each language occupies its own region of the embedding space. Translation language modelling (TLM) concatenates a parallel pair and masks spans across both sides, so a masked token in one language can be predicted from its translation in the other.

A second lever is continued pre-training: run more masked language modelling on raw target-language text before fine-tuning. The gain is largest for languages whose script or morphology is far from English, and it costs only a few GPU hours per language.

Worked Code

python
import math
from collections import defaultdict

DICTIONARY = {"the": "el", "film": "pelicula", "was": "fue", "boring": "aburrida",
              "great": "gran", "acting": "actuacion", "story": "historia",
              "i": "yo", "loved": "disfrute", "excellent": "excelente",
              "terrible": "terrible", "slow": "lenta", "movie": "pelicula"}

ENGLISH = [("the film was boring", 0), ("great acting and story", 1),
           ("i loved the movie", 1), ("the story was slow", 0),
           ("excellent acting", 1), ("terrible film", 0)]
TARGET = [("el pelicula fue aburrida", 0), ("gran actuacion e historia", 1),
          ("yo disfrute la pelicula", 1), ("la historia fue lenta", 0)]


def translate(text):
    return " ".join(DICTIONARY.get(w, w) for w in text.split())


def train(rows):
    counts = defaultdict(lambda: defaultdict(int))
    prior = defaultdict(int)
    for text, label in rows:
        prior[label] += 1
        for w in translate(text).split():
            counts[label][w] += 1
    total = sum(prior.values())
    return counts, prior, total


def predict(model, text, k=0.5):
    counts, prior, total = model
    labels = sorted(prior)
    vocab = 1 + len({w for c in counts.values() for w in c})
    best, best_lp = labels[0], float("-inf")
    for label in labels:
        lp = math.log((prior[label] + k) / (total + k * len(labels)))
        for w in translate(text).split():
            lp += math.log((counts[label][w] + k) / (sum(counts[label].values()) + k * vocab))
        if lp > best_lp:
            best_lp, best = lp, label
    return best


model = train(ENGLISH)
hits = sum(1 for t, g in TARGET if predict(model, t) == g)
per_class = {}
for label in (0, 1):
    tp = sum(1 for t, g in TARGET if g == label and predict(model, t) == label)
    n = sum(1 for _, g in TARGET if g == label)
    per_class[label] = tp / max(1, n)
print("zero-shot accuracy:", round(hits / len(TARGET), 3))
print("per-language class recall:", per_class)
python
import math
import random


def bootstrap_gap(source_scores, target_scores, iters=5000, seed=3):
    """95 percent CI for the transfer gap via paired resampling."""
    random.seed(seed)
    n = min(len(source_scores), len(target_scores))
    observed = sum(source_scores) / n - sum(target_scores) / n
    draws = []
    for _ in range(iters):
        idx = [random.randrange(n) for _ in range(n)]
        draws.append(sum(source_scores[i] for i in idx) / n
                     - sum(target_scores[i] for i in idx) / n)
    draws.sort()
    lo, hi = draws[int(0.025 * iters)], draws[int(0.975 * iters)]
    return observed, lo, hi


EN = [88.6, 86.9, 87.4, 88.1, 86.3, 87.9]
AR = [76.5, 75.1, 77.8, 74.9, 75.6, 76.2]
ZH = [82.1, 81.4, 80.9, 82.6, 81.0, 81.8]
SW = [71.2, 70.4, 72.5, 69.8, 70.9, 71.5]

for name, scores in (("Chinese", ZH), ("Arabic", AR), ("Swahili", SW)):
    gap, lo, hi = bootstrap_gap(EN, scores)
    print(f"{name:8s} gap {gap:5.2f}  95% CI [{lo:.2f}, {hi:.2f}]")

macro = sum(sum(x) / len(x) for x in (EN, AR, ZH, SW)) / 4
english = sum(EN) / len(EN)
print(f"macro over 4 languages {macro:.2f}  transfer gap {english - macro:.2f}")

Real-World Applications

  • XLM-R is pre-trained on 2.5 terabytes of CommonCrawl text over 100 languages with a 250,000-piece SentencePiece vocabulary, then fine-tuned once on English and evaluated zero-shot in 15 XNLI languages.
  • XNLI supplies 7,500 test examples per language, so a 15-language evaluation is 112,500 items and a single average is stable to within a point.
  • Per-language adapters at about 3.15M parameters, 0.57 percent of the backbone, let a platform ship 40 new languages for the cost of one extra model each.
  • AmericasNLP and AmericasNLP-2021 demonstrate that continued target-language masked modelling closes the gap for indigenous languages with fewer than one million documents.

💡Report the spread, not only the mean

A 79.4 zero-shot average hides Swahili near 71 and Chinese near 82; publishing min, max, and per-language scores is what lets a reviewer judge whether the model is safe to deploy in a specific market.

Common Mistakes

Averaging languages with unweighted means

Fix: Report macro averages with per-language rows, and note that a language with 7,500 test items contributes exactly as much as another with 100

Ignoring vocabulary coverage before blaming the model

Fix: Compute token-level coverage of the shared 250k pieces; below about 97 percent, degradation is a tokenizer problem, not a transfer problem

Fine-tuning on English and evaluating with a translated dev set

Fix: Keep the dev split in the target language or use a held-out English dev set, otherwise the tuning step leaks target-language supervision

Best Practices

  • Use alpha 0.5 when allocating shared vocabulary pieces, so low-resource languages keep usable coverage
  • Add TLM or continued target-language MLM before declaring a language unsupported
  • Publish macro, min, and max accuracy together with the source-language score

Key Takeaways

  • XLM-R reaches about 88.6 on English XNLI against a zero-shot average near 79.4, a gap of 9.2 points
  • 250,000 shared pieces across 100 languages averages 2,500 pieces per language and needs alpha-weighted allocation
  • Language adapters cost about 3.15M parameters, 0.57 percent of a 550M backbone
  • Transfer gaps must be reported with per-language spread, since a single mean hides languages 17 points behind English

Frequently Asked Questions

Why does a shared subword vocabulary make transfer work?

Because every language's tokens are cut into pieces drawn from one table, so a Spanish inference verb still lands on embedding rows updated during English training. Without that sharing, each language would need its own output layer and zero-shot transfer would be impossible.

How many languages can one model serve?

XLM-R covers 100 and mBERT 104, but coverage is not quality: languages with very little pre-training text degrade sharply. Adapter stacks add roughly 0.57 percent parameters per language, so the practical limit is data rather than memory.

Is zero-shot transfer enough for production?

For classification tasks with close languages, often yes. For languages with limited coverage or unique script, continued target-language pre-training usually buys 3 to 8 points, which is usually worth the GPU hours.

Interview Questions

Q1: How do you measure cross-lingual transfer quality?

Train on English, evaluate zero-shot in each target language, then report macro average plus min, max, and per-language scores; a 79.4 average spans roughly 71 to 88

Q2: What does translation language modelling add?

It masks tokens across both sides of a parallel pair so a masked English span can be predicted from its translation, explicitly pulling aligned meanings together

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-07

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert NLP Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement