| """SET 4: Goldfish monolingual -> bilingual merge on the REAL composition models. |
| goldfish-models/eng_latn_1000mb x goldfish-models/{nld,spa,ell,pol}_*_1000mb (GPT-2, 125M each, |
| SEPARATE monolingual tokenizers). Rungs: M0 naive average (the merge the manuscript reports as |
| failing) vs M1 vocab-remapped + unit-aligned (permutation / Procrustes on the residual basis, |
| free MLP axis, attention heads). |
| |
| METRIC: Delta-floor in NATS PER UTF-8 BYTE on FLORES-200 devtest. Bytes, not tokens: the two |
| parents use different tokenizers, so nats/token is not comparable across them. This is a |
| LIKELIHOOD metric, not benchmark accuracy.""" |
| import os, sys, json, time, argparse, gc |
| sys.path.insert(0, "/root/compose-audit") |
| from common import * |
| import gpt2_align as G2 |
| from mergeschool.core.models import load_hf |
|
|
| ap = argparse.ArgumentParser() |
| ap.add_argument("--pairs", default="nld_Latn:nld_latn,spa_Latn:spa_latn,ell_Grek:ell_grek,pol_Latn:pol_latn") |
| ap.add_argument("--n_sent", type=int, default=500) |
| ap.add_argument("--bs", type=int, default=8) |
| ap.add_argument("--barrier_n", type=int, default=7) |
| A = ap.parse_args() |
| OUT = "/root/compose-audit/results/set4_goldfish.jsonl" |
| DEV = "cuda" |
| ENG_REPO = "goldfish-models/eng_latn_1000mb" |
|
|
|
|
| def log(*a): |
| print(f"[{time.strftime('%H:%M:%S')}]", *a, flush=True) |
|
|
|
|
| |
| def build_blocks(tok, text, block=512, max_blocks=64): |
| ids = tok(text)["input_ids"] |
| n = max(1, min(max_blocks, len(ids) // block)) |
| ids = ids[: n * block] |
| arr = torch.from_numpy(np.asarray(ids, dtype=np.int64).reshape(n, block)) |
| nbytes = sum(len(tok.decode(list(arr[i, 1:].numpy())).encode("utf-8")) for i in range(n)) |
| return arr, nbytes |
|
|
|
|
| @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 |
|
|
|
|
| @torch.no_grad() |
| def sent_acts(model, tok, lines, dev, bs=16, maxlen=128): |
| """Mean-pooled per-sentence residual activations, {layer: (n_sent, d)} -- rows are matched |
| ACROSS LANGUAGES by FLORES sentence id, which is what makes a cross-lingual basis map fittable.""" |
| outs = None |
| for i in range(0, len(lines), bs): |
| enc = tok(lines[i:i + bs], return_tensors="pt", padding=True, truncation=True, max_length=maxlen) |
| ids = enc["input_ids"].to(dev); am = enc["attention_mask"].to(dev).float() |
| hs = model(ids, attention_mask=enc["attention_mask"].to(dev), output_hidden_states=True).hidden_states |
| if outs is None: |
| outs = [[] for _ in hs] |
| w = am / am.sum(1, keepdim=True).clamp(min=1) |
| for j, h in enumerate(hs): |
| outs[j].append((h.float() * w.unsqueeze(-1)).sum(1).cpu()) |
| return {j: torch.cat(o).numpy().astype(np.float64) for j, o in enumerate(outs)} |
|
|
|
|
| |
| 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) |
| log(f"gpt2 d={D} heads={NH} layers={NL} vocab={V}") |
|
|
| eng_lines = flores_lines("eng_Latn")[: A.n_sent] |
| eng_text = "\n".join(eng_lines) |
| bl_e_e, by_e_e = build_blocks(tok_e, eng_text) |
| acts_e = sent_acts(m_e, tok_e, eng_lines, DEV) |
| shell = m_e |
|
|
|
|
| def ev_np(sd, blocks): |
| sd_load(shell, sd, DEV) |
| t, n = nll_total(shell, blocks, DEV, bs=A.bs) |
| return t, n |
|
|
|
|
| nll_e_eng_t, nll_e_eng_n = nll_total(m_e, bl_e_e, DEV, bs=A.bs) |
| PARENT_ENG = {"nats_per_byte": nll_e_eng_t / by_e_e, "nats_per_token": nll_e_eng_t / nll_e_eng_n} |
| log(f"eng parent on eng: {PARENT_ENG}") |
|
|
| done = set() |
| if os.path.exists(OUT): |
| for line in open(OUT): |
| try: done.add(json.loads(line)["lang"]) |
| except Exception: pass |
| fh = open(OUT, "a") |
|
|
| for spec in A.pairs.split(","): |
| fcode, gcode = spec.split(":") |
| if fcode in done: |
| log("skip", fcode); 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] |
| x_text = "\n".join(x_lines) |
| bl_x_x, by_x_x = build_blocks(tok_x, x_text) |
| bl_x_e, by_x_e = build_blocks(tok_e, x_text) |
| acts_x = sent_acts(m_x, tok_x, x_lines, DEV) |
| tx, nx = nll_total(m_x, bl_x_x, DEV, bs=A.bs) |
| parent_x = {"nats_per_byte": tx / by_x_x, "nats_per_token": tx / nx} |
| del m_x; torch.cuda.empty_cache() |
| te, ne = ev_np(SD_E, bl_x_e) |
| eng_on_x = {"nats_per_byte": te / by_x_e, "nats_per_token": te / ne} |
| log(f" parents: eng/eng={PARENT_ENG['nats_per_byte']:.4f} x/x={parent_x['nats_per_byte']:.4f} " |
| f"eng-on-x={eng_on_x['nats_per_byte']:.4f} nats/byte") |
|
|
| |
| 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) |
| bad = ~np.isfinite(W).all(axis=1) if W.shape[0] == V else ~np.isfinite(W).all(axis=0) |
| if W.shape[0] == V: |
| W[bad] = np.asarray(SD_E[k], float)[bad] |
| SD_X_V[k] = W |
| anchors = AL.vocab_anchors(tok_e, tok_x) |
| log(f" vocab anchors={len(anchors)} ({len(anchors)/V:.1%} of English ids)") |
|
|
| 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) |
| sdpf, ipf = G2.align_full(SD_E, SD_X_V, D, NH, acts_e, acts_x, "permutation", body_keys=BODY, accept_each=False) |
| sdof, iof = G2.align_full(SD_E, SD_X_V, D, NH, acts_e, acts_x, "orthogonal", body_keys=BODY, accept_each=False) |
| log(f" align perm={ip} orth={io}") |
|
|
| |
| KEYS = shared_keys(SD_E, SD_X) |
| fa, fb = flat(SD_E, KEYS), flat(SD_X, KEYS) |
| p = {"n_emb_anchors": n_anch, "weight_cosine": float(fa @ fb / (np.linalg.norm(fa) * np.linalg.norm(fb))), |
| "vocab_overlap": len(anchors) / V} |
| p["weight_cosine_body"] = float(np.mean([ |
| float(np.asarray(SD_E[k], float).ravel() @ np.asarray(SD_X[k], float).ravel() / |
| (np.linalg.norm(SD_E[k]) * np.linalg.norm(SD_X[k]) + 1e-12)) for k in BODY])) |
| q_p = MT.quotient_weight_distance(SD_E, SD_X_V, sdp, BODY) |
| q_o = MT.quotient_weight_distance(SD_E, SD_X_V, sdo, BODY) |
| p.update({"d_raw": q_p["d_raw"], "qmd_perm": q_p["qmd"], "coord_share_perm": q_p["coord_fraction"], |
| "qmd_orth": q_o["qmd"], "coord_share_orth": q_o["coord_fraction"]}) |
| b_raw = AL.block_normalised_distance(SD_E, SD_X_V, BODY) |
| b_p = AL.block_normalised_distance(SD_E, sdp, BODY) |
| b_o = AL.block_normalised_distance(SD_E, sdo, BODY) |
| p.update({"bnd_raw": b_raw, "bnd_perm": b_p, "bnd_orth": b_o, |
| "coord_share_bnd_perm": float((b_raw - b_p) / b_raw), |
| "coord_share_bnd_orth": float((b_raw - b_o) / b_raw)}) |
| ck, ckby = mean_cka(acts_e, acts_x) |
| p["cka_mean"] = ck; p["cka_last"] = ckby[max(ckby)] |
| for g in ("perm", "procrustes", "ot"): |
| try: |
| qr = MT.quotient_residual(acts_e[NL // 2], acts_x[NL // 2], group=g) |
| p[f"qmd_act_{g}"] = qr["distance"]; p[f"aligned_cka_{g}"] = qr["aligned_cka"] |
| except Exception: |
| p[f"qmd_act_{g}"] = float("nan") |
|
|
| |
| 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]), |
| "M1d_vocab_perm_forced": MG.average([SD_E, sdpf]), |
| "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]), |
| "M1f_perm_novocab": MG.average([SD_E, G2.align_full(SD_E, SD_X, D, NH, acts_e, acts_x, "permutation", body_keys=BODY)[0]])} |
| res = {} |
| for name, sd in rungs.items(): |
| t_e, n_e = ev_np(sd, bl_e_e) |
| t_x, n_x = ev_np(sd, bl_x_e) |
| res[name] = { |
| "eng": {"nats_per_byte": t_e / by_e_e, "nats_per_token": t_e / n_e}, |
| "x": {"nats_per_byte": t_x / by_x_e, "nats_per_token": t_x / n_x}, |
| "delta_floor_eng": t_e / by_e_e - PARENT_ENG["nats_per_byte"], |
| "delta_floor_x": t_x / by_x_e - min(parent_x["nats_per_byte"], eng_on_x["nats_per_byte"]), |
| } |
| res[name]["delta_floor_mean"] = 0.5 * (res[name]["delta_floor_eng"] + res[name]["delta_floor_x"]) |
| for name in res: |
| res[name]["delta_vs_naive_mean"] = res[name]["delta_floor_mean"] - res["M0_naive_avg"]["delta_floor_mean"] |
|
|
| r = {"set": "set4_goldfish", "lang": fcode, "repo_a": ENG_REPO, "repo_b": repo, |
| "corpus": "flores200_devtest", "n_sent": A.n_sent, |
| "metric": "nats_per_utf8_byte (likelihood, NOT benchmark accuracy)", |
| "parents": {"eng_on_eng": PARENT_ENG, "x_on_x": parent_x, "eng_on_x": eng_on_x}, |
| "floor_eng": PARENT_ENG["nats_per_byte"], |
| "floor_x": min(parent_x["nats_per_byte"], eng_on_x["nats_per_byte"]), |
| "align_info": {"perm": ip, "orth": io, "perm_forced": ipf, "orth_forced": iof}, "predictors": p, "rungs": res} |
|
|
| |
| def ev_mean(sd): |
| t_e, _ = ev_np(sd, bl_e_e); t_x, _ = ev_np(sd, bl_x_e) |
| return 0.5 * (t_e / by_e_e + t_x / by_x_e) |
| try: |
| bn = EV.merge_barrier(SD_E, SD_X, ev_mean, n=A.barrier_n) |
| r["barrier_naive"] = {"barrier": bn["barrier"], "losses": list(map(float, bn["losses"]))} |
| bp = EV.merge_barrier(SD_E, sdp, ev_mean, n=A.barrier_n) |
| r["barrier_perm"] = {"barrier": bp["barrier"], "losses": list(map(float, bp["losses"]))} |
| except Exception as e: |
| log("barrier failed", e) |
|
|
| r["secs"] = time.time() - t0 |
| fh.write(json.dumps(r) + "\n"); fh.flush() |
| log(f" {fcode}: M0 dfloor_mean={res['M0_naive_avg']['delta_floor_mean']:+.4f} " |
| f"M1a={res['M1a_vocab_avg']['delta_floor_mean']:+.4f} " |
| f"M1b_perm={res['M1b_vocab_perm_avg']['delta_floor_mean']:+.4f} " |
| f"M1c_orth={res['M1c_vocab_orth_avg']['delta_floor_mean']:+.4f} ({r['secs']:.0f}s)") |
| del rungs, sdp, sdo, sdpf, sdof, sd_emb, sd_emb2, SD_X, SD_X_V; gc.collect() |
| fh.close() |
| log("DONE set4") |
|
|