Upload src/xscript/eval/alignment.py with huggingface_hub
Browse files- src/xscript/eval/alignment.py +135 -0
src/xscript/eval/alignment.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""MEXA-style cross-lingual representation alignment on FLORES+ dev.
|
| 2 |
+
|
| 3 |
+
For every layer, embed each language's parallel sentences by mean-pooling that
|
| 4 |
+
layer's hidden states, then measure how well EN sentences retrieve their
|
| 5 |
+
translations (and vice versa). High alignment on cross-script pairs would say
|
| 6 |
+
the model builds a shared multilingual space despite the script gap -- the
|
| 7 |
+
representation-side counterpart to the BPB/BTS story.
|
| 8 |
+
|
| 9 |
+
Reported per (EN, partner) pair, at the best-aligned layer:
|
| 10 |
+
- top-1 EN->L and L->EN retrieval accuracy
|
| 11 |
+
- mutual nearest-neighbour rate
|
| 12 |
+
- mean cosine similarity of translations and its margin over non-pairs
|
| 13 |
+
Cross-script (AR/ZH) vs same-script (DE/FR), and starved vs destarved, is the
|
| 14 |
+
comparison of interest.
|
| 15 |
+
|
| 16 |
+
Only languages in the checkpoint's training mixture are embedded. Monolingual
|
| 17 |
+
runs therefore have no cross-lingual pair; an EN-partner bilingual run reports
|
| 18 |
+
exactly that pair.
|
| 19 |
+
"""
|
| 20 |
+
import json
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
|
| 23 |
+
import numpy as np
|
| 24 |
+
import torch
|
| 25 |
+
|
| 26 |
+
from ..langs import ANCHOR, LANGS
|
| 27 |
+
from ..paths import RUNS, RESULTS, tokenizer_dir, ensure
|
| 28 |
+
from ..tok.wrapper import Tok
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@torch.no_grad()
|
| 32 |
+
def _embed(model, tok, sentences, device, seq_len, batch=32) -> np.ndarray:
|
| 33 |
+
"""(n_layers+1, N, dim) L2-normalised mean-pooled embeddings."""
|
| 34 |
+
model.eval()
|
| 35 |
+
out = None
|
| 36 |
+
N = len(sentences)
|
| 37 |
+
for s0 in range(0, N, batch):
|
| 38 |
+
chunk = sentences[s0:s0 + batch]
|
| 39 |
+
seqs = [tok.encode(t, bos=True)[:seq_len] for t in chunk]
|
| 40 |
+
lens = [len(s) for s in seqs]
|
| 41 |
+
maxlen = max(lens)
|
| 42 |
+
arr = np.zeros((len(seqs), maxlen), dtype=np.int64)
|
| 43 |
+
for i, s in enumerate(seqs):
|
| 44 |
+
arr[i, :len(s)] = s
|
| 45 |
+
idx = torch.from_numpy(arr).to(device)
|
| 46 |
+
reps = model.layer_reps(idx).float() # (Lr, b, T, d)
|
| 47 |
+
mask = torch.zeros(len(seqs), maxlen, device=device)
|
| 48 |
+
for i, ln in enumerate(lens):
|
| 49 |
+
mask[i, :ln] = 1.0
|
| 50 |
+
m = mask[None, :, :, None]
|
| 51 |
+
pooled = (reps * m).sum(2) / m.sum(2).clamp(min=1) # (Lr, b, d)
|
| 52 |
+
pooled = torch.nn.functional.normalize(pooled, dim=-1).cpu().numpy()
|
| 53 |
+
if out is None:
|
| 54 |
+
out = [np.zeros((N, pooled.shape[-1]), dtype=np.float32)
|
| 55 |
+
for _ in range(pooled.shape[0])]
|
| 56 |
+
for lyr in range(pooled.shape[0]):
|
| 57 |
+
out[lyr][s0:s0 + len(seqs)] = pooled[lyr]
|
| 58 |
+
return np.stack(out, axis=0)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _retrieval(E: np.ndarray, F: np.ndarray) -> dict:
|
| 62 |
+
sim = E @ F.T
|
| 63 |
+
n = sim.shape[0]
|
| 64 |
+
en_to = sim.argmax(1)
|
| 65 |
+
to_en = sim.argmax(0)
|
| 66 |
+
diag = np.arange(n)
|
| 67 |
+
top1_ef = float((en_to == diag).mean())
|
| 68 |
+
top1_fe = float((to_en == diag).mean())
|
| 69 |
+
mutual = float(((en_to == diag) & (to_en[en_to] == diag)).mean())
|
| 70 |
+
matched = float(np.diag(sim).mean())
|
| 71 |
+
if n > 1:
|
| 72 |
+
nonmatched = float((sim.sum() - np.trace(sim)) / (n * (n - 1)))
|
| 73 |
+
else:
|
| 74 |
+
nonmatched = 0.0
|
| 75 |
+
return {"top1_en2l": top1_ef, "top1_l2en": top1_fe, "mutual_nn": mutual,
|
| 76 |
+
"cosine_matched": matched, "cosine_nonmatched": nonmatched,
|
| 77 |
+
"cosine_margin": matched - nonmatched}
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def compute(run_name: str, tok_name: str, split: str = "dev",
|
| 81 |
+
model=None, device=None, seq_len: int = 2048,
|
| 82 |
+
langs: list[str] | None = None) -> dict:
|
| 83 |
+
from .. import flores
|
| 84 |
+
dev = device or torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 85 |
+
if model is None:
|
| 86 |
+
model, ck_langs = _load_model(run_name, dev)
|
| 87 |
+
langs = langs or ck_langs
|
| 88 |
+
elif langs is None:
|
| 89 |
+
raise ValueError("langs is required when passing an in-memory model")
|
| 90 |
+
partners = [lang for lang in langs if lang != ANCHOR] if ANCHOR in langs else []
|
| 91 |
+
if not partners:
|
| 92 |
+
return {"run": run_name, "split": split, "langs": langs, "pairs": {}}
|
| 93 |
+
eval_langs = [ANCHOR] + partners
|
| 94 |
+
par = flores.load_parallel(eval_langs, split)
|
| 95 |
+
tok = Tok(tokenizer_dir(tok_name))
|
| 96 |
+
emb = {l: _embed(model, tok, par[l], dev, seq_len) for l in par}
|
| 97 |
+
n_layers = emb[ANCHOR].shape[0]
|
| 98 |
+
pairs = {}
|
| 99 |
+
for p in partners:
|
| 100 |
+
per_layer = [_retrieval(emb[ANCHOR][ly], emb[p][ly]) for ly in range(n_layers)]
|
| 101 |
+
best = max(range(n_layers), key=lambda ly: per_layer[ly]["mutual_nn"])
|
| 102 |
+
pairs[p] = {"same_script": LANGS[p].same_script_as_en,
|
| 103 |
+
"best_layer": best, "best": per_layer[best],
|
| 104 |
+
"per_layer": per_layer}
|
| 105 |
+
return {"run": run_name, "split": split, "langs": langs, "pairs": pairs}
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def _load_model(run_name: str, device, tag: str = "final"):
|
| 109 |
+
from ..model import ModelConfig, Transformer
|
| 110 |
+
ck = torch.load(RUNS / run_name / "checkpoints" / f"{tag}.pt",
|
| 111 |
+
map_location="cpu", weights_only=False)
|
| 112 |
+
model = Transformer(ModelConfig(**ck["cfg"]["model"]))
|
| 113 |
+
model.load_state_dict(ck["model"])
|
| 114 |
+
return model.to(device).eval(), list(ck["cfg"]["langs"])
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def run(run_name: str, tok_name: str, split: str = "dev",
|
| 118 |
+
out_dir: Path | None = None) -> dict:
|
| 119 |
+
out_dir = ensure(Path(out_dir) if out_dir else RESULTS / "alignment")
|
| 120 |
+
res = compute(run_name, tok_name, split)
|
| 121 |
+
(out_dir / f"{run_name}.json").write_text(json.dumps(res, indent=2))
|
| 122 |
+
md = [f"# Alignment: {run_name} (FLORES+ {split})", "",
|
| 123 |
+
"| partner | script | best layer | top1 EN->L | top1 L->EN | mutual-NN | cosine pair | cosine margin |",
|
| 124 |
+
"|---|---|---|---|---|---|---|---|"]
|
| 125 |
+
for p, v in res["pairs"].items():
|
| 126 |
+
b = v["best"]
|
| 127 |
+
md.append(f"| {p} | {'same' if v['same_script'] else 'cross'} | "
|
| 128 |
+
f"{v['best_layer']} | {b['top1_en2l']:.3f} | "
|
| 129 |
+
f"{b['top1_l2en']:.3f} | {b['mutual_nn']:.3f} | "
|
| 130 |
+
f"{b['cosine_matched']:.3f} | {b['cosine_margin']:.3f} |")
|
| 131 |
+
if not res["pairs"]:
|
| 132 |
+
md.extend(["", "No EN-partner bilingual pair exists in this run."])
|
| 133 |
+
(out_dir / f"{run_name}.md").write_text("\n".join(md) + "\n")
|
| 134 |
+
print(f"[align] wrote {out_dir}/{run_name}.md")
|
| 135 |
+
return res
|