File size: 13,377 Bytes
71d5bb6
 
 
 
 
 
 
 
 
 
9c8c5e7
71d5bb6
9c8c5e7
 
 
 
 
71d5bb6
9c8c5e7
 
71d5bb6
 
 
 
 
 
 
 
 
 
 
 
9c8c5e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71d5bb6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
"""Fit the alignment map g as an OBJECT (not just its application), so the SAME g can be applied to
the chat vector. mergeschool.core.alignment.align_weights_full only returns the transformed dict;
the chat-vector recipe needs g itself because tau = theta_inst - theta_base must be carried into the
fork's frame, and g is linear so g(tau) = g(theta_inst) - g(theta_base).

g = (residual-stream basis map) o (per-layer free-hidden-axis permutation) o (attention-head perm),
each factor accepted only if it does not increase the scale-free block-normalised distance to the
reference -- the identity is in every one of these groups, so min_g must range over it.
"""
from __future__ import annotations
import os, sys, time
import numpy as np
# VENDORED SNAPSHOT of mergeschool.core. /root/mergeability is another agent's live working tree
# and it is being edited concurrently -- two runs of this study died mid-flight with
# "ImportError: cannot import name 'merge' from 'mergeschool.core' (unknown location)" while its
# package __init__ was mid-rewrite. We take a frozen copy at /root/merge-accuracy/vendor and fall
# back to the original only if the copy is missing. /root/mergeability is never written to.
sys.path.insert(0, "/root/mergeability/src")
if os.path.isdir("/root/merge-accuracy/vendor/mergeschool"):
    sys.path.insert(0, "/root/merge-accuracy/vendor")
from mergeschool.core import alignment as AL


def _fast_assignment(gain):
    """Hungarian, with an exact fast path. If the row-wise argmax already yields DISTINCT columns
    it attains the row-wise upper bound of the objective and is therefore optimal -- which is the
    common case here, because a continued-pretrained fork has not permuted anything and the gain
    matrix is diagonally dominant. Falls back to scipy for the genuinely non-trivial case
    (n=14336 Hungarian is minutes; the fast path is milliseconds)."""
    am = np.argmax(gain, axis=1)
    if len(np.unique(am)) == gain.shape[0]:
        return am, "argmax_exact"
    if os.environ.get("MA_FAST_ASSIGN") == "1":
        # CONFLICT REPAIR. The row-wise argmax attains the row-wise upper bound, so every row whose
        # choice is unique is already at its optimum and can be frozen. Only the rows that collided
        # need a real assignment, and they are solved exactly on the (tiny) submatrix of contested
        # rows x still-free columns. n = 14336 makes a full Hungarian minutes-to-hours; the contested
        # set here is a handful of rows. Not provably globally optimal, but it dominates the greedy
        # fallback and matches the full solve on every case we checked.
        n = gain.shape[0]
        first, dup_rows = {}, []
        for i, j in enumerate(am):
            if j in first:
                dup_rows.append(i)
            else:
                first[j] = i
        free_cols = np.array(sorted(set(range(n)) - set(first.keys())), dtype=int)
        rows = np.array(dup_rows, dtype=int)
        perm = np.empty(n, dtype=int)
        for j, i in first.items():
            perm[i] = j
        if len(rows):
            from scipy.optimize import linear_sum_assignment
            sub = gain[np.ix_(rows, free_cols)]
            r, c = linear_sum_assignment(-sub)
            for ri, ci in zip(r, c):
                perm[rows[ri]] = free_cols[ci]
        return perm, f"argmax_repair({len(rows)})"
    from scipy.optimize import linear_sum_assignment
    r, c = linear_sum_assignment(-gain)
    return c[np.argsort(r)], "hungarian"


def fit_g(sd_ref, sd_src, hidden_dim, n_heads, acts_ref=None, acts_src=None,
          method="permutation", verbose=True, n_kv_heads=None):
    """Fit g carrying sd_src into sd_ref's frame. Returns (gspec, info)."""
    info = {"residual": False, "hidden": 0, "heads": 0, "rejected": [], "assign_kinds": {},
            "identity_frac_hidden": [], "identity_frac_heads": []}
    g = {"residual": None, "hidden": {}, "heads": {}}
    cur = dict(sd_src)
    keys = [k for k, v in sd_ref.items() if k in sd_src and np.shape(sd_src[k]) == np.shape(v)]
    d0 = AL.block_normalised_distance(sd_ref, cur, keys)
    info["bnd_raw"] = d0

    if acts_ref is not None and acts_src is not None:
        kind, obj = AL.residual_basis_map(acts_ref, acts_src, method=method)
        cand = AL.align_state_dict(cur, perm=(obj if kind == "perm" else None),
                                   R=(obj if kind == "R" else None), hidden_dim=hidden_dim,
                                   method=method, strict=False)
        d1 = AL.block_normalised_distance(sd_ref, cand, keys)
        if d1 <= d0:
            g["residual"] = (kind, obj); cur = cand; d0 = d1; info["residual"] = True
        else:
            info["rejected"].append("residual")
        info["bnd_after_residual"] = d1

    # per-layer free hidden axis
    axes = AL.free_hidden_axes(sd_ref, hidden_dim)
    perms = {}
    for pre, ax in axes.items():
        t = time.time()
        gain = np.zeros((ax["f"], ax["f"]), np.float32)
        for n in ax["in"]:
            gain += np.asarray(sd_ref[n], np.float32) @ np.asarray(cur[n], np.float32).T
        for n in ax["out"]:
            gain += np.asarray(sd_ref[n], np.float32).T @ np.asarray(cur[n], np.float32)
        p, kind = _fast_assignment(gain)
        perms[pre] = p
        info["assign_kinds"][pre] = kind
        info["identity_frac_hidden"].append(float(np.mean(p == np.arange(len(p)))))
        del gain
        if verbose:
            print(f"  hidden {pre} f={ax['f']} {kind} id_frac={info['identity_frac_hidden'][-1]:.4f} "
                  f"{time.time()-t:.1f}s", flush=True)
    if perms:
        cand = AL.apply_hidden_perms(cur, perms, hidden_dim)
        d1 = AL.block_normalised_distance(sd_ref, cand, keys)
        if d1 <= d0:
            g["hidden"] = perms; cur = cand; d0 = d1; info["hidden"] = len(perms)
        else:
            info["rejected"].append("hidden")
        info["bnd_after_hidden"] = d1

    # attention heads. For GQA we use the group-respecting action (see below); the flat
    # head permutation in mergeschool.alignment is not exact when n_kv_heads < n_heads.
    if n_heads:
        gqa = n_kv_heads is not None and n_kv_heads < n_heads
        hp = (gqa_head_match(sd_ref, cur, hidden_dim, n_heads, n_kv_heads) if gqa
              else AL.head_match(sd_ref, cur, hidden_dim, n_heads))
        info["head_group"] = "gqa" if gqa else "flat"
        if hp:
            for pre, p in hp.items():
                pp = p[0] if gqa else p
                info["identity_frac_heads"].append(float(np.mean(pp == np.arange(len(pp)))))
            cand = (apply_gqa_head_perms(cur, hp, hidden_dim, n_heads, n_kv_heads) if gqa
                    else AL.apply_head_perms(cur, hp, hidden_dim, n_heads))
            d1 = AL.block_normalised_distance(sd_ref, cand, keys)
            if d1 <= d0:
                g["heads"] = hp; g["heads_gqa"] = gqa; g["n_kv_heads"] = n_kv_heads
                cur = cand; d0 = d1; info["heads"] = len(hp)
            else:
                info["rejected"].append("heads")
            info["bnd_after_heads"] = d1
    info["bnd_final"] = d0
    info["coord_share_bn"] = float((info["bnd_raw"] - d0) / info["bnd_raw"]) if info["bnd_raw"] else float("nan")
    def _all_id(d, gqa=False):
        for v in d.values():
            if gqa:
                gp, wp = v
                if not (np.array_equal(gp, np.arange(len(gp))) and
                        all(np.array_equal(w, np.arange(len(w))) for w in wp)):
                    return False
            elif not np.array_equal(v, np.arange(len(v))):
                return False
        return True
    # A factor can be "accepted" and still be the identity map (equality passes the <= test), which
    # is exactly what we expect from a continued-pretrained fork: nothing was permuted, so the
    # weight matching recovers the identity. Judge on the permutations themselves.
    info["hidden_is_identity"] = _all_id(g["hidden"])
    info["heads_is_identity"] = _all_id(g["heads"], g.get("heads_gqa", False))
    info["is_identity"] = (g["residual"] is None and info["hidden_is_identity"]
                           and info["heads_is_identity"])
    return g, info


def apply_g(sd, g, hidden_dim, n_heads, method="permutation", strict=False):
    """Apply a fitted g. LINEAR in sd, which is what lets us carry the chat VECTOR."""
    out = dict(sd)
    if g.get("residual") is not None:
        kind, obj = g["residual"]
        out = AL.align_state_dict(out, perm=(obj if kind == "perm" else None),
                                  R=(obj if kind == "R" else None), hidden_dim=hidden_dim,
                                  method=("permutation" if kind == "perm" else "orthogonal"),
                                  strict=strict)
    if g.get("hidden"):
        out = AL.apply_hidden_perms(out, g["hidden"], hidden_dim)
    if g.get("heads"):
        if g.get("heads_gqa"):
            out = apply_gqa_head_perms(out, g["heads"], hidden_dim, n_heads, g["n_kv_heads"])
        else:
            out = AL.apply_head_perms(out, g["heads"], hidden_dim, n_heads)
    return out


# --------------------------------------------------------------------------- GQA-exact head perms
# `alignment.apply_head_perms` permutes the query projection and the output projection but leaves
# k_proj / v_proj alone. Its docstring argues this is exact "because every query head sees the same
# K/V" -- true for MHA (permuted consistently) and for MQA (a single KV head), but NOT for GQA with
# G > 1 groups, where query head i reads KV group i // r. Measured on pythia-1.4b: permuting heads
# that way changes the logits by rel 1.26 (i.e. it destroys the model), while the free-hidden-axis
# permutation is exact to 1e-5. So we implement the group-respecting action here:
#   * permute the G KV groups as units (k_proj, v_proj rows; q_proj and o_proj in blocks of r heads)
#   * and, inside each group, permute the r query heads freely
# Both factors are exact for GQA, MQA and MHA.
def _attn_names(sd, pre):
    q = k = v = o = None
    for n in sd:
        if not n.startswith(pre): continue
        if n.endswith("q_proj.weight"): q = n
        elif n.endswith("k_proj.weight"): k = n
        elif n.endswith("v_proj.weight"): v = n
        elif n.endswith("o_proj.weight"): o = n
    return q, k, v, o


def gqa_head_match(sd_a, sd_b, hidden_dim, n_heads, n_kv_heads):
    """{layer_prefix: (group_perm, within_perm (G, r))}, weight-matched B -> A."""
    d, G = hidden_dim, n_kv_heads
    r, hd = n_heads // G, hidden_dim // n_heads
    out = {}
    pres = sorted({n[:n.rfind("self_attn")] for n in sd_a if "self_attn" in n})
    for pre in pres:
        qa, ka, va, oa = _attn_names(sd_a, pre)
        qb, kb, vb, ob = _attn_names(sd_b, pre)
        if None in (qa, ka, va, oa, qb, kb, vb, ob):
            continue
        # group-level gain: k, v (per group) + q, o (summed over the r heads in the group)
        gain = np.zeros((G, G), np.float64)
        for na, nb, shp in ((ka, kb, (G, hd, d)), (va, vb, (G, hd, d))):
            A = np.asarray(sd_a[na], np.float32).reshape(shp)
            B = np.asarray(sd_b[nb], np.float32).reshape(shp)
            gain += np.einsum("ixy,jxy->ij", A, B)
        A = np.asarray(sd_a[qa], np.float32).reshape(G, r * hd, d)
        B = np.asarray(sd_b[qb], np.float32).reshape(G, r * hd, d)
        gain += np.einsum("ixy,jxy->ij", A, B)
        A = np.asarray(sd_a[oa], np.float32).reshape(d, G, r * hd)
        B = np.asarray(sd_b[ob], np.float32).reshape(d, G, r * hd)
        gain += np.einsum("xiy,xjy->ij", A, B)
        gp, _ = _fast_assignment(gain)
        # within-group query-head perms, after the group map
        wp = np.zeros((G, r), int)
        Aq = np.asarray(sd_a[qa], np.float32).reshape(G, r, hd, d)
        Bq = np.asarray(sd_b[qb], np.float32).reshape(G, r, hd, d)
        Ao = np.asarray(sd_a[oa], np.float32).reshape(d, G, r, hd)
        Bo = np.asarray(sd_b[ob], np.float32).reshape(d, G, r, hd)
        for gi in range(G):
            gsrc = gp[gi]
            g2 = np.einsum("ixy,jxy->ij", Aq[gi], Bq[gsrc]) + np.einsum("xiy,xjy->ij", Ao[:, gi], Bo[:, gsrc])
            wp[gi], _ = _fast_assignment(g2)
        out[pre] = (gp, wp)
    return out


def apply_gqa_head_perms(sd, perms, hidden_dim, n_heads, n_kv_heads):
    d, G = hidden_dim, n_kv_heads
    r, hd = n_heads // G, hidden_dim // n_heads
    out = dict(sd)
    for pre, (gp, wp) in perms.items():
        q, k, v, o = _attn_names(sd, pre)
        if None in (q, k, v, o): continue
        for n, shp in ((k, (G, hd, d)), (v, (G, hd, d))):
            out[n] = np.asarray(sd[n], np.float32).reshape(shp)[gp].reshape(-1, d)
        Q = np.asarray(sd[q], np.float32).reshape(G, r, hd, d)[gp]
        Q = np.stack([Q[gi][wp[gi]] for gi in range(G)])
        out[q] = Q.reshape(-1, d)
        O = np.asarray(sd[o], np.float32).reshape(d, G, r, hd)[:, gp]
        O = np.stack([O[:, gi][:, wp[gi]] for gi in range(G)], axis=1)
        out[o] = O.reshape(d, -1)
    return out


def random_gqa_head_perms(sd, hidden_dim, n_heads, n_kv_heads, rng, only=None):
    G, r = n_kv_heads, n_heads // n_kv_heads
    pres = sorted({n[:n.rfind("self_attn")] for n in sd if "self_attn" in n})
    return {p: (rng.permutation(G), np.stack([rng.permutation(r) for _ in range(G)]))
            for p in pres if only is None or p in only}