| """SET 4, ACCURACY arm: MultiBLiMP 1.0 (jumelet/multiblimp) on the Goldfish merges. |
| |
| The Δfloor tables for SET 4 are likelihood only. This asks the accuracy question directly, on the |
| same merges: does anything survive as *grammatical competence*? Minimal pairs are `sen` (grammatical) |
| vs `wrong_sen`; a model is correct when it assigns the higher total log-probability to `sen`. |
| Chance = 0.500. |
| |
| CAVEAT built into the design: the merged models live in the ENGLISH parent's token-id space, so |
| partner-language items must be tokenized with the English tokenizer. The per-cell UNK rate is |
| reported alongside every number; where it is high (Greek) the partner-language accuracy is not |
| interpretable as grammatical competence and is marked as such.""" |
| import os, sys, json, time, csv, argparse, gc |
| sys.path.insert(0, "/root/compose-audit") |
| from common import * |
| import gpt2_align as G2 |
| from mergeschool.core.models import load_hf |
| from huggingface_hub import hf_hub_download |
|
|
| ap = argparse.ArgumentParser() |
| ap.add_argument("--pairs", default="nld_Latn:nld_latn:nld,spa_Latn:spa_latn:spa,ell_Grek:ell_grek:ell,pol_Latn:pol_latn:pol") |
| 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=48) |
| A = ap.parse_args() |
| OUT = "/root/compose-audit/results/set4_multiblimp.jsonl" |
| DEV = "cuda" |
| ENG_REPO = "goldfish-models/eng_latn_1000mb" |
|
|
|
|
| def log(*a): |
| print(f"[{time.strftime('%H:%M:%S')}]", *a, flush=True) |
|
|
|
|
| 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"], r.get("phenomenon", "?")) 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 score(model, ids, am, dev, bs): |
| out = [] |
| 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) |
| out.append((lp.gather(-1, x[:, 1:].unsqueeze(-1)).squeeze(-1) * m[:, 1:].float()).sum(1).cpu()) |
| return torch.cat(out).numpy() |
|
|
|
|
| def unk_rate(tok, ids, am): |
| u = tok.unk_token_id |
| if u is None: return 0.0 |
| return float(((ids == u) & (am.bool())).sum().item() / max(1, am.sum().item())) |
|
|
|
|
| log("loading eng parent") |
| m_e, tok_e = load_hf(ENG_REPO, dtype=torch.float32, device=DEV); m_e.eval() |
| cfg = m_e.config |
| D, NH, NL, V = cfg.n_embd, cfg.n_head, cfg.n_layer, cfg.vocab_size |
| SD_E = sd_np(m_e) |
| shell = m_e |
|
|
| sys.path.insert(0, "/root/compose-audit") |
| from set4_goldfish_lib import sent_acts |
|
|
| eng_lines = flores_lines("eng_Latn")[: A.n_sent] |
| acts_e = sent_acts(m_e, tok_e, eng_lines, DEV) |
| MB_ENG = mb_pairs("eng", A.max_items) |
| ENC_ENG_E = (encode(tok_e, [g for g, b, p in MB_ENG]), encode(tok_e, [b for g, b, p in MB_ENG])) |
| log(f"MultiBLiMP eng items={len(MB_ENG)} UNK(eng tok)={unk_rate(tok_e, *ENC_ENG_E[0]):.2%}") |
|
|
|
|
| def acc(sd, enc_g, enc_b): |
| sd_load(shell, sd, DEV) |
| sg = score(shell, *enc_g, DEV, A.bs); sb = score(shell, *enc_b, DEV, A.bs) |
| return float((sg > sb).mean()) |
|
|
|
|
| ACC_E_ENG = acc(SD_E, *ENC_ENG_E) |
| log(f"eng parent, MultiBLiMP-eng = {ACC_E_ENG:.4f}") |
|
|
| 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, gcode, mb = spec.split(":") |
| if fcode in done: continue |
| t0 = time.time() |
| repo = f"goldfish-models/{gcode}_1000mb" |
| log(f"=== {fcode} <- {repo}") |
| m_x, tok_x = load_hf(repo, dtype=torch.float32, device=DEV); m_x.eval() |
| SD_X = sd_np(m_x) |
| x_lines = flores_lines(fcode)[: A.n_sent] |
| acts_x = sent_acts(m_x, tok_x, x_lines, DEV) |
| MB_X = mb_pairs(mb, A.max_items) |
| ENC_X_X = (encode(tok_x, [g for g, b, p in MB_X]), encode(tok_x, [b for g, b, p in MB_X])) |
| ENC_X_E = (encode(tok_e, [g for g, b, p in MB_X]), encode(tok_e, [b for g, b, p in MB_X])) |
| unk_x_e = unk_rate(tok_e, *ENC_X_E[0]); unk_x_x = unk_rate(tok_x, *ENC_X_X[0]) |
| sg = score(m_x, *ENC_X_X[0], DEV, A.bs); sb = score(m_x, *ENC_X_X[1], DEV, A.bs) |
| ACC_X_X = float((sg > sb).mean()) |
| del m_x; torch.cuda.empty_cache() |
| ACC_E_X = acc(SD_E, *ENC_X_E) |
| log(f" items={len(MB_X)} UNK(eng tok on {mb})={unk_x_e:.2%} X parent MB-{mb}={ACC_X_X:.4f} " |
| f"eng parent MB-{mb}={ACC_E_X:.4f} (chance 0.5)") |
|
|
| vkeys = [k for k in SD_X if k.endswith("wte.weight") or k.endswith("lm_head.weight")] |
| SD_X_V, cov = AL.remap_vocab_rows(SD_X, tok_e, tok_x, V, keys=vkeys) |
| for k in vkeys: |
| W = np.asarray(SD_X_V[k], float) |
| if W.shape[0] == V: |
| bad = ~np.isfinite(W).all(axis=1); W[bad] = np.asarray(SD_E[k], float)[bad] |
| SD_X_V[k] = W |
| BODY = [k for k in SD_E if not (k.endswith("wte.weight") or k.endswith("lm_head.weight"))] |
| R_emb, n_anch = G2.emb_procrustes(SD_E, SD_X, tok_e, tok_x) |
| sd_emb = G2.apply_resid(SD_X_V, D, R=R_emb) |
| sd_emb2, _ = G2.align_full(SD_E, sd_emb, D, NH, None, None, "permutation", body_keys=BODY) |
| sdp, ip = G2.align_full(SD_E, SD_X_V, D, NH, acts_e, acts_x, "permutation", body_keys=BODY) |
| sdo, io = G2.align_full(SD_E, SD_X_V, D, NH, acts_e, acts_x, "orthogonal", body_keys=BODY) |
| sdof, _ = G2.align_full(SD_E, SD_X_V, D, NH, acts_e, acts_x, "orthogonal", body_keys=BODY, accept_each=False) |
|
|
| rungs = {"M0_naive_avg": MG.average([SD_E, SD_X]), |
| "M1a_vocab_avg": MG.average([SD_E, SD_X_V]), |
| "M1b_vocab_perm_avg": MG.average([SD_E, sdp]), |
| "M1c_vocab_orth_avg": MG.average([SD_E, sdo]), |
| "M1e_vocab_orth_forced": MG.average([SD_E, sdof]), |
| "M1g_emb_procrustes": MG.average([SD_E, sd_emb]), |
| "M1h_emb_proc_units": MG.average([SD_E, sd_emb2])} |
| res = {} |
| for k, sd in rungs.items(): |
| res[k] = {"mb_eng": acc(sd, *ENC_ENG_E), "mb_x": acc(sd, *ENC_X_E)} |
| res[k]["delta_eng_vs_eng_parent"] = res[k]["mb_eng"] - ACC_E_ENG |
| res[k]["delta_x_vs_x_parent"] = res[k]["mb_x"] - ACC_X_X |
|
|
| r = {"set": "set4_multiblimp", "lang": fcode, "mb_lang": mb, "repo_b": repo, |
| "metric": "MultiBLiMP 1.0 accuracy (chance=0.5) -- ACCURACY, not likelihood", |
| "n_items_eng": len(MB_ENG), "n_items_x": len(MB_X), |
| "unk_rate_eng_tok_on_x_items": unk_x_e, "unk_rate_own_tok_on_x_items": unk_x_x, |
| "parents": {"eng_on_mb_eng": ACC_E_ENG, "x_on_mb_x": ACC_X_X, "eng_on_mb_x": ACC_E_X}, |
| "rungs": res, "align_info": {"perm": ip, "orth": io}, "secs": time.time() - t0} |
| fh.write(json.dumps(r) + "\n"); fh.flush() |
| log(" " + " ".join(f"{k}: eng={v['mb_eng']:.3f} x={v['mb_x']:.3f}" for k, v in res.items())) |
| del rungs, sdp, sdo, sdof, sd_emb, sd_emb2, SD_X, SD_X_V; gc.collect() |
| fh.close() |
| log("DONE set4_multiblimp") |
|
|