Download code/set1_corpus_robustness.py from Cross-Mergeability/compose-audit: direct link, hf CLI and curl.
- Browser
- Download file 5.45 kB
-
https://huggingface.co/datasets/Cross-Mergeability/compose-audit/resolve/main/code/set1_corpus_robustness.py
- Command line
-
hf download hf://datasets/Cross-Mergeability/compose-audit/code/set1_corpus_robustness.py
-
curl -L -o set1_corpus_robustness.py https://huggingface.co/datasets/Cross-Mergeability/compose-audit/resolve/main/code/set1_corpus_robustness.py
5.45 kB
| """Robustness: is SET 1's Δfloor an artifact of the held-out corpus? | |
| The main SET 1 tables score on FLORES-200 English devtest, which is genuinely held out from | |
| PolyPythia training but out-of-domain for the Pile. A reviewer's first objection is that the merge | |
| penalty is inflated by domain shift. This re-scores a subset of the same pairs and the same merges on | |
| a **Pile sample** (`NeelNanda/pile-10k`, in-distribution for Pythia) and on **WikiText-103 | |
| validation**, and reports the three side by side.""" | |
| import os, sys, json, time, itertools, argparse, gc | |
| sys.path.insert(0, "/root/compose-audit") | |
| from common import * | |
| from transformers import AutoModelForCausalLM, AutoTokenizer | |
| from datasets import load_dataset | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--size", default="14m") | |
| ap.add_argument("--seeds", default="1,2,3,4,5,6") | |
| ap.add_argument("--blocks", type=int, default=48) | |
| ap.add_argument("--bs", type=int, default=16) | |
| ap.add_argument("--acts_rows", type=int, default=2048) | |
| A = ap.parse_args() | |
| SEEDS = [int(s) for s in A.seeds.split(",")] | |
| OUT = f"/root/compose-audit/results/corpus_{A.size}.jsonl" | |
| DEV = "cuda" | |
| def log(*a): print(f"[{time.strftime('%H:%M:%S')}]", *a, flush=True) | |
| 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) | |
| 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(np.einsum("ixy,jxy->ij", Aq, Bq) + np.einsum("xiy,xjy->ij", Ad, Bd)) | |
| return perms | |
| def neox_apply_head(sd, perms, d, nh): | |
| hd, o = 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" | |
| o[qk] = np.asarray(sd[qk], float).reshape(nh, 3 * hd, d)[h].reshape(3 * d, d) | |
| if qb in sd: o[qb] = np.asarray(sd[qb], float).reshape(nh, 3 * hd)[h].reshape(3 * d) | |
| o[de] = np.asarray(sd[de], float).reshape(d, nh, hd)[:, h].reshape(d, d) | |
| return o | |
| def align_perm(sd_a, sd_b, d, aa, ab, nh, nl): | |
| sd, _ = AL.align_weights_full(sd_a, sd_b, d, acts_a=aa, acts_b=ab, n_heads=None, | |
| method="permutation", 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 | |
| tok = AutoTokenizer.from_pretrained(f"EleutherAI/pythia-{A.size}") | |
| CORPORA = {} | |
| CORPORA["flores_eng"] = make_blocks(tok, flores_lines("eng_Latn"), 512, A.blocks) | |
| try: | |
| d = load_dataset("NeelNanda/pile-10k", split="train") | |
| CORPORA["pile_10k"] = make_blocks(tok, [x for x in d["text"][:400]], 512, A.blocks) | |
| except Exception as e: | |
| log("pile load failed", type(e).__name__, str(e)[:150]) | |
| try: | |
| d = load_dataset("Salesforce/wikitext", "wikitext-103-raw-v1", split="validation") | |
| CORPORA["wikitext103_val"] = make_blocks(tok, [x for x in d["text"] if x.strip()][:4000], 512, A.blocks) | |
| except Exception as e: | |
| log("wikitext load failed", type(e).__name__, str(e)[:150]) | |
| log("corpora:", {k: tuple(v.shape) for k, v in CORPORA.items()}) | |
| 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 ev_all(sd): | |
| sd_load(shell, sd, DEV) | |
| return {k: nll_nats(shell, b, DEV, bs=A.bs) for k, b in CORPORA.items()} | |
| SDS, ACTS, PAR = {}, {}, {} | |
| 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, CORPORA["flores_eng"], DEV, n_rows=A.acts_rows, bs=A.bs) | |
| del m; torch.cuda.empty_cache() | |
| PAR[s] = ev_all(SDS[s]) | |
| log(f" seed{s} {PAR[s]}") | |
| 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() | |
| sbp = align_perm(SDS[a], SDS[b], D, ACTS[a], ACTS[b], NH, NL) | |
| rungs = {"M0_naive_avg": MG.average([SDS[a], SDS[b]]), "M1_perm_avg": MG.average([SDS[a], sbp])} | |
| res = {} | |
| for k, sd in rungs.items(): | |
| nl_ = ev_all(sd) | |
| res[k] = {c: {"nll": v, "delta_floor": v - min(PAR[a][c], PAR[b][c])} for c, v in nl_.items()} | |
| r = {"set": "set1_corpus_robustness", "size": A.size, "pair": [a, b], | |
| "parent_nll": {"a": PAR[a], "b": PAR[b]}, "rungs": res, "secs": time.time() - t0} | |
| fh.write(json.dumps(r) + "\n"); fh.flush() | |
| log(f"pair {a},{b} " + " | ".join( | |
| f"{c}: M0 {res['M0_naive_avg'][c]['delta_floor']:+.2f} M1 {res['M1_perm_avg'][c]['delta_floor']:+.2f}" | |
| for c in CORPORA) + f" ({r['secs']:.0f}s)") | |
| del rungs, sbp; gc.collect() | |
| fh.close() | |
| log("DONE corpus", A.size) | |