File size: 6,706 Bytes
44bc7e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0389a3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
"""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.")})


# --------------------------------------------------------------- residual basis (d)
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            # norm affine: exact under perm, kept under R
            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      # (d, out): residual is the INPUT axis
            elif n.endswith("attn.c_proj.weight") or n.endswith("mlp.c_proj.weight"):
                out[n] = P(W, 1) if P else W @ R        # (in, d): residual is the OUTPUT axis
            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


# --------------------------------------------------------------- free MLP hidden axis (4d)
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)          # (4d,d)@(d,4d)
        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


# --------------------------------------------------------------- attention heads
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):                                   # q | k | v, each (d, d)
            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


# --------------------------------------------------------------- composition with accept-each
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


# --------------------------------------------------------------- embedding-row Procrustes
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)