compose-audit / code /bgpt_merge.py
suchirsalhan's picture
compose-audit refresh 2026-08-26 22:07 UTC
58e7bb7 verified
Raw
History Blame Contribute Delete
8.61 kB
"""SET 4b: merging two BILINGUAL models of the SAME language pair.
This is the cell that separates the two obstructions SET 4 confounds. `B-GPT_en_X_simultaneous` and
`B-GPT_X_en_simultaneous` are trained on the same two languages, the same data recipe and the same
architecture, and their tokenizers share ~94% of their surface forms (against ~15-28% for two
monolingual Goldfish tokenizers) — so vocabulary transport is nearly lossless here. What is left
between them is an independent training run: different init, different data order, a permuted
vocabulary indexing. If merging works anywhere in the composition setting, it should work here.
Rungs: M0 naive · M1a vocab-transported · M1b +permutation-aligned · M1c +Procrustes ·
M1g embedding-row Procrustes. Metrics: Δfloor in nats/UTF-8 byte (FLORES-200 devtest, both
languages) AND MultiBLiMP 1.0 accuracy, on the same merges."""
import os, sys, json, time, csv, argparse, gc
sys.path.insert(0, "/root/compose-audit")
from common import *
import gpt2_align as G2
from set4_goldfish_lib import sent_acts
from mergeschool.core.models import load_hf
from huggingface_hub import hf_hub_download
ap = argparse.ArgumentParser()
ap.add_argument("--pairs", default="nld_Latn:nl:nld,spa_Latn:es:spa,ell_Grek:el:ell,pol_Latn:pl:pol")
ap.add_argument("--variant", default="simultaneous")
ap.add_argument("--n_sent", type=int, default=500)
ap.add_argument("--max_items", type=int, default=1200)
ap.add_argument("--bs", type=int, default=16)
A = ap.parse_args()
OUT = "/root/compose-audit/results/bgpt_merge.jsonl"
DEV = "cuda"
BLOCK = 128 # B-GPT's n_positions
def log(*a): print(f"[{time.strftime('%H:%M:%S')}]", *a, flush=True)
def build_blocks(tok, text, block=BLOCK, max_blocks=200):
ids = tok(text)["input_ids"]
n = max(1, min(max_blocks, len(ids) // block))
arr = torch.from_numpy(np.asarray(ids[: n * block], dtype=np.int64).reshape(n, block))
nb = sum(len(tok.decode(list(arr[i, 1:].numpy())).encode("utf-8")) for i in range(n))
return arr, nb
@torch.no_grad()
def nll_total(model, blocks, dev, bs):
tot, ntok = 0.0, 0
for i in range(0, blocks.shape[0], bs):
x = blocks[i:i + bs].to(dev)
lp = torch.log_softmax(model(x).logits.float()[:, :-1], -1)
tgt = x[:, 1:]
tot += (-lp.gather(-1, tgt.unsqueeze(-1)).squeeze(-1)).sum().item(); ntok += tgt.numel()
return tot, ntok
def mb_pairs(lang, n):
p = hf_hub_download("jumelet/multiblimp", f"{lang}/data.tsv", repo_type="dataset")
rows = list(csv.DictReader(open(p, encoding="utf-8"), delimiter="\t"))[:n]
return [(r["sen"], r["wrong_sen"]) for r in rows if r.get("sen") and r.get("wrong_sen")]
def encode(tok, sents, maxlen=64):
e = tok(sents, return_tensors="pt", padding=True, truncation=True, max_length=maxlen)
return e["input_ids"], e["attention_mask"]
@torch.no_grad()
def mb_acc(model, encg, encb, dev, bs=48):
def sc(ids, am):
o = []
for i in range(0, ids.shape[0], bs):
x, m = ids[i:i + bs].to(dev), am[i:i + bs].to(dev)
lp = torch.log_softmax(model(x, attention_mask=m).logits.float()[:, :-1], -1)
o.append((lp.gather(-1, x[:, 1:].unsqueeze(-1)).squeeze(-1) * m[:, 1:].float()).sum(1).cpu())
return torch.cat(o).numpy()
return float((sc(*encg) > sc(*encb)).mean())
eng_lines = flores_lines("eng_Latn")[: A.n_sent]
eng_text = "\n".join(eng_lines)
MB_ENG = mb_pairs("eng", A.max_items)
done = set()
if os.path.exists(OUT):
for l in open(OUT):
try: done.add(json.loads(l)["lang"])
except Exception: pass
fh = open(OUT, "a")
for spec in A.pairs.split(","):
fcode, x2, mb = spec.split(":")
if fcode in done: continue
t0 = time.time()
ra = f"catherinearnett/B-GPT_en_{x2}_{A.variant}"
rb = f"catherinearnett/B-GPT_{x2}_en_{A.variant}"
log(f"=== {fcode}: A={ra} B={rb}")
try:
m_a, tok_a = load_hf(ra, dtype=torch.float32, device=DEV); m_a.eval()
m_b, tok_b = load_hf(rb, dtype=torch.float32, device=DEV); m_b.eval()
except Exception as e:
log("load failed", type(e).__name__, str(e)[:200]); continue
cfg = m_a.config
D, NH, V = cfg.n_embd, cfg.n_head, cfg.vocab_size
SD_A, SD_B = sd_np(m_a), sd_np(m_b)
x_lines = flores_lines(fcode)[: A.n_sent]; x_text = "\n".join(x_lines)
MBX = mb_pairs(mb, A.max_items)
acts_a = sent_acts(m_a, tok_a, eng_lines + x_lines, DEV) # same sentences, both models
acts_b = sent_acts(m_b, tok_b, eng_lines + x_lines, DEV)
bl_e, by_e = build_blocks(tok_a, eng_text); bl_x, by_x = build_blocks(tok_a, x_text)
ENC_E = (encode(tok_a, [g for g, _ in MB_ENG]), encode(tok_a, [b for _, b in MB_ENG]))
ENC_X = (encode(tok_a, [g for g, _ in MBX]), encode(tok_a, [b for _, b in MBX]))
ta, _ = nll_total(m_a, bl_e, DEV, A.bs); txa, _ = nll_total(m_a, bl_x, DEV, A.bs)
PA = {"nats_per_byte_eng": ta / by_e, "nats_per_byte_x": txa / by_x,
"multiblimp_eng": mb_acc(m_a, *ENC_E, DEV), "multiblimp_x": mb_acc(m_a, *ENC_X, DEV)}
# parent B in its OWN tokenizer, so its floor is not penalised by A's indexing
blb_e, byb_e = build_blocks(tok_b, eng_text); blb_x, byb_x = build_blocks(tok_b, x_text)
tb, _ = nll_total(m_b, blb_e, DEV, A.bs); txb, _ = nll_total(m_b, blb_x, DEV, A.bs)
ENC_E_B = (encode(tok_b, [g for g, _ in MB_ENG]), encode(tok_b, [b for _, b in MB_ENG]))
ENC_X_B = (encode(tok_b, [g for g, _ in MBX]), encode(tok_b, [b for _, b in MBX]))
PB = {"nats_per_byte_eng": tb / byb_e, "nats_per_byte_x": txb / byb_x,
"multiblimp_eng": mb_acc(m_b, *ENC_E_B, DEV), "multiblimp_x": mb_acc(m_b, *ENC_X_B, DEV)}
del m_b; torch.cuda.empty_cache()
shell = m_a
log(f" parents A={PA} B={PB}")
vkeys = [k for k in SD_B if k.endswith("wte.weight") or k.endswith("lm_head.weight")]
SD_B_V, _ = AL.remap_vocab_rows(SD_B, tok_a, tok_b, V, keys=vkeys)
for k in vkeys:
W = np.asarray(SD_B_V[k], float)
if W.shape[0] == V:
bad = ~np.isfinite(W).all(axis=1); W[bad] = np.asarray(SD_A[k], float)[bad]
SD_B_V[k] = W
anchors = AL.vocab_anchors(tok_a, tok_b)
BODY = [k for k in SD_A if not (k.endswith("wte.weight") or k.endswith("lm_head.weight"))]
R_emb, n_anch = G2.emb_procrustes(SD_A, SD_B, tok_a, tok_b)
sd_emb = G2.apply_resid(SD_B_V, D, R=R_emb)
sdp, ip = G2.align_full(SD_A, SD_B_V, D, NH, acts_a, acts_b, "permutation", body_keys=BODY)
sdo, io = G2.align_full(SD_A, SD_B_V, D, NH, acts_a, acts_b, "orthogonal", body_keys=BODY)
rungs = {"M0_naive_avg": MG.average([SD_A, SD_B]),
"M1a_vocab_avg": MG.average([SD_A, SD_B_V]),
"M1b_vocab_perm_avg": MG.average([SD_A, sdp]),
"M1c_vocab_orth_avg": MG.average([SD_A, sdo]),
"M1g_emb_procrustes": MG.average([SD_A, sd_emb])}
floor_e = min(PA["nats_per_byte_eng"], PB["nats_per_byte_eng"])
floor_x = min(PA["nats_per_byte_x"], PB["nats_per_byte_x"])
ceil_e = max(PA["multiblimp_eng"], PB["multiblimp_eng"])
ceil_x = max(PA["multiblimp_x"], PB["multiblimp_x"])
res = {}
for k, sd in rungs.items():
sd_load(shell, sd, DEV)
t_e, _ = nll_total(shell, bl_e, DEV, A.bs); t_x, _ = nll_total(shell, bl_x, DEV, A.bs)
res[k] = {"nats_per_byte_eng": t_e / by_e, "nats_per_byte_x": t_x / by_x,
"delta_floor_eng": t_e / by_e - floor_e, "delta_floor_x": t_x / by_x - floor_x,
"multiblimp_eng": mb_acc(shell, *ENC_E, DEV), "multiblimp_x": mb_acc(shell, *ENC_X, DEV)}
res[k]["delta_floor_mean"] = 0.5 * (res[k]["delta_floor_eng"] + res[k]["delta_floor_x"])
res[k]["multiblimp_mean"] = 0.5 * (res[k]["multiblimp_eng"] + res[k]["multiblimp_x"])
r = {"set": "bgpt_merge", "lang": fcode, "repo_a": ra, "repo_b": rb, "variant": A.variant,
"context_tokens": BLOCK, "vocab_anchors": len(anchors), "vocab_overlap": len(anchors) / V,
"metric": "nats/UTF-8 byte (likelihood) + MultiBLiMP accuracy",
"parents": {"A": PA, "B": PB}, "floor_eng": floor_e, "floor_x": floor_x,
"ceiling_mb_eng": ceil_e, "ceiling_mb_x": ceil_x,
"align_info": {"perm": ip, "orth": io}, "rungs": res, "secs": time.time() - t0}
fh.write(json.dumps(r) + "\n"); fh.flush()
log(" " + " | ".join(f"{k}: dfl={v['delta_floor_mean']:+.3f} MB={v['multiblimp_mean']:.3f}"
for k, v in res.items()))
del rungs, sdp, sdo, sd_emb, SD_B, SD_B_V, m_a; gc.collect(); torch.cuda.empty_cache()
fh.close()
log("DONE bgpt_merge")