| """What would SUCCESS look like? The jointly-trained bilingual ceiling. |
| |
| SET 4 shows that merging two monolingual Goldfish models produces a model that is destroyed by |
| likelihood and badly degraded by accuracy. That is only interpretable against what a bilingual model |
| of the same budget actually achieves. B-GPT (Arnett et al.) trains English+X jointly with a single |
| shared tokenizer — the target the composition literature is trying to reach without joint training. |
| |
| Reports the same two metrics on the same two corpora: nats per UTF-8 byte on FLORES-200 devtest, and |
| MultiBLiMP 1.0 accuracy.""" |
| import os, sys, json, time, csv, argparse |
| sys.path.insert(0, "/root/compose-audit") |
| from common import * |
| 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=8) |
| A = ap.parse_args() |
| OUT = "/root/compose-audit/results/bgpt_ceiling.jsonl" |
| DEV = "cuda" |
|
|
|
|
| def log(*a): print(f"[{time.strftime('%H:%M:%S')}]", *a, flush=True) |
|
|
|
|
| def build_blocks(tok, text, block=128, 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=8): |
| 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")] |
|
|
|
|
| @torch.no_grad() |
| def mb_acc(model, tok, pairs, dev, bs=48, maxlen=64): |
| def sc(sents): |
| e = tok(sents, return_tensors="pt", padding=True, truncation=True, max_length=maxlen) |
| ids, am = e["input_ids"], e["attention_mask"] |
| 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() |
| sg, sb = sc([g for g, _ in pairs]), sc([b for _, b in pairs]) |
| unk = 0.0 |
| if tok.unk_token_id is not None: |
| e = tok([g for g, _ in pairs], return_tensors="pt", padding=True, truncation=True, max_length=maxlen) |
| unk = float(((e["input_ids"] == tok.unk_token_id) & e["attention_mask"].bool()).sum().item() |
| / max(1, e["attention_mask"].sum().item())) |
| return float((sg > sb).mean()), unk |
|
|
|
|
| eng_text = "\n".join(flores_lines("eng_Latn")[: A.n_sent]) |
| MB_ENG = mb_pairs("eng", A.max_items) |
| BLOCK = 128 |
| |
|
|
|
|
| def eval_model(m, tok, x_text, mbx): |
| be, nbe = build_blocks(tok, eng_text, BLOCK); bx, nbx = build_blocks(tok, x_text, BLOCK) |
| te, _ = nll_total(m, be, DEV, bs=A.bs); tx, _ = nll_total(m, bx, DEV, bs=A.bs) |
| ae, ue = mb_acc(m, tok, MB_ENG, DEV) |
| ax, ux = mb_acc(m, tok, mbx, DEV) |
| return {"nats_per_byte_eng": te / nbe, "nats_per_byte_x": tx / nbx, |
| "multiblimp_eng": ae, "multiblimp_x": ax, "unk_rate_eng": ue, "unk_rate_x": ux} |
|
|
| 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 |
| repo = f"catherinearnett/B-GPT_en_{x2}_{A.variant}" |
| try: |
| m, tok = load_hf(repo, dtype=torch.float32, device=DEV); m.eval() |
| except Exception as e: |
| log("FAILED to load", repo, type(e).__name__, str(e)[:200]); continue |
| x_text = "\n".join(flores_lines(fcode)[: A.n_sent]) |
| MBX = mb_pairs(mb, A.max_items) |
| arms = {"bgpt_joint_bilingual": eval_model(m, tok, x_text, MBX)} |
| log(f" B-GPT joint: {arms['bgpt_joint_bilingual']}") |
| del m; torch.cuda.empty_cache() |
|
|
| |
| gcode = {"nld_Latn": "nld_latn", "spa_Latn": "spa_latn", "ell_Grek": "ell_grek", "pol_Latn": "pol_latn"}[fcode] |
| m_e, tok_e = load_hf("goldfish-models/eng_latn_1000mb", dtype=torch.float32, device=DEV); m_e.eval() |
| SD_E = sd_np(m_e) |
| arms["goldfish_eng_parent"] = eval_model(m_e, tok_e, x_text, MBX) |
| m_x, tok_x = load_hf(f"goldfish-models/{gcode}_1000mb", dtype=torch.float32, device=DEV); m_x.eval() |
| SD_X = sd_np(m_x) |
| arms["goldfish_partner_parent"] = eval_model(m_x, tok_x, x_text, MBX) |
| del m_x; torch.cuda.empty_cache() |
| V = int(m_e.config.vocab_size) |
| 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 |
| for nm, sd in (("merge_M0_naive", MG.average([SD_E, SD_X])), |
| ("merge_M1a_vocab", MG.average([SD_E, SD_X_V]))): |
| sd_load(m_e, sd, DEV) |
| arms[nm] = eval_model(m_e, tok_e, x_text, MBX) |
| log(f" {nm}: {arms[nm]}") |
| del m_e; torch.cuda.empty_cache() |
|
|
| r = {"set": "bgpt_ceiling", "lang": fcode, "repo": repo, "variant": A.variant, |
| "context_tokens": BLOCK, "n_items_eng": len(MB_ENG), "n_items_x": len(MBX), |
| "arms": arms} |
| fh.write(json.dumps(r) + "\n"); fh.flush() |
| fh.close() |
| log("DONE bgpt") |
|
|