compose-audit / code /set1_repair.py
suchirsalhan's picture
compose-audit refresh 2026-08-26 21:04 UTC
47a719e verified
Raw
History Blame Contribute Delete
9.64 kB
"""Did we try hard enough to make merging work?
The obvious objection to SET 1's negative result is that a plain average of aligned weights is a weak
merge: averaging two networks halves the variance of every pre-activation, and REPAIR (Jordan et al.,
ICLR 2023) shows that restoring those first- and second-order statistics recovers most of the
remaining barrier on vision nets. This adds that rung, training-free: after the permutation-aligned
average, walk the layers in order and affine-correct each Linear's pre-activations so their per-unit
mean and std match the average of the two parents' own statistics on the same corpus.
Rungs: M0 naive · M1 permutation-aligned average · M4 = M1 + REPAIR · M5 = M0 + REPAIR.
Metrics: Δfloor in nats/token (FLORES-200 eng devtest) AND BLiMP accuracy, on the same merges."""
import os, sys, json, time, glob, itertools, argparse, gc, csv
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("--blocks", type=int, default=48)
ap.add_argument("--bs", type=int, default=16)
ap.add_argument("--n_per_paradigm", type=int, default=200)
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/repair_{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)
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_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
# ------------------------------------------------------------------ REPAIR
TARGETS = ("mlp.dense_h_to_4h", "attention.query_key_value")
@torch.no_grad()
def preact_stats(model, blocks, dev, bs, nl):
"""{(layer, target): (mean, std)} of each Linear's OUTPUT (= pre-activation), per unit."""
acc = {}
hs = []
def mk(key):
def hook(mod, inp, out):
o = out.detach().float().reshape(-1, out.shape[-1])
s = acc.setdefault(key, [0.0, None, None])
s[0] += o.shape[0]
s[1] = o.sum(0) if s[1] is None else s[1] + o.sum(0)
s[2] = (o * o).sum(0) if s[2] is None else s[2] + (o * o).sum(0)
return hook
for L in range(nl):
blk = model.gpt_neox.layers[L]
hs.append(blk.mlp.dense_h_to_4h.register_forward_hook(mk((L, "mlp.dense_h_to_4h"))))
hs.append(blk.attention.query_key_value.register_forward_hook(mk((L, "attention.query_key_value"))))
for i in range(0, blocks.shape[0], bs):
model(blocks[i:i + bs].to(dev))
for h in hs: h.remove()
out = {}
for k, (n, s1, s2) in acc.items():
m = s1 / n
v = (s2 / n - m * m).clamp_min(1e-12)
out[k] = (m.cpu().numpy().astype(np.float64), v.sqrt().cpu().numpy().astype(np.float64))
return out
def repair(sd_merged, stats_a, stats_b, shell, blocks, dev, bs, nl):
"""Walk layers in order; after fixing layers < L the inputs to layer L are already corrected, so
layer L's own statistics are re-measured before it is corrected. Affine correction on the
Linear's weight/bias, so the model stays exactly a model of the same architecture."""
sd = {k: np.array(v, dtype=np.float64, copy=True) for k, v in sd_merged.items()}
for L in range(nl):
sd_load(shell, sd, dev)
cur = preact_stats(shell, blocks, dev, bs, nl)
for t in TARGETS:
mu_t = 0.5 * (stats_a[(L, t)][0] + stats_b[(L, t)][0])
sd_t = 0.5 * (stats_a[(L, t)][1] + stats_b[(L, t)][1])
mu_m, sd_m = cur[(L, t)]
g = sd_t / np.maximum(sd_m, 1e-8)
wk, bk = f"gpt_neox.layers.{L}.{t}.weight", f"gpt_neox.layers.{L}.{t}.bias"
sd[wk] = sd[wk] * g[:, None]
sd[bk] = (sd[bk] - mu_m) * g + mu_t
return sd
# ------------------------------------------------------------------ BLiMP
def load_blimp(n_per):
out = []
for d in sorted(glob.glob(BLIMP + "*/")):
f = glob.glob(d + "*.parquet")
if not f: continue
t = pq.read_table(f[0]).to_pydict()
out.append((os.path.basename(d.rstrip("/")), t["sentence_good"][:n_per], t["sentence_bad"][:n_per]))
return out
tok = AutoTokenizer.from_pretrained(f"EleutherAI/pythia-{A.size}")
if tok.pad_token is None: tok.pad_token = tok.eos_token
def enc(sents, maxlen=48):
e = tok(sents, return_tensors="pt", padding=True, truncation=True, max_length=maxlen)
return e["input_ids"], e["attention_mask"]
ENC = [(n, enc(g), enc(b)) for n, g, b in load_blimp(A.n_per_paradigm)]
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
log(f"size={A.size} d={D} heads={NH} layers={NL} blimp_paradigms={len(ENC)}")
@torch.no_grad()
def bscore(ids, am):
o = []
for i in range(0, ids.shape[0], 128):
x, m = ids[i:i + 128].to(DEV), am[i:i + 128].to(DEV)
lp = torch.log_softmax(shell(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()
def evaluate(sd):
sd_load(shell, sd, DEV)
nll = nll_nats(shell, blocks, DEV, bs=A.bs)
cor = tot = 0
for name, (gi, gm), (bi, bm) in ENC:
sg, sb = bscore(gi, gm), bscore(bi, bm)
cor += int((sg > sb).sum()); tot += len(sg)
return nll, cor / tot
SDS, ACTS, PAR, STATS = {}, {}, {}, {}
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=A.bs)
del m; torch.cuda.empty_cache()
PAR[s] = evaluate(SDS[s])
log(f" seed{s} nll={PAR[s][0]:.4f} blimp={PAR[s][1]:.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_perm(sa, sb, D, ACTS[a], ACTS[b], NH, NL)
sd_load(shell, sa, DEV); st_a = preact_stats(shell, blocks, DEV, A.bs, NL)
sd_load(shell, sbp, DEV); st_b = preact_stats(shell, blocks, DEV, A.bs, NL)
sd_load(shell, sb, DEV); st_braw = preact_stats(shell, blocks, DEV, A.bs, NL)
rungs = {"M0_naive_avg": MG.average([sa, sb]), "M1_perm_avg": MG.average([sa, sbp])}
rungs["M4_perm_repair"] = repair(rungs["M1_perm_avg"], st_a, st_b, shell, blocks, DEV, A.bs, NL)
rungs["M5_naive_repair"] = repair(rungs["M0_naive_avg"], st_a, st_braw, shell, blocks, DEV, A.bs, NL)
floor = min(PAR[a][0], PAR[b][0]); ceil = max(PAR[a][1], PAR[b][1])
res = {}
for k, sd in rungs.items():
nll, acc = evaluate(sd)
res[k] = {"nll": nll, "delta_floor": nll - floor, "blimp_acc": acc,
"blimp_delta_vs_ceiling": acc - ceil}
r = {"set": "set1_repair", "size": A.size, "pair": [a, b], "floor": floor, "blimp_ceiling": ceil,
"parent_nll": {"a": PAR[a][0], "b": PAR[b][0]},
"parent_blimp": {"a": PAR[a][1], "b": PAR[b][1]}, "rungs": res, "secs": time.time() - t0}
fh.write(json.dumps(r) + "\n"); fh.flush()
log(f"pair {a},{b} floor={floor:.2f}/ceil={ceil:.3f} | " +
" | ".join(f"{k}: {v['delta_floor']:+.2f}n {v['blimp_acc']:.3f}" for k, v in res.items()) +
f" ({r['secs']:.0f}s)")
del rungs, sbp; gc.collect()
fh.close()
log("DONE repair", A.size)