Multilingual NLP: sharing a model does not make languages interchangeable
多语言 NLP
Align two invented word spaces, expose an unidentifiable mapping, and examine language sampling and per-language evaluation.
multilingual-nlpA common coordinate system needs evidence
Imagine two invented dictionaries whose entries are points on a plane. Both arrange related entries into similar shapes, but one coordinate system is rotated. Knowing a few translation pairs could let us align them and look up the remaining pairs. If the geometries are distorted differently, one rotation will not be enough. If the known pairs constrain only one direction, several mappings may fit them equally well.
Multilingual NLP builds methods that process or share information across languages. Sharing can occur through dictionaries, aligned vector spaces, a common tokenizer, model parameters or training objectives. Cross-lingual transfer asks whether information learned in one language helps a task in another. The presence of multiple languages in training is not itself evidence that transfer succeeded for each one.
State the supervision regime carefully. A task can use parallel sentences, bilingual dictionaries, monolingual text or target-language task labels in different combinations. “Zero-shot” target-task evaluation usually concerns the absence of target-task training labels under a stated setup; it does not automatically imply that no target-language text or bilingual resource was used. Our example uses an explicit seed dictionary and holds out other translation labels.
Artetxe and colleagues study constrained mappings between word spaces. XLM-R studies shared multilingual contextual representations and discusses the tradeoff between positive transfer and limited model capacity. They offer two different ways to share information, not interchangeable implementations of one algorithm. Bilingual mappings Multilingual representation learning
What an orthogonal mapping can preserve
Take k seed pairs, each represented by d-dimensional row vectors. Normalize each nonzero input vector by its L2 length. Put aligned source and target rows in matrices X and Y. An orthogonal alignment solves:
The Frobenius norm sums squared coordinate errors over the seed pairs. Orthogonality restricts the map to transformations that preserve Euclidean geometry, including reflections. It prevents arbitrary stretching from fitting the dictionary while changing monolingual relationships. The paper develops this constraint alongside length normalization and optional mean centering; our program implements normalization and the orthogonal map, not the centering variant. Sections 2–2.3
Expand the squared error and use the orthogonal constraint:
The first two terms are fixed. Maximizing the trace is the orthogonal Procrustes problem. If X-transpose Y has singular value decomposition U Sigma V-transpose, one optimum and its objective value are:
To see why, set R=VᵀWᵀU. It is orthogonal, so each diagonal entry is at most 1. The trace is the sum of σ-j times R-jj; since singular values are nonnegative, it is at most the sum of σ-j. Choosing W=UVᵀ makes R=I and attains that bound.
Matrix orientation matters. The cited paper decomposes the transposed cross-product and therefore writes the factors in the opposite order. Mixing those conventions would map in the wrong direction. Our tests recover a known row-vector rotation and compare the objective with an independent angle search over rotations and reflections. Orthogonal solution, §2.1
For any source row vectors x and z, an orthogonal square W preserves their inner product:
With unit vectors, the mapped source–target dot product is cosine similarity. A nearest-neighbor decoder selects the target row with the largest value. It is a ranking rule, not a calibrated translation probability; its result depends on which target words are available as candidates.
A perfect seed fit need not identify the map. With only [1,0] mapping to [1,0], both the identity and diag(1,−1) satisfy the seed exactly. They send the unseen direction [0,1] to opposite points. In this orthogonal problem without an additional determinant restriction, a full-rank cross-product gives a unique optimum; the program marks rank-deficient cases as non-unique instead of treating one SVD output as evidence of identification.
This is a limitation of the available constraints, separate from whether two real language spaces satisfy an orthogonal model at all. Polysemy, different vocabularies, corpus domains and unequal geometry can make that model inadequate. The toy example constructs matching geometry deliberately; it cannot establish that languages are naturally interchangeable.
Keep the seed dictionary separate from the test labels
The complete original program uses Python 3.12 and NumPy 1.26.4. It creates six paired points related by a known orthogonal transformation. Seed indices are 0, 2 and 4; held-out translation labels are 1, 3 and 5. All target vectors remain available for retrieval. This is a vocabulary-available evaluation, not an unseen-target-data claim.
"""Original bilingual alignment and multilingual sampling diagnostics.
Inputs are invented vector spaces and explicit seed pairs, not trained language
embeddings. Target vocabulary is available; held-out translation labels are not.
"""
import json
import numpy as np
def vectors(value):
x=np.asarray(value,float)
if x.ndim!=2 or not 1<=x.shape[0]<=64 or not 1<=x.shape[1]<=8 or not np.isfinite(x).all() or (np.abs(x)>1e6).any():raise ValueError('Use bounded 1..64 by 1..8 vectors')
norm=np.linalg.norm(x,axis=1,keepdims=True)
if (norm==0).any():raise ValueError('A zero embedding has no cosine direction')
return x/norm
def pairs(values,source_size,target_size):
result=[tuple(p) for p in values]
if not result or len(result)>64 or any(len(p)!=2 or any(type(i) is not int for i in p) or not 0<=p[0]<source_size or not 0<=p[1]<target_size for p in result):raise ValueError('Valid nonempty integer dictionary pairs required')
if len({p[0] for p in result})!=len(result) or len({p[1] for p in result})!=len(result):raise ValueError('This teaching seed dictionary must be one-to-one')
return result
def fit(source,target,seed):
x=vectors(source);y=vectors(target)
if x.shape[1]!=y.shape[1]:raise ValueError('Both languages need the same embedding dimension')
seed=pairs(seed,len(x),len(y));a=x[[i for i,j in seed]];b=y[[j for i,j in seed]]
# Row vectors: SVD(X.T @ Y)=U S V.T, so W=U @ V.T.
u,s,vt=np.linalg.svd(a.T@b);w=u@vt
rank=int(np.linalg.matrix_rank(a.T@b))
return dict(mapping=w,source=x,target=y,seed=seed,singular_values=s,
seed_squared_error=float(np.sum((a@w-b)**2)),rank=rank,unique_orthogonal_optimum=rank==x.shape[1])
def nearest(source,target,mapping):
x=vectors(source);y=vectors(target);w=np.asarray(mapping,float)
if x.shape[1]!=y.shape[1] or w.shape!=(x.shape[1],x.shape[1]) or not np.isfinite(w).all():raise ValueError('Mapping dimensions or values invalid')
if not np.allclose(w.T@w,np.eye(len(w)),rtol=0,atol=1e-10):raise ValueError('This evaluator expects an orthogonal mapping')
scores=(x@w)@y.T
return dict(indices=np.argmax(scores,axis=1).tolist(),scores=scores.tolist())
def evaluate(fitted,test_pairs):
test=pairs(test_pairs,len(fitted['source']),len(fitted['target']))
seed_source={i for i,j in fitted['seed']};seed_target={j for i,j in fitted['seed']}
if any(i in seed_source or j in seed_target for i,j in test):raise ValueError('Hold out both sides of these one-to-one translation labels')
predicted=nearest(fitted['source'],fitted['target'],fitted['mapping'])['indices']
return dict(accuracy=sum(predicted[i]==j for i,j in test)/len(test),pairs=len(test),
predictions=[dict(source=i,target=j,predicted=predicted[i]) for i,j in test])
def language_sampling(counts,alpha):
n=np.asarray(counts,float)
if n.ndim!=1 or not 1<=len(n)<=32 or not np.isfinite(n).all() or (n<0).any() or (n>1e15).any() or not (n>0).any():raise ValueError('Nonnegative bounded corpus counts with some data required')
if isinstance(alpha,bool) or not np.isscalar(alpha) or not np.isfinite(alpha) or not 0<=alpha<=1:raise ValueError('Use a sampling exponent in [0,1]')
positive=n>0;logits=alpha*np.log(n[positive]);weights=np.exp(logits-logits.max());p=np.zeros_like(n);p[positive]=weights/weights.sum()
return p
def aggregate(correct,total):
c=np.asarray(correct);n=np.asarray(total)
if c.ndim!=1 or c.shape!=n.shape or not len(c) or not np.issubdtype(c.dtype,np.integer) or not np.issubdtype(n.dtype,np.integer) or (n<=0).any() or (c<0).any() or (c>n).any():raise ValueError('Integer counts with nonzero per-language denominators required')
return dict(micro=float(c.sum()/n.sum()),macro=float(np.mean(c/n)),per_language=(c/n).tolist())
def demo():
angles=np.arange(6)*np.pi/3;x=np.column_stack([np.cos(angles),np.sin(angles)])
rotation=np.array([[0.,-1.],[1.,0.]]);y=x@rotation;seed=[(0,0),(2,2),(4,4)];held=[(1,1),(3,3),(5,5)]
fitted=fit(x,y,seed);raw=nearest(x,y,np.eye(2));aligned=evaluate(fitted,held)
deficient=fit([[1,0],[0,1]],[[1,0],[0,1],[0,-1]],[(0,0)]);alternative=np.diag([1.,-1.])
distorted=fit(x,x@np.array([[2.,1.],[0.,.5]]),seed)
return dict(source=x.tolist(),target=y.tolist(),seed_pairs=seed,heldout_pairs=held,mapping=fitted['mapping'].tolist(),
seed_squared_error=fitted['seed_squared_error'],raw_heldout_accuracy=sum(raw['indices'][i]==j for i,j in held)/len(held),aligned=aligned,
nonidentifiable=dict(rank=deficient['rank'],unique=deficient['unique_orthogonal_optimum'],
first_mapping=deficient['mapping'].tolist(),alternative_mapping=alternative.tolist(),
first_predictions=nearest(deficient['source'],deficient['target'],deficient['mapping'])['indices'],
alternative_predictions=nearest(deficient['source'],deficient['target'],alternative)['indices']),
distorted_seed_squared_error=distorted['seed_squared_error'],
sampling=[dict(alpha=a,counts=[10000,100],probabilities=language_sampling([10000,100],a).tolist()) for a in [1.,.3,0.]],
aggregation=aggregate([90,1],[100,10]),
conditions='Six invented translation pairs, three seed and three held-out labels. Geometry is constructed, not evidence about real languages. Sampling and aggregate-metric examples are separate diagnostics.')
if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))
Using the original coordinates gives zero accuracy on the three held-out labels; fitting the seed map gives accuracy 1. Those numbers follow from constructed geometry. The rank-deficient example then gives two exact seed fits with different predictions for an unconstrained direction. A separate sheared target space leaves positive seed error after orthogonal fitting, exposing the model’s inability to undo arbitrary distortion.
The tests check the trace bound, the known mapping, all source inner products, seed-order invariance, zero-vector rejection and nearest-neighbor ties. They also reject test pairs whose source or target label overlaps the one-to-one seed dictionary. The one-to-one restriction is a teaching contract; real translation dictionaries can contain several acceptable translations and require a matching evaluation protocol.
For k seeds and dimension d, cross-product construction and SVD cost O(kd²+d³). Dense retrieval for n source and m target rows costs O(nmd) and stores O(nm) similarities. Vector preparation adds O((n+m)d) work. This program caps each vocabulary at 64 rows and dimension at eight. A zero vector has no cosine direction and is rejected; exact score ties select the lowest target index.
Sharing capacity also means choosing who gets training time
A shared multilingual model has a different mechanism from a fitted dictionary map. It can learn common contextual parameters from language data, but languages compete for training exposure and finite representational capacity. XLM-R explicitly studies positive transfer alongside capacity dilution and reports a language-sampling exponent of 0.3 in its setup. That observation does not establish one best mixture for every model or corpus. Model/data and capacity discussion
For a separate teaching diagnostic, define a smoothed language mixture using corpus sizes n-l:
At alpha 1, exposure is proportional to size; at alpha zero, languages with positive data are sampled uniformly. The explicit zero-data rule avoids treating zero-to-the-zero as a source of training examples. With sizes [10000,100] and alpha 0.3, the language exposure ratio is 100^0.3. Per original example, the smaller corpus is revisited 100^0.7 times as often as the larger one. More exposure does not create more independent data.
This diagnostic illustrates a declared power-law mixture; it does not reproduce the complete XLM-R training pipeline. Tokenization, sequence lengths, batches and data filtering also affect actual exposure. A shared vocabulary may segment languages unevenly, so compare budgets in declared units rather than assuming equal numbers of sequences contain equal amounts of information.
Evaluation must keep the languages visible. For language-specific correct counts c-l and nonzero test sizes m-l:
In another independent example, one language has 90/100 correct and another 1/10. Micro accuracy is 91/110, about 0.8273, while macro accuracy is 0.5. Neither number replaces per-language results. Declare the language set, missing evaluations, domains, acceptable translations and whether tuning used target-language labels. An overall gain can coexist with serious regressions for a smaller group.
Check what the shared representation actually guarantees
-
Why does preserving source-language inner products not prove that every target translation will be correct?
Answer: It constrains geometry within the source space, not the semantic correspondence between spaces. The target geometry may differ, the dictionary may be wrong or the available seeds may leave directions unconstrained.
-
One seed is [1,0]→[1,0]. Give two orthogonal solutions and explain their disagreement.
Answer: The identity and
diag(1,−1)both fit it exactly. They map [0,1] to [0,1] and [0,−1], respectively. Zero seed error therefore does not identify predictions in the unconstrained direction. -
Two corpora have size ratio 100:1. Under exponent 0.3, what are the language exposure ratio and the smaller corpus’s relative exposure per example?
Answer: The language ratio is 100^0.3:1. Dividing each exposure by its corpus size gives the smaller corpus 100^0.7 times the per-example exposure. That repeats available data; it does not increase its diversity.
-
Languages score 90/100 and 1/10. Why might micro accuracy make the system look better than macro accuracy?
Answer: Micro accuracy weights each test example equally, so the larger set dominates: 91/110. Macro accuracy gives each language equal weight: (0.9+0.1)/2=0.5. Report both denominators and the individual scores.
Read the sharing mechanism and evaluation together
The 2016 mapping paper makes its geometric constraints explicit. VecMap’s official repository places that method in a larger series of supervised and unsupervised mapping work; this article does not implement the whole series. XLM-R provides a contextual multilingual approach with its own data, objective and capacity tradeoffs. Mapping assumptions Pinned VecMap reference XLM-R
Before attributing a cross-language improvement to shared knowledge, identify the resources that were shared, the labels that were withheld and the languages for which the improvement was measured. Those choices determine whether an experiment demonstrates alignment, transfer or simply a better-resourced training setup.
Make a prediction, then check
Does one perfectly fitted seed [1,0]→[1,0] identify the full two-dimensional map?
Learning objectives
- Derive the orthogonal row-vector mapping and preserve its orientation.
- Identify unconstrained directions despite zero seed error.
- Calculate how language sampling changes per-example exposure.
- Report held-out dictionary labels and per-language evaluation separately.
Prerequisites & connections
Explore related knowledge →References
- Learning principled bilingual mappings of word embeddings while preserving monolingual invariance
Mikel Artetxe, Gorka Labaka, Eneko Agirre · 2016 - Unsupervised Cross-lingual Representation Learning at Scale
Alexis Conneau, Kartikay Khandelwal, Naman Goyal, Vishrav Chaudhary, Guillaume Wenzek, Francisco Guzmán, Edouard Grave, Myle Ott, Luke Zettlemoyer, Veselin Stoyanov · 2020 - VecMap: pinned mapping framework README and license header
Mikel Artetxe, Gorka Labaka, Eneko Agirre · 2019
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-13 · Single AI author checked row-vector orthogonal mapping against scoped Artetxe definitions and XLM-R sampling description. Six paired equations and four explained exercises: SVD objective expansion and trace bound, unrestricted determinant, rank deficiency with two maps, positive sheared-space residual, sampling probabilities and micro/macro aggregation. Constructed vectors and held-out seed labels are not a language benchmark; no centering or full XLM-R reproduction.
- Six paired equations include the explicit trace bound; pre-clarification draft preserved. Orthogonality, determinant freedom, rank-one nonuniqueness, disjoint seed/test labels, positive-count sampling and equal-language aggregation independently checked.
- Four computed SVGs bind exact bilingual MDX. The four-topic group passed nine numeric/encoding checks and 24 isolated language/width cases with four fallback fonts; eight actual screenshots inspected by the AI author. Literal-prose AST checked before freezing. Full article browser acceptance is separate; no human peer review.
Source locations checked:
- Learning principled bilingual mappings of word embeddings while preserving monolingual invariance · Visually read page2/2290 sections2–2.3: row-vector objective, orthogonal SVD solution, normalization and centering. Our transposed cross-product convention is equivalent; centering and corpus evaluation not implemented.
- Unsupervised Cross-lingual Representation Learning at Scale · Abstract positive transfer/capacity dilution and section3 layout222–238: shared subwords, sampling alpha 0.3 and no language embeddings. Teaching mixture is explicit; no full training pipeline, model-size or performance reproduction.
- VecMap: pinned mapping framework README and license header · Commit 2019-07-01; README 1–25: method series, mapping and evaluation tools. LICENSE.txt first32 lines identify GPLv3; full redistribution obligations not reviewed. Reference only, no code copied.
Related topics