多语言NLP:共用模型,不等于语言可以互换
Multilingual NLP
对齐两套虚构词向量,揭示无法唯一确定的映射,再检查语言采样与分语言评测。
multilingual-nlp共用坐标系,需要什么证据?
设想两本虚构词典,每个词条都是平面上的一个点。两边把相关词条排成相似形状,只是其中一个坐标系旋转了。知道少数翻译对,也许就能对齐两边,查找剩余词对。但如果几何形状发生不同扭曲,一次旋转并不够;如果已知词对只约束一个方向,多个映射也可能同样拟合得很好。
多语言NLP(multilingual NLP)研究跨语言处理或共享信息的方法。共享可以发生在词典、对齐后的向量空间、共同分词器、模型参数或训练目标上。跨语言迁移问的是:一种语言学到的信息,是否帮助了另一种语言的任务?训练里出现多种语言,本身不能证明每种语言都获得了迁移收益。
需要仔细说明监督设置。平行句子、双语词典、单语文本和目标语言任务标签,可以有不同组合。目标任务的“零样本”评测通常指在声明设置下没有使用目标任务训练标签,不自动意味着没有用过目标语言文本或双语资源。本例明确使用种子词典,只留出其他翻译标签。
Artetxe等人研究受约束的词空间映射;XLM-R研究共享的多语言上下文表示,并讨论正迁移与有限模型容量的取舍。这是两种不同的信息共享方式,不是同一算法的可互换实现。双语映射 多语言表示学习
正交映射能够保留什么
取k个种子词对,每个表示成d维行向量。先把每个非零向量除以L2长度,令对齐后的源、目标行组成矩阵X和Y。正交对齐求解:
Frobenius范数把各词对、各坐标的平方误差相加。正交约束把映射限制为保持欧氏几何的变换,包括反射,避免任意拉伸在拟合词典时破坏单语关系。原论文把这个约束与长度归一化、可选均值中心化一起讨论;本程序实现归一化和正交映射,没有实现中心化变体。第2—2.3节
展开平方误差,利用正交约束:
前两项固定,因此问题变成最大化迹,即正交Procrustes问题。如果X转置乘Y的奇异值分解为U Sigma V转置,一个最优解及其目标值为:
要看清这个解为什么成立,可令R=VᵀWᵀU。R正交,每个对角元素最多为1。迹是σ-j与R-jj乘积之和;奇异值非负,所以它最多为σ-j之和。选择W=UVᵀ,就使R=I,达到这个上界。
矩阵方向很重要。引用论文分解的是转置后的交叉矩阵,因此因子顺序相反;混用两套记法会把方向搞反。本例测试恢复已知行向量旋转,并用旋转、反射的独立角度搜索比较目标值。正交解,第2.1节
对于任意源行向量x和z,方阵W正交时保留内积:
向量为单位长度时,映射后的源—目标内积就是余弦相似度。最近邻解码器选择值最大的目标行。这是排序规则,不是经过校准的翻译概率;结果也依赖有哪些目标词可以作为候选。
种子拟合完美,不一定能唯一识别映射。只知道[1,0]映到[1,0],单位矩阵和diag(1,−1)都能精确满足种子,却把未观察方向[0,1]送到相反两点。在这个不另限行列式的正交问题中,交叉矩阵满秩给出唯一最优解;秩亏时程序明确标记非唯一,不把某次SVD输出当作已经识别映射的证据。
这是约束不足的问题,另一个问题则是两种真实语言是否满足正交模型。多义词、不同词表、语料领域和不等价几何,都可能使模型不合适。玩具例子故意构造相配的几何,不能证明语言天然可以互换。
把种子词典和测试标签分开
完整原创程序使用Python 3.12和NumPy 1.26.4,构造由已知正交变换连接的六对点。种子索引为0、2、4,留出的翻译标签为1、3、5;所有目标向量仍可参与检索。这是目标词表可见的评测,不是目标数据完全未见的声明。
"""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))
直接用原坐标,三对留出标签准确率为零;拟合种子映射后,准确率为1。这些数值来自构造的几何。秩亏例子接着给出两个精确种子解,它们对未约束方向作出不同预测。另一个经过剪切的目标空间,在正交拟合后仍留正误差,说明模型不能撤销任意扭曲。
测试核对迹上界、已知映射、全部源向量内积、种子顺序不变性、零向量拒绝和最近邻同分规则。若测试词对任一侧的标签与一一对应种子重合,也会报错。一一对应是教学约定;真实翻译词典可能允许多个正确译词,评测约定也应相应改变。
对k个种子、维数d,构造交叉矩阵和SVD需要O(kd²+d³)。n个源行对m个目标行的稠密检索为O(nmd),保存O(nm)相似度;向量准备另需O((n+m)d)。本程序每边词表最多64行,维数最多八。零向量没有余弦方向,因此拒绝;精确同分时选择最低目标索引。
共用容量,还意味着分配谁的训练时间
共享多语言模型的机制不同于拟合词典映射。它可以从语言数据学习共用上下文参数,各语言却也在争取训练曝光和有限表示容量。XLM-R明确研究正迁移与容量稀释,并在其设置中报告了0.3的语言采样指数。这不能证明某种混合对所有模型、语料都最好。模型、数据与容量讨论
下面用一个独立教学例子,按语料规模n-l定义平滑语言混合:
alpha为1时按规模分配曝光,为零时在有数据的语言间均匀采样。明确的零数据规则,避免把零的零次方当成训练样本来源。规模[10000,100]、alpha为0.3时,两语言曝光比为100^0.3;按每条原始样本计算,小语料被重访的频率是大语料的100^0.7倍。曝光增加,不会创造更多独立数据。
该例子演示声明的幂次混合,没有复现完整XLM-R训练流程。分词、序列长度、批次和数据过滤也会影响实际曝光。共用词表可能对不同语言切出不同颗粒度,因此要用明确单位比较预算,不能假设相同序列条数就包含同样信息量。
评测必须保留分语言结果。设各语言答对c-l条、测试数m-l非零,则:
另一个独立例子中,两语言分别答对90/100与1/10。微平均为91/110,约0.8273;宏平均为0.5。两项都不能替代各语言分数。需要说明语言集合、缺失评测、领域、可接受译词,以及调参是否用了目标语言标签。总体改善,可能同时伴随小群体的严重退步。
检查共享表示究竟保证了什么
-
为什么保留源语言内积,不能证明所有目标译词都会正确?
答案:它约束源空间内部几何,没有确定两个空间之间的语义对应。目标几何可能不同,词典可能错误,已有种子也可能留下未约束方向。
-
唯一种子为[1,0]→[1,0]。给出两个正交解,解释它们在哪里不同。
答案:单位矩阵与
diag(1,−1)都精确拟合,但把[0,1]分别映到[0,1]和[0,−1]。因此,零种子误差不能识别未约束方向的预测。 -
两语料规模比为100:1,采样指数0.3。语言曝光比和小语料的相对单样本曝光分别是多少?
答案:语言曝光比为100^0.3:1。再除以各自语料规模,小语料单样本曝光为大语料的100^0.7倍;这是重复已有数据,不是增加多样性。
-
两语言分别答对90/100与1/10,为什么微平均可能让系统看起来比宏平均更好?
答案:微平均给每条测试样本相同权重,大测试集占主导,得到91/110;宏平均给每种语言相同权重,得到(0.9+0.1)/2=0.5。应同时说明分母并报告各语言分数。
把共享机制与评测放在一起读
2016年的映射论文明确写出几何约束;VecMap官方仓库把它放进更大的有监督、无监督映射系列中,本篇没有实现整个系列。XLM-R则采用上下文多语言方法,有自己的数据、目标和容量取舍。映射假设 固定版本VecMap参考 XLM-R
把跨语言改善归因于共享知识之前,应先辨认共享了哪些资源、留出了哪些标签,以及改善究竟在哪些语言上测得。这些选择决定实验展示的是对齐、迁移,还是资源更充足的训练设置。
先判断,再看解释
一个完美拟合的种子[1,0]→[1,0],能识别完整二维映射吗?
学习目标
- 推导正交行向量映射并保持方向一致。
- 识别零种子误差下仍未约束的方向。
- 计算语言采样怎样改变单样本曝光。
- 分清留出词典标签与分语言评测。
先修与延伸
查看知识关联图 →参考文献
- 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
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(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.
- 六组双语公式包括显式迹上界推导,补充前稿保留。独立检查正交性、行列式自由、秩一不唯一、种子与测试标签分离、正计数采样及语言等权汇总。
- 四张计算SVG绑定真实双语程序;本组九项数值/编码检查、24组语言/宽度及四字体检查通过,AI作者实际查看八张截图。冻结前检查普通正文AST;完整文章页面验收另记,不称人工同行审校。
核对的来源位置:
- 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.
相关主题