File size: 4,891 Bytes
47a719e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 | """Sanity: is the alignment actually FUNCTION-PRESERVING?
Every M1 rung is only meaningful if g.th_B computes exactly what th_B computes. A permutation of the
residual basis, of the free MLP hidden axis and of the attention heads is exact in theory; a bug in
applying it produces a plausible-looking state dict whose merges are quietly garbage. This checks it
empirically on both substrates: evaluate the parent, then evaluate the aligned parent, and compare.
An orthogonal map is NOT expected to be exact (it does not commute with the elementwise LayerNorm
gain), so its drift is reported as a magnitude, not as a pass/fail."""
import sys, json, glob
sys.path.insert(0, "/root/compose-audit")
from common import *
import gpt2_align as G2
from transformers import AutoModelForCausalLM, AutoTokenizer
from mergeschool.core.models import load_hf
from set4_goldfish_lib import sent_acts
DEV = "cuda"
out = {}
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
# ---------------- SET 1 / GPTNeoX
tok = AutoTokenizer.from_pretrained("EleutherAI/pythia-14m")
blocks = make_blocks(tok, flores_lines("eng_Latn"), block=512, max_blocks=24)
ma = AutoModelForCausalLM.from_pretrained("EleutherAI/pythia-14m-seed1", dtype=torch.float32).to(DEV).eval()
mb = AutoModelForCausalLM.from_pretrained("EleutherAI/pythia-14m-seed2", dtype=torch.float32).to(DEV).eval()
D, NH, NL = ma.config.hidden_size, ma.config.num_attention_heads, ma.config.num_hidden_layers
sa, sb = sd_np(ma), sd_np(mb)
aa, ab = capture_acts(ma, blocks, DEV), capture_acts(mb, blocks, DEV)
base = nll_nats(mb, blocks, DEV, bs=16)
res = {}
for method in ("permutation", "orthogonal"):
sd, info = AL.align_weights_full(sa, sb, D, acts_a=aa, acts_b=ab, n_heads=None,
method=method, strict=True, accept_each=False)
sd_load(mb, sd, DEV); res[f"{method}_residual+mlp"] = nll_nats(mb, blocks, DEV, bs=16) - base
if method == "permutation":
hp = neox_head_match(sa, sd, D, NH, NL)
sd2 = neox_apply_head(sd, hp, D, NH)
sd_load(mb, sd2, DEV); res["permutation_full(+heads)"] = nll_nats(mb, blocks, DEV, bs=16) - base
sd_load(mb, sb, DEV)
out["set1_pythia14m"] = {"parent_nll": base, "nll_change_after_alignment": res}
print("SET1", json.dumps(out["set1_pythia14m"], indent=1))
del ma, mb; torch.cuda.empty_cache()
# ---------------- SET 4 / GPT-2 (Conv1D)
m_e, tok_e = load_hf("goldfish-models/eng_latn_1000mb", dtype=torch.float32, device=DEV); m_e.eval()
m_x, tok_x = load_hf("goldfish-models/nld_latn_1000mb", dtype=torch.float32, device=DEV); m_x.eval()
D2, NH2 = m_e.config.n_embd, m_e.config.n_head
lines_e = flores_lines("eng_Latn")[:300]; lines_x = flores_lines("nld_Latn")[:300]
ae = sent_acts(m_e, tok_e, lines_e, DEV); ax = sent_acts(m_x, tok_x, lines_x, DEV)
sde, sdx = sd_np(m_e), sd_np(m_x)
bl = make_blocks(tok_x, lines_x, block=512, max_blocks=16)
b0 = nll_nats(m_x, bl, DEV, bs=8)
res2 = {}
for tag, sd in (("perm_residual_only", G2.apply_resid(sdx, D2, perm=AL.residual_basis_map(ae, ax, "permutation")[1])),
("mlp_only", G2.apply_mlp(sdx, G2.mlp_match(sde, sdx))),
("heads_only", G2.apply_head(sdx, G2.head_match(sde, sdx, D2, NH2), D2, NH2)),
("perm_full", G2.align_full(sde, sdx, D2, NH2, ae, ax, "permutation", accept_each=False)[0]),
("orth_full", G2.align_full(sde, sdx, D2, NH2, ae, ax, "orthogonal", accept_each=False)[0])):
sd_load(m_x, sd, DEV); res2[tag] = nll_nats(m_x, bl, DEV, bs=8) - b0
out["set4_goldfish_nld"] = {"parent_nll": b0, "nll_change_after_alignment": res2}
print("SET4", json.dumps(out["set4_goldfish_nld"], indent=1))
json.dump(out, open("/root/compose-audit/results/alignment_health.json", "w"), indent=1)
|