Sub topic 11
Multilingual sentence embeddings and cross-lingual retrieval
This chapter assumes you know how transformer encoders produce token vectors, how cosine similarity works, and how to call Hugging Face transformers and sentence-transformers. It also assumes you have read the earlier chapters on shared subword tokenization and why representations line up across languages.
Why sentence-level embeddings need their own treatment
A multilingual encoder such as XLM-R gives one vector per token. For classification you fine-tune a head on top and the model learns what to do with those vectors. For retrieval, clustering, deduplication or semantic search you need a single fixed-size vector per sentence, and you need two sentences with the same meaning to land close together, whatever language they are in.
A raw pretrained encoder does not do this well, even though its token representations are partly aligned across languages. Two reasons explain it:
- Masked language modeling never trains the model to make sentence vectors comparable. Mean-pooled XLM-R vectors from different sentences tend to occupy a narrow cone of the space, so cosine similarities are all high and poorly separated.
- Alignment in a pretrained model is partial. Translations are closer than unrelated sentences, but language identity is often still the strongest signal. Nearest neighbors of an English sentence are frequently other English sentences, even when an exact French translation exists.
A multilingual sentence embedding model fixes both problems with an additional training stage built around sentence pairs.
How multilingual sentence encoders are trained
Most practical models follow one of three recipes.
Contrastive training on translation pairs
Take a batch of translation pairs, such as an English sentence and its German translation. Encode both sides. Treat each true pair as a positive and every other sentence in the batch as a negative. The loss pushes true pairs together and everything else apart. Models such as LaBSE and many of the multilingual E5 and BGE-M3 family use variants of this. Parallel data comes from sources such as OPUS, Tatoeba and mined web bitext.
Multilingual knowledge distillation
This recipe, used for paraphrase-multilingual-* models in sentence-transformers, starts from a strong English teacher model. The student is a multilingual encoder. For each translation pair (s, t), the student must make its embedding of s and its embedding of t both match the teacher's embedding of s. The English space is thereby copied into many languages.
The advantage is that you need only parallel sentences and a good English model. The student is aligned by construction, so a sentence and its translation map to nearly the same point.
Large-scale weakly supervised contrastive pretraining
Newer retrieval models first train on huge numbers of text pairs (question and answer, title and body) in many languages, then fine-tune on labeled retrieval data. Alignment across languages emerges from the multilingual backbone and from some cross-lingual pairs in the mix.
Encoding and comparing sentences across languages
The following example encodes three sentences with a distilled multilingual model. Two are translations of each other, and one is unrelated.
from sentence_transformers import SentenceTransformer, util
model = SentenceTransformer("paraphrase-multilingual-MiniLM-L12-v2")
sentences = [
"The cat is sleeping on the sofa.",
"Le chat dort sur le canapé.",
"The stock market fell sharply today.",
]
emb = model.encode(sentences, convert_to_tensor=True)
print("en vs fr, same meaning:", util.cos_sim(emb[0], emb[1]).item())
print("en vs en, different meaning:", util.cos_sim(emb[0], emb[2]).item())The first similarity is typically high, often above 0.8. The second is much lower, often below 0.2. The point of the comparison is that a cross-language pair with the same meaning scores higher than a same-language pair with different meaning. This is the property that makes the vector space language-agnostic. Exact values vary by model version, so treat any number as an approximation.
Pooling and normalization
A sentence encoder turns token vectors into one vector with a pooling step. The common choices are:
| Pooling | How it works | Typical use |
|---|---|---|
| Mean | Average all token vectors, ignoring padding | Most `sentence-transformers` models |
| CLS | Use the first token's vector | LaBSE (with a dense layer), BERT-style models |
| Max | Element-wise maximum over tokens | Rare |
Always use the pooling the model was trained with. The SentenceTransformer class reads this from the model's configuration, which is why it is safer than hand-written pooling over AutoModel outputs. Many models also expect L2-normalized vectors. After normalization, cosine similarity equals the dot product, which lets vector indexes use fast inner-product search.
Instruction prefixes
Some retrieval models, notably the multilingual E5 family, require a prefix on each input such as query: or passage: . Omitting the prefix quietly lowers quality without raising an error. Read the model card before use.
Cross-lingual retrieval
Cross-lingual retrieval means the query and the documents are in different languages. A user types a question in Spanish, and the system returns relevant passages written in English, Japanese or any other indexed language. With a shared embedding space the pipeline needs no translation step:
- Encode every document once and store the vectors in an index.
- Encode the query with the same model.
- Return the documents with the highest cosine similarity.
Here is a small, runnable version using exact search.
from sentence_transformers import SentenceTransformer, util
model = SentenceTransformer("paraphrase-multilingual-MiniLM-L12-v2")
corpus = [
"Der Eiffelturm steht in Paris.",
"Mount Fuji is the highest mountain in Japan.",
"El banco central subió los tipos de interés.",
"Python is a popular programming language.",
]
corpus_emb = model.encode(corpus, convert_to_tensor=True, normalize_embeddings=True)
queries = [
"Where is the Eiffel Tower?",
"¿Cuál es la montaña más alta de Japón?",
]
query_emb = model.encode(queries, convert_to_tensor=True, normalize_embeddings=True)
hits = util.semantic_search(query_emb, corpus_emb, top_k=2)
for q, h in zip(queries, hits):
print(q)
for item in h:
print(f" {item['score']:.3f} {corpus[item['corpus_id']]}")For corpora beyond a few hundred thousand vectors, replace exact search with an approximate nearest neighbor index such as FAISS (HNSW or IVF) or a vector database. Approximate indexes trade a small amount of recall for large speedups.
Common errors and failure modes
Language bias in rankings
Even good models favor documents in the query's language. An English query can rank a mediocre English passage above a better German one. This is called language bias. Ways to reduce it:
- Evaluate with cross-lingual queries, not only monolingual ones.
- Retrieve separately per language and merge with score normalization.
- Use a cross-encoder reranker that is itself multilingual.
- Choose a model trained with explicit cross-lingual retrieval data, such as BGE-M3 or multilingual E5.
Quality varies across languages
Alignment is best for languages with abundant parallel data. For low-resource languages, similarity scores for true translations are lower and variable. Scores are also not calibrated across language pairs. A cosine similarity of 0.7 might mean a near-perfect match for French and English, but only a rough match for Yoruba and English. Do not use one global threshold for all language pairs without checking it per pair.
Tokenization cost and truncation
The tokenizer chapter showed that some scripts produce many more tokens per sentence. Sentence encoders have a maximum sequence length, often 128 or 512 tokens. A passage in Burmese or Hindi can be truncated earlier, in terms of meaning, than the same passage in English. Check the token count per language and chunk documents by tokens, not characters.
Mixed-up semantics
Translation-trained models capture meaning similarity well but can ignore details such as negation, numbers and named entities. "The meeting is on Monday" and "The meeting is not on Monday" may score very high. If your task depends on such distinctions, add a reranker or a downstream check.
Mean-pooled raw encoders
Using xlm-roberta-base directly with mean pooling for retrieval is a common mistake. Without sentence-level training, results are poor. Use a model that was trained as a sentence encoder.
Choosing a model
| Need | Reasonable choice | Notes |
|---|---|---|
| Quick prototype, ~50 languages | `paraphrase-multilingual-MiniLM-L12-v2` | Small, fast, short max length |
| Bitext mining, sentence matching | LaBSE | Strong on translation pair detection, weaker on topical retrieval |
| Retrieval over long, multilingual documents | BGE-M3 or multilingual E5 | Longer context, trained for retrieval |
| Strict latency budget | Distilled small models | Measure recall on your own data |
Decide by measuring on a sample of your own queries and documents. Benchmarks such as MTEB (which has multilingual tasks) and MIRACL or Mr. TyDi for cross-lingual and multilingual retrieval give useful starting points. Report recall@k or nDCG@10 per language and per language pair, not one average, for the reasons covered in the evaluation chapter.
Evaluating alignment directly
Two quick checks are worth running before you build on an embedding model.
- Translation retrieval (Tatoeba-style). Take N sentences and their translations. For each source sentence, check whether its translation is the nearest neighbor among all translations. The fraction correct is the retrieval accuracy for that language pair.
- Similarity gap. Compare the mean cosine similarity of true translation pairs to that of random pairs. A small gap signals weak alignment.
import torch
from sentence_transformers import SentenceTransformer, util
model = SentenceTransformer("paraphrase-multilingual-MiniLM-L12-v2")
en = [
"I like coffee.",
"The train is late.",
"She reads a book.",
"We are going home.",
]
de = [
"Ich mag Kaffee.",
"Der Zug hat Verspätung.",
"Sie liest ein Buch.",
"Wir gehen nach Hause.",
]
a = model.encode(en, convert_to_tensor=True, normalize_embeddings=True)
b = model.encode(de, convert_to_tensor=True, normalize_embeddings=True)
sim = util.cos_sim(a, b)
pred = sim.argmax(dim=1)
acc = (pred == torch.arange(len(en))).float().mean().item()
print("translation retrieval accuracy:", acc)Four sentences make a toy test. Use at least a thousand pairs per language pair for real numbers.
Summary of the working model
- Pretrained multilingual encoders are only partly aligned at sentence level. A second training stage on translation pairs or retrieval pairs produces a sentence embedding space where meaning dominates over language.
- Use the model's own pooling, normalization and prefixes.
- Cross-lingual retrieval is encode, index, search. No translation is needed, but language bias, uneven quality across languages, token-length truncation and uncalibrated scores need explicit checks.
- Evaluate per language pair on your own data.
Exercise
You build a cross-lingual search system with a distilled multilingual encoder. English queries retrieve English documents well, but relevant Thai documents rarely appear in the top 10, even though a manual check shows that the encoder scores the Thai passages as fairly similar to the query. Name two likely causes and one fix for each.
Show answer
Cause 1: language bias. English documents receive higher similarity than Thai documents with equal relevance, so they crowd the top 10. Fix: retrieve top results per language and merge with per-language score normalization, or add a multilingual cross-encoder reranker over a larger candidate list. Cause 2: truncation from tokenization cost. Thai text produces many more tokens, so the encoder's maximum length cuts off part of each Thai passage and its vector represents only the start. Fix: chunk Thai documents by token count (for example 128 tokens per chunk), index each chunk, and aggregate scores per document. A model with a longer context, such as BGE-M3, also helps.
Exercise
Why can a raw xlm-roberta-base model with mean pooling give poor cross-lingual retrieval, and what is the standard remedy?
Show answer
Masked language modeling does not train sentence vectors to be comparable, and its cross-lingual alignment is partial. Vectors cluster by language and sit in a narrow cone, so similarities are poorly separated. The remedy is to use a model trained as a sentence encoder, with contrastive training on translation or retrieval pairs, or distillation from an English teacher.