Upload code/gpt2_align.py with huggingface_hub
Browse files- code/gpt2_align.py +125 -0
code/gpt2_align.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""GPT-2 (Conv1D, transposed-weight) symmetry factors. mergeschool's generic aligners assume the
|
| 2 |
+
row-major nn.Linear convention, so the residual/MLP/head maps are written out explicitly here for
|
| 3 |
+
the goldfish family. Every factor below is exact (LayerNorm is permutation-equivariant; GELU is
|
| 4 |
+
elementwise; GPT-2 uses learned positional embeddings so head permutation is exact)."""
|
| 5 |
+
import numpy as np
|
| 6 |
+
import sys
|
| 7 |
+
sys.path.insert(0, "/root/mergeability/src")
|
| 8 |
+
from mergeschool.core import alignment as AL
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def _pre(n):
|
| 12 |
+
p = n.split(".")
|
| 13 |
+
for i, x in enumerate(p):
|
| 14 |
+
if x.isdigit():
|
| 15 |
+
return ".".join(p[:i + 1]) + "."
|
| 16 |
+
return None
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def layers_of(sd):
|
| 20 |
+
return sorted({int(k.split(".")[2]) for k in sd if k.startswith("transformer.h.")})
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
# --------------------------------------------------------------- residual basis (d)
|
| 24 |
+
def apply_resid(sd, d, perm=None, R=None):
|
| 25 |
+
"""Carry sd into another model's residual basis. perm: index array (exact). R: (d,d) orthogonal
|
| 26 |
+
with acts_B @ R ~ acts_A (exact up to LayerNorm's elementwise scale, which is left alone)."""
|
| 27 |
+
out = {}
|
| 28 |
+
P = (lambda W, ax: np.take(W, perm, axis=ax)) if perm is not None else None
|
| 29 |
+
for name, W in sd.items():
|
| 30 |
+
W = np.asarray(W, float)
|
| 31 |
+
n = name
|
| 32 |
+
try:
|
| 33 |
+
if n.endswith("wte.weight") or n.endswith("wpe.weight") or n.endswith("lm_head.weight"):
|
| 34 |
+
out[n] = P(W, 1) if P else W @ R
|
| 35 |
+
elif ("ln_" in n or n.endswith("ln_f.weight") or n.endswith("ln_f.bias")) and W.ndim == 1:
|
| 36 |
+
out[n] = P(W, 0) if P else W # norm affine: exact under perm, kept under R
|
| 37 |
+
elif n.endswith("attn.c_attn.weight") or n.endswith("mlp.c_fc.weight"):
|
| 38 |
+
out[n] = P(W, 0) if P else R.T @ W # (d, out): residual is the INPUT axis
|
| 39 |
+
elif n.endswith("attn.c_proj.weight") or n.endswith("mlp.c_proj.weight"):
|
| 40 |
+
out[n] = P(W, 1) if P else W @ R # (in, d): residual is the OUTPUT axis
|
| 41 |
+
elif (n.endswith("attn.c_proj.bias") or n.endswith("mlp.c_proj.bias")) and W.shape[0] == d:
|
| 42 |
+
out[n] = P(W, 0) if P else W @ R
|
| 43 |
+
else:
|
| 44 |
+
out[n] = W
|
| 45 |
+
except Exception:
|
| 46 |
+
out[n] = W
|
| 47 |
+
return out
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
# --------------------------------------------------------------- free MLP hidden axis (4d)
|
| 51 |
+
def mlp_match(sd_a, sd_b):
|
| 52 |
+
perms = {}
|
| 53 |
+
for L in layers_of(sd_a):
|
| 54 |
+
fa, fb = f"transformer.h.{L}.mlp.c_fc.weight", f"transformer.h.{L}.mlp.c_proj.weight"
|
| 55 |
+
A = np.asarray(sd_a[fa], float).T @ np.asarray(sd_b[fa], float) # (4d,d)@(d,4d)
|
| 56 |
+
A = A + np.asarray(sd_a[fb], float) @ np.asarray(sd_b[fb], float).T
|
| 57 |
+
perms[L] = AL._assignment(A)
|
| 58 |
+
return perms
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def apply_mlp(sd, perms):
|
| 62 |
+
out = dict(sd)
|
| 63 |
+
for L, q in perms.items():
|
| 64 |
+
out[f"transformer.h.{L}.mlp.c_fc.weight"] = np.asarray(sd[f"transformer.h.{L}.mlp.c_fc.weight"], float)[:, q]
|
| 65 |
+
out[f"transformer.h.{L}.mlp.c_fc.bias"] = np.asarray(sd[f"transformer.h.{L}.mlp.c_fc.bias"], float)[q]
|
| 66 |
+
out[f"transformer.h.{L}.mlp.c_proj.weight"] = np.asarray(sd[f"transformer.h.{L}.mlp.c_proj.weight"], float)[q]
|
| 67 |
+
return out
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
# --------------------------------------------------------------- attention heads
|
| 71 |
+
def head_match(sd_a, sd_b, d, nh):
|
| 72 |
+
hd, perms = d // nh, {}
|
| 73 |
+
for L in layers_of(sd_a):
|
| 74 |
+
ca, cp = f"transformer.h.{L}.attn.c_attn.weight", f"transformer.h.{L}.attn.c_proj.weight"
|
| 75 |
+
gain = np.zeros((nh, nh))
|
| 76 |
+
for blk in range(3): # q | k | v, each (d, d)
|
| 77 |
+
A = np.asarray(sd_a[ca], float)[:, blk * d:(blk + 1) * d].reshape(d, nh, hd)
|
| 78 |
+
B = np.asarray(sd_b[ca], float)[:, blk * d:(blk + 1) * d].reshape(d, nh, hd)
|
| 79 |
+
gain += np.einsum("xiy,xjy->ij", A, B)
|
| 80 |
+
A = np.asarray(sd_a[cp], float).reshape(nh, hd, d)
|
| 81 |
+
B = np.asarray(sd_b[cp], float).reshape(nh, hd, d)
|
| 82 |
+
gain += np.einsum("ixy,jxy->ij", A, B)
|
| 83 |
+
perms[L] = AL._assignment(gain)
|
| 84 |
+
return perms
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def apply_head(sd, perms, d, nh):
|
| 88 |
+
hd, out = d // nh, dict(sd)
|
| 89 |
+
for L, h in perms.items():
|
| 90 |
+
ca, cb = f"transformer.h.{L}.attn.c_attn.weight", f"transformer.h.{L}.attn.c_attn.bias"
|
| 91 |
+
cp = f"transformer.h.{L}.attn.c_proj.weight"
|
| 92 |
+
W = np.asarray(sd[ca], float).copy()
|
| 93 |
+
Bv = np.asarray(sd[cb], float).copy()
|
| 94 |
+
for blk in range(3):
|
| 95 |
+
s = slice(blk * d, (blk + 1) * d)
|
| 96 |
+
W[:, s] = W[:, s].reshape(d, nh, hd)[:, h].reshape(d, d)
|
| 97 |
+
Bv[s] = Bv[s].reshape(nh, hd)[h].reshape(d)
|
| 98 |
+
out[ca], out[cb] = W, Bv
|
| 99 |
+
out[cp] = np.asarray(sd[cp], float).reshape(nh, hd, d)[h].reshape(d, d)
|
| 100 |
+
return out
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
# --------------------------------------------------------------- composition with accept-each
|
| 104 |
+
def align_full(sd_a, sd_b, d, nh, acts_a=None, acts_b=None, method="permutation", body_keys=None,
|
| 105 |
+
accept_each=True):
|
| 106 |
+
info = {"residual": False, "mlp": 0, "heads": 0, "rejected": []}
|
| 107 |
+
sd = dict(sd_b)
|
| 108 |
+
|
| 109 |
+
def keep(cand, tag):
|
| 110 |
+
if not accept_each:
|
| 111 |
+
return cand, True
|
| 112 |
+
if AL.block_normalised_distance(sd_a, cand, body_keys) <= AL.block_normalised_distance(sd_a, sd, body_keys):
|
| 113 |
+
return cand, True
|
| 114 |
+
info["rejected"].append(tag)
|
| 115 |
+
return sd, False
|
| 116 |
+
|
| 117 |
+
if acts_a is not None and acts_b is not None:
|
| 118 |
+
kind, obj = AL.residual_basis_map(acts_a, acts_b, method=method)
|
| 119 |
+
cand = apply_resid(sd, d, perm=(obj if kind == "perm" else None), R=(obj if kind == "R" else None))
|
| 120 |
+
sd, ok = keep(cand, "residual"); info["residual"] = ok
|
| 121 |
+
mp = mlp_match(sd_a, sd)
|
| 122 |
+
sd, ok = keep(apply_mlp(sd, mp), "mlp"); info["mlp"] = len(mp) if ok else 0
|
| 123 |
+
hp = head_match(sd_a, sd, d, nh)
|
| 124 |
+
sd, ok = keep(apply_head(sd, hp, d, nh), "heads"); info["heads"] = len(hp) if ok else 0
|
| 125 |
+
return sd, info
|