Sub topic 4
Why representations line up across languages
This chapter explains why a model pretrained on many languages ends up placing similar meanings near each other, even when no one told it which sentences are translations. It assumes you know masked language modeling, the structure of a transformer encoder, and the basics of tokenization from the earlier chapters. You should also be comfortable extracting hidden states with transformers.
The puzzle
mBERT was trained with a masked language modeling (MLM) objective on Wikipedia text from about 100 languages. It never saw a translation pair. Yet researchers found that a classifier fine-tuned on English labels often worked in other languages. For that to happen, a German sentence about a cat has to land in roughly the same region of representation space as its English counterpart. The classifier head only learned where "positive" or "entailment" lives in that space.
Nothing in the MLM loss asks for this. Each masked-token prediction is made inside one language. Alignment appears as a side effect of how the model is built and trained. Several mechanisms contribute, and researchers still disagree about how much each matters.
Mechanisms that cause alignment
Shared parameters under capacity pressure
Every language passes through the same attention and feed-forward weights. The model has a fixed budget, so it is cheaper to reuse a circuit that tracks "subject, verb, object" or "this token is a place name" than to learn one copy per language. Where languages have similar structure, reuse lowers the loss. The shared weights then force similar inputs to produce similar hidden states.
Anchor tokens in the shared vocabulary
A shared subword vocabulary (covered in the tokenization chapter) means some pieces appear in several languages. Digits, punctuation, Latin-script names, URLs, loanwords, and code snippets are examples. Each such piece has one embedding, whose training signal comes from every language containing it. These anchors tie the languages together at the input.
Anchors are not the full explanation, though. Studies that trained models on languages with no shared vocabulary, or with scripts deliberately remapped so that no tokens overlap, still found considerable transfer. Overlap helps, but the model can also align languages through structure alone.
Similar co-occurrence structure
Words with similar meanings tend to occur in similar contexts in every language. "Dog" appears near words for animals, walking, and food, and so does its translation. A model that learns meaning from context therefore learns geometrically similar neighborhoods in each language. Earlier work on static word embeddings showed that separately trained embedding spaces for two languages are often related by a roughly linear rotation. Multilingual pretraining plausibly exploits the same regularity inside one network.
Code-switching and parallel-ish text
Web text includes quoted foreign phrases, bilingual glossaries, and translated documents. These give weak, accidental cross-lingual signal. Models like XLM also add explicit supervision, described below.
Explicit alignment objectives
Translation language modeling (TLM) from the XLM paper concatenates a sentence with its translation and masks tokens in both. To predict a masked English word, the model can look at the German sentence. This directly teaches alignment. XLM-R drops TLM and relies on MLM over much more data (CommonCrawl), and it still transfers well. That is evidence that implicit mechanisms are enough when data and capacity are large.
Where in the network alignment happens
Alignment is not uniform across layers. Probing studies on mBERT and XLM-R report a consistent pattern.
| Layer region | What it tends to encode | Cross-lingual alignment |
|---|---|---|
| Embedding and lowest layers | Token identity, script, surface form | Weak, except for anchor tokens |
| Middle layers | Syntax and sentence-level meaning | Strongest |
| Top layers | Features specialized for predicting masked tokens in a specific language | Weaker again |
The top layers have to output a distribution over a vocabulary that is mostly language-specific, so they re-separate languages. This is why sentence-retrieval and transfer probes often work best with hidden states from the middle of the network, not the last layer. It also affects fine-tuning. If you freeze lower layers, you keep alignment that task training on one language might otherwise distort.
A language-identity component remains
Alignment is partial. Hidden states usually contain a language-specific component alongside the meaning component. If you project mean-pooled representations to two dimensions, sentences often cluster by language first and by meaning second. Work on mBERT showed that subtracting each language's mean vector from its representations improves cross-lingual retrieval noticeably. That suggests the representation is approximately "meaning plus a language offset", and the offset is mostly a constant shift.
Raw hidden states are also anisotropic. Their vectors occupy a narrow cone, so cosine similarity between any two sentences is high. Absolute cosine values are therefore misleading. Compare rankings, such as whether a translation is the nearest neighbor, and not raw similarity numbers.
Measuring alignment yourself
The script below embeds five English-German translation pairs with XLM-R. For each layer it reports how often the true translation is the nearest neighbor, and the mean cosine similarity of true pairs. It uses mean pooling over non-padding tokens. Five pairs is a toy sample, so treat the output as a demonstration. For a real measurement, use hundreds or thousands of pairs, such as the Tatoeba sentences used in the XTREME benchmark.
import torch
import torch.nn.functional as F
from transformers import AutoModel, AutoTokenizer
name = "xlm-roberta-base"
tok = AutoTokenizer.from_pretrained(name)
model = AutoModel.from_pretrained(name, output_hidden_states=True).eval()
pairs = [
("The cat is sleeping.", "Die Katze schläft."),
("I am reading a book.", "Ich lese ein Buch."),
("The weather is nice today.", "Das Wetter ist heute schön."),
("We are going to the market.", "Wir gehen zum Markt."),
("The train arrives at noon.", "Der Zug kommt mittags an."),
]
def embed(sentences):
batch = tok(sentences, padding=True, return_tensors="pt")
with torch.no_grad():
out = model(**batch)
mask = batch["attention_mask"].unsqueeze(-1)
pooled = [(h * mask).sum(1) / mask.sum(1) for h in out.hidden_states]
return F.normalize(torch.stack(pooled), dim=-1) # (layers+1, n, dim)
en = embed([p[0] for p in pairs])
de = embed([p[1] for p in pairs])
sim = en @ de.transpose(1, 2) # (layers+1, n, n)
gold = torch.arange(len(pairs))
for layer in [0, 4, 8, 12]:
s = sim[layer]
top1 = (s.argmax(dim=1) == gold).float().mean().item()
print(f"layer {layer:2d} top1={top1:.2f} mean_true_cos={s.diag().mean().item():.3f}")Expect retrieval accuracy to be lowest at layer 0 and highest in the middle layers. Layer 0 mean-pools only the token embeddings, so it behaves like a bag of subwords. Expect true-pair cosine values to be high at every layer because of anisotropy.
What alignment does and does not guarantee
Alignment explains why zero-shot transfer works, but it limits transfer in predictable ways.
- It is approximate. Distant languages, such as English and Japanese or English and Swahili, align less tightly than English and German. Zero-shot accuracy drops accordingly.
- It favors high-resource languages. Languages with more pretraining text get better-organized regions of the space. Low-resource languages are crowded into poorly structured regions, which later chapters on data imbalance and the curse of multilinguality revisit.
- Meaning aligns more than form. Tasks that depend on fine surface or syntax details, such as part-of-speech tagging in a language with different word order, transfer less cleanly than coarse semantic tasks.
- Fine-tuning can erode it. Training many epochs on a single source language can drift the top layers toward source-language features. Lower learning rates, fewer epochs, or freezing lower layers can preserve alignment.
Diagnosing alignment in practice
- Collect a parallel sample for each language pair you care about, with at least several hundred sentences.
- Extract mean-pooled hidden states from several layers, not only the last.
- Compute nearest-neighbor retrieval accuracy in both directions.
- Repeat after subtracting each language's mean vector. A large gain means a language offset is hurting you.
- Choose the layer with the best retrieval. Use it for feature-based pipelines, or unfreeze from there when fine-tuning.
Exercise
A colleague extracts last-layer mean-pooled XLM-R vectors for English and Hindi sentences and finds that every English-Hindi cosine similarity is above 0.9, even for unrelated sentences. They conclude the model aligns the two languages almost perfectly. What is wrong with the conclusion, and what two changes would give a more reliable measurement?
Show answer
High cosine for unrelated pairs reflects anisotropy and a shared language offset, not alignment. Alignment means a translation is closer than non-translations. Two changes: (1) measure nearest-neighbor retrieval accuracy on parallel sentences instead of raw cosine, and (2) use a middle layer rather than the last, and optionally subtract each language's mean vector before comparing.