| """GPT-2 (Conv1D, transposed-weight) symmetry factors. mergeschool's generic aligners assume the |
| row-major nn.Linear convention, so the residual/MLP/head maps are written out explicitly here for |
| the goldfish family. Every factor below is exact (LayerNorm is permutation-equivariant; GELU is |
| elementwise; GPT-2 uses learned positional embeddings so head permutation is exact).""" |
| import numpy as np |
| import sys |
| sys.path.insert(0, "/root/mergeability/src") |
| from mergeschool.core import alignment as AL |
|
|
|
|
| def _pre(n): |
| p = n.split(".") |
| for i, x in enumerate(p): |
| if x.isdigit(): |
| return ".".join(p[:i + 1]) + "." |
| return None |
|
|
|
|
| def layers_of(sd): |
| return sorted({int(k.split(".")[2]) for k in sd if k.startswith("transformer.h.")}) |
|
|
|
|
| |
| def apply_resid(sd, d, perm=None, R=None): |
| """Carry sd into another model's residual basis. perm: index array (exact). R: (d,d) orthogonal |
| with acts_B @ R ~ acts_A (exact up to LayerNorm's elementwise scale, which is left alone).""" |
| out = {} |
| P = (lambda W, ax: np.take(W, perm, axis=ax)) if perm is not None else None |
| for name, W in sd.items(): |
| W = np.asarray(W, float) |
| n = name |
| try: |
| if n.endswith("wte.weight") or n.endswith("wpe.weight") or n.endswith("lm_head.weight"): |
| out[n] = P(W, 1) if P else W @ R |
| elif ("ln_" in n or n.endswith("ln_f.weight") or n.endswith("ln_f.bias")) and W.ndim == 1: |
| out[n] = P(W, 0) if P else W |
| elif n.endswith("attn.c_attn.weight") or n.endswith("mlp.c_fc.weight"): |
| out[n] = P(W, 0) if P else R.T @ W |
| elif n.endswith("attn.c_proj.weight") or n.endswith("mlp.c_proj.weight"): |
| out[n] = P(W, 1) if P else W @ R |
| elif (n.endswith("attn.c_proj.bias") or n.endswith("mlp.c_proj.bias")) and W.shape[0] == d: |
| out[n] = P(W, 0) if P else W @ R |
| else: |
| out[n] = W |
| except Exception: |
| out[n] = W |
| return out |
|
|
|
|
| |
| def mlp_match(sd_a, sd_b): |
| perms = {} |
| for L in layers_of(sd_a): |
| fa, fb = f"transformer.h.{L}.mlp.c_fc.weight", f"transformer.h.{L}.mlp.c_proj.weight" |
| A = np.asarray(sd_a[fa], float).T @ np.asarray(sd_b[fa], float) |
| A = A + np.asarray(sd_a[fb], float) @ np.asarray(sd_b[fb], float).T |
| perms[L] = AL._assignment(A) |
| return perms |
|
|
|
|
| def apply_mlp(sd, perms): |
| out = dict(sd) |
| for L, q in perms.items(): |
| out[f"transformer.h.{L}.mlp.c_fc.weight"] = np.asarray(sd[f"transformer.h.{L}.mlp.c_fc.weight"], float)[:, q] |
| out[f"transformer.h.{L}.mlp.c_fc.bias"] = np.asarray(sd[f"transformer.h.{L}.mlp.c_fc.bias"], float)[q] |
| out[f"transformer.h.{L}.mlp.c_proj.weight"] = np.asarray(sd[f"transformer.h.{L}.mlp.c_proj.weight"], float)[q] |
| return out |
|
|
|
|
| |
| def head_match(sd_a, sd_b, d, nh): |
| hd, perms = d // nh, {} |
| for L in layers_of(sd_a): |
| ca, cp = f"transformer.h.{L}.attn.c_attn.weight", f"transformer.h.{L}.attn.c_proj.weight" |
| gain = np.zeros((nh, nh)) |
| for blk in range(3): |
| A = np.asarray(sd_a[ca], float)[:, blk * d:(blk + 1) * d].reshape(d, nh, hd) |
| B = np.asarray(sd_b[ca], float)[:, blk * d:(blk + 1) * d].reshape(d, nh, hd) |
| gain += np.einsum("xiy,xjy->ij", A, B) |
| A = np.asarray(sd_a[cp], float).reshape(nh, hd, d) |
| B = np.asarray(sd_b[cp], float).reshape(nh, hd, d) |
| gain += np.einsum("ixy,jxy->ij", A, B) |
| perms[L] = AL._assignment(gain) |
| return perms |
|
|
|
|
| def apply_head(sd, perms, d, nh): |
| hd, out = d // nh, dict(sd) |
| for L, h in perms.items(): |
| ca, cb = f"transformer.h.{L}.attn.c_attn.weight", f"transformer.h.{L}.attn.c_attn.bias" |
| cp = f"transformer.h.{L}.attn.c_proj.weight" |
| W = np.asarray(sd[ca], float).copy() |
| Bv = np.asarray(sd[cb], float).copy() |
| for blk in range(3): |
| s = slice(blk * d, (blk + 1) * d) |
| W[:, s] = W[:, s].reshape(d, nh, hd)[:, h].reshape(d, d) |
| Bv[s] = Bv[s].reshape(nh, hd)[h].reshape(d) |
| out[ca], out[cb] = W, Bv |
| out[cp] = np.asarray(sd[cp], float).reshape(nh, hd, d)[h].reshape(d, d) |
| return out |
|
|
|
|
| |
| def align_full(sd_a, sd_b, d, nh, acts_a=None, acts_b=None, method="permutation", body_keys=None, |
| accept_each=True): |
| info = {"residual": False, "mlp": 0, "heads": 0, "rejected": []} |
| sd = dict(sd_b) |
|
|
| def keep(cand, tag): |
| if not accept_each: |
| return cand, True |
| if AL.block_normalised_distance(sd_a, cand, body_keys) <= AL.block_normalised_distance(sd_a, sd, body_keys): |
| return cand, True |
| info["rejected"].append(tag) |
| return sd, False |
|
|
| if acts_a is not None and acts_b is not None: |
| kind, obj = AL.residual_basis_map(acts_a, acts_b, method=method) |
| cand = apply_resid(sd, d, perm=(obj if kind == "perm" else None), R=(obj if kind == "R" else None)) |
| sd, ok = keep(cand, "residual"); info["residual"] = ok |
| mp = mlp_match(sd_a, sd) |
| sd, ok = keep(apply_mlp(sd, mp), "mlp"); info["mlp"] = len(mp) if ok else 0 |
| hp = head_match(sd_a, sd, d, nh) |
| sd, ok = keep(apply_head(sd, hp, d, nh), "heads"); info["heads"] = len(hp) if ok else 0 |
| return sd, info |
|
|
|
|
| |
| def emb_procrustes(sd_a, sd_b, tok_a, tok_b, key="transformer.wte.weight", max_anchors=None): |
| """Fit the residual-basis rotation from the EMBEDDING ROWS of shared surface forms, data-free. |
| |
| Rows of the two embedding tables that spell the same string are the one correspondence two |
| monolingual tokenizers genuinely share, so `min_R ||E_a[anchors] - E_b[anchors] R||` is a |
| legitimate estimate of the basis map with no corpus and no forward pass. Returns (R, n_anchors). |
| """ |
| anchors = AL.vocab_anchors(tok_a, tok_b, max_anchors) |
| ia = [i for i, _ in anchors]; ib = [j for _, j in anchors] |
| Ea = np.asarray(sd_a[key], float)[ia] |
| Eb = np.asarray(sd_b[key], float)[ib] |
| return AL.procrustes_align(Ea, Eb)["R"], len(anchors) |
|
|