| """ACCURACY, not likelihood: does the Δfloor rescue transfer to BLiMP? |
| |
| The audit's sharpest point is that "recovery is not success" -- a likelihood rescue has not been |
| shown to transfer to benchmark accuracy. PolyPythia parents are English LMs, so BLiMP is directly |
| applicable to SET 1's merges. Scoring: sum log p over the sentence (all tokens after the first); |
| a paradigm item is correct when the grammatical sentence scores higher. Chance = 50%.""" |
| import os, sys, json, time, glob, itertools, argparse, gc |
| sys.path.insert(0, "/root/compose-audit") |
| from common import * |
| from transformers import AutoModelForCausalLM, AutoTokenizer |
| import pyarrow.parquet as pq |
|
|
| ap = argparse.ArgumentParser() |
| ap.add_argument("--size", default="14m") |
| ap.add_argument("--seeds", default="1,2,3,4,5,6,7,8,9") |
| ap.add_argument("--n_per_paradigm", type=int, default=200) |
| ap.add_argument("--bs", type=int, default=128) |
| ap.add_argument("--acts_rows", type=int, default=2048) |
| ap.add_argument("--tag", default="blimp") |
| ap.add_argument("--blocks", type=int, default=48) |
| A = ap.parse_args() |
| SEEDS = [int(s) for s in A.seeds.split(",")] |
| OUT = f"/root/compose-audit/results/{A.tag}_{A.size}.jsonl" |
| DEV = "cuda" |
| BLIMP = glob.glob("/root/hf_cache_brainalign/hub/datasets--nyu-mll--blimp/snapshots/*/")[0] |
|
|
|
|
| def log(*a): |
| print(f"[{time.strftime('%H:%M:%S')}]", *a, flush=True) |
|
|
|
|
| |
| import importlib.util |
| spec = importlib.util.spec_from_file_location("s1", "/root/compose-audit/set1_polypythia.py") |
|
|
| def neox_head_match(sd_a, sd_b, d, nh, nl): |
| hd, perms = d // nh, {} |
| for L in range(nl): |
| qk = f"gpt_neox.layers.{L}.attention.query_key_value.weight" |
| de = f"gpt_neox.layers.{L}.attention.dense.weight" |
| if qk not in sd_a: continue |
| Aq = np.asarray(sd_a[qk], float).reshape(nh, 3 * hd, d) |
| Bq = np.asarray(sd_b[qk], float).reshape(nh, 3 * hd, d) |
| g = np.einsum("ixy,jxy->ij", Aq, Bq) |
| Ad = np.asarray(sd_a[de], float).reshape(d, nh, hd) |
| Bd = np.asarray(sd_b[de], float).reshape(d, nh, hd) |
| perms[L] = AL._assignment(g + np.einsum("xiy,xjy->ij", Ad, Bd)) |
| return perms |
|
|
|
|
| def neox_apply_head(sd, perms, d, nh): |
| hd, out = d // nh, dict(sd) |
| for L, h in perms.items(): |
| qk = f"gpt_neox.layers.{L}.attention.query_key_value.weight" |
| qb = f"gpt_neox.layers.{L}.attention.query_key_value.bias" |
| de = f"gpt_neox.layers.{L}.attention.dense.weight" |
| out[qk] = np.asarray(sd[qk], float).reshape(nh, 3 * hd, d)[h].reshape(3 * d, d) |
| if qb in sd: out[qb] = np.asarray(sd[qb], float).reshape(nh, 3 * hd)[h].reshape(3 * d) |
| out[de] = np.asarray(sd[de], float).reshape(d, nh, hd)[:, h].reshape(d, d) |
| return out |
|
|
|
|
| def align_full(sd_a, sd_b, d, aa, ab, nh, nl, method): |
| sd, info = AL.align_weights_full(sd_a, sd_b, d, acts_a=aa, acts_b=ab, n_heads=None, |
| method=method, strict=True, accept_each=True) |
| hp = neox_head_match(sd_a, sd, d, nh, nl) |
| if hp: |
| cand = neox_apply_head(sd, hp, d, nh) |
| if AL.block_normalised_distance(sd_a, cand) <= AL.block_normalised_distance(sd_a, sd): |
| sd = cand |
| return sd |
|
|
|
|
| |
| def load_blimp(tok, n_per): |
| items = [] |
| for d in sorted(glob.glob(BLIMP + "*/")): |
| name = os.path.basename(d.rstrip("/")) |
| f = glob.glob(d + "*.parquet") |
| if not f: continue |
| t = pq.read_table(f[0]).to_pydict() |
| good, bad = t["sentence_good"][:n_per], t["sentence_bad"][:n_per] |
| items.append((name, good, bad)) |
| return items |
|
|
|
|
| def encode(tok, sents, maxlen=48): |
| enc = tok(sents, return_tensors="pt", padding=True, truncation=True, max_length=maxlen) |
| return enc["input_ids"], enc["attention_mask"] |
|
|
|
|
| @torch.no_grad() |
| def score(model, ids, am, dev, bs=128): |
| 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) |
| tgt = x[:, 1:] |
| tokl = lp.gather(-1, tgt.unsqueeze(-1)).squeeze(-1) * m[:, 1:].float() |
| out.append(tokl.sum(1).cpu()) |
| return torch.cat(out).numpy() |
|
|
|
|
| tok = AutoTokenizer.from_pretrained(f"EleutherAI/pythia-{A.size}") |
| if tok.pad_token is None: tok.pad_token = tok.eos_token |
| PARA = load_blimp(tok, A.n_per_paradigm) |
| log(f"BLiMP paradigms={len(PARA)} items/paradigm={len(PARA[0][1])}") |
| ENC = [(n, encode(tok, g), encode(tok, b)) for n, g, b in PARA] |
|
|
| lines = flores_lines("eng_Latn") |
| blocks = make_blocks(tok, lines, block=512, max_blocks=A.blocks) |
| shell = AutoModelForCausalLM.from_pretrained(f"EleutherAI/pythia-{A.size}-seed{SEEDS[0]}", |
| dtype=torch.float32).to(DEV).eval() |
| cfg = shell.config |
| D, NH, NL = cfg.hidden_size, cfg.num_attention_heads, cfg.num_hidden_layers |
|
|
|
|
| def blimp_acc(sd): |
| sd_load(shell, sd, DEV) |
| per, tot, cor = {}, 0, 0 |
| for name, (gi, gm), (bi, bm) in ENC: |
| sg = score(shell, gi, gm, DEV, bs=A.bs) |
| sb = score(shell, bi, bm, DEV, bs=A.bs) |
| c = int((sg > sb).sum()); per[name] = c / len(sg); cor += c; tot += len(sg) |
| return cor / tot, per |
|
|
|
|
| SDS, ACTS, PACC = {}, {}, {} |
| for s in SEEDS: |
| m = AutoModelForCausalLM.from_pretrained(f"EleutherAI/pythia-{A.size}-seed{s}", dtype=torch.float32).to(DEV).eval() |
| SDS[s] = sd_np(m); ACTS[s] = capture_acts(m, blocks, DEV, n_rows=A.acts_rows, bs=16) |
| del m; torch.cuda.empty_cache() |
| a, _ = blimp_acc(SDS[s]); PACC[s] = a |
| log(f" seed{s} BLiMP={a:.4f}") |
|
|
| done = set() |
| if os.path.exists(OUT): |
| for l in open(OUT): |
| try: done.add(tuple(json.loads(l)["pair"])) |
| except Exception: pass |
| fh = open(OUT, "a") |
| for a, b in itertools.combinations(SEEDS, 2): |
| if (a, b) in done: continue |
| t0 = time.time() |
| sa, sb = SDS[a], SDS[b] |
| sbp = align_full(sa, sb, D, ACTS[a], ACTS[b], NH, NL, "permutation") |
| sbo = align_full(sa, sb, D, ACTS[a], ACTS[b], NH, NL, "orthogonal") |
| rungs = {"M0_naive_avg": MG.average([sa, sb]), "M1_perm_avg": MG.average([sa, sbp]), |
| "M1_orth_avg": MG.average([sa, sbo])} |
| res = {} |
| for k, sd in rungs.items(): |
| acc, per = blimp_acc(sd) |
| res[k] = {"blimp_acc": acc, "per_paradigm": per} |
| r = {"set": "set1_blimp", "size": A.size, "pair": [a, b], |
| "metric": "BLiMP accuracy (chance=0.5) -- ACCURACY, not likelihood", |
| "n_per_paradigm": A.n_per_paradigm, "n_paradigms": len(ENC), |
| "parent_acc": {"a": PACC[a], "b": PACC[b]}, "ceiling": max(PACC[a], PACC[b]), |
| "rungs": {k: {"blimp_acc": v["blimp_acc"], |
| "delta_vs_best_parent": v["blimp_acc"] - max(PACC[a], PACC[b])} for k, v in res.items()}, |
| "per_paradigm": {k: v["per_paradigm"] for k, v in res.items()}, |
| "secs": time.time() - t0} |
| fh.write(json.dumps(r) + "\n"); fh.flush() |
| log(f"pair {a},{b} ceil={r['ceiling']:.4f} M0={res['M0_naive_avg']['blimp_acc']:.4f} " |
| f"M1p={res['M1_perm_avg']['blimp_acc']:.4f} M1o={res['M1_orth_avg']['blimp_acc']:.4f} ({r['secs']:.0f}s)") |
| del rungs, sbp, sbo; gc.collect() |
| fh.close() |
| log("DONE blimp", A.size) |
|
|