suchirsalhan commited on
Commit
71d5bb6
·
verified ·
1 Parent(s): 2c343df

Upload code/gmap.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. code/gmap.py +223 -0
code/gmap.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fit the alignment map g as an OBJECT (not just its application), so the SAME g can be applied to
2
+ the chat vector. mergeschool.core.alignment.align_weights_full only returns the transformed dict;
3
+ the chat-vector recipe needs g itself because tau = theta_inst - theta_base must be carried into the
4
+ fork's frame, and g is linear so g(tau) = g(theta_inst) - g(theta_base).
5
+
6
+ g = (residual-stream basis map) o (per-layer free-hidden-axis permutation) o (attention-head perm),
7
+ each factor accepted only if it does not increase the scale-free block-normalised distance to the
8
+ reference -- the identity is in every one of these groups, so min_g must range over it.
9
+ """
10
+ from __future__ import annotations
11
+ import sys, time
12
+ import numpy as np
13
+ sys.path.insert(0, "/root/mergeability/src")
14
+ from mergeschool.core import alignment as AL
15
+
16
+
17
+ def _fast_assignment(gain):
18
+ """Hungarian, with an exact fast path. If the row-wise argmax already yields DISTINCT columns
19
+ it attains the row-wise upper bound of the objective and is therefore optimal -- which is the
20
+ common case here, because a continued-pretrained fork has not permuted anything and the gain
21
+ matrix is diagonally dominant. Falls back to scipy for the genuinely non-trivial case
22
+ (n=14336 Hungarian is minutes; the fast path is milliseconds)."""
23
+ am = np.argmax(gain, axis=1)
24
+ if len(np.unique(am)) == gain.shape[0]:
25
+ return am, "argmax_exact"
26
+ from scipy.optimize import linear_sum_assignment
27
+ r, c = linear_sum_assignment(-gain)
28
+ return c[np.argsort(r)], "hungarian"
29
+
30
+
31
+ def fit_g(sd_ref, sd_src, hidden_dim, n_heads, acts_ref=None, acts_src=None,
32
+ method="permutation", verbose=True, n_kv_heads=None):
33
+ """Fit g carrying sd_src into sd_ref's frame. Returns (gspec, info)."""
34
+ info = {"residual": False, "hidden": 0, "heads": 0, "rejected": [], "assign_kinds": {},
35
+ "identity_frac_hidden": [], "identity_frac_heads": []}
36
+ g = {"residual": None, "hidden": {}, "heads": {}}
37
+ cur = dict(sd_src)
38
+ keys = [k for k, v in sd_ref.items() if k in sd_src and np.shape(sd_src[k]) == np.shape(v)]
39
+ d0 = AL.block_normalised_distance(sd_ref, cur, keys)
40
+ info["bnd_raw"] = d0
41
+
42
+ if acts_ref is not None and acts_src is not None:
43
+ kind, obj = AL.residual_basis_map(acts_ref, acts_src, method=method)
44
+ cand = AL.align_state_dict(cur, perm=(obj if kind == "perm" else None),
45
+ R=(obj if kind == "R" else None), hidden_dim=hidden_dim,
46
+ method=method, strict=False)
47
+ d1 = AL.block_normalised_distance(sd_ref, cand, keys)
48
+ if d1 <= d0:
49
+ g["residual"] = (kind, obj); cur = cand; d0 = d1; info["residual"] = True
50
+ else:
51
+ info["rejected"].append("residual")
52
+ info["bnd_after_residual"] = d1
53
+
54
+ # per-layer free hidden axis
55
+ axes = AL.free_hidden_axes(sd_ref, hidden_dim)
56
+ perms = {}
57
+ for pre, ax in axes.items():
58
+ t = time.time()
59
+ gain = np.zeros((ax["f"], ax["f"]), np.float32)
60
+ for n in ax["in"]:
61
+ gain += np.asarray(sd_ref[n], np.float32) @ np.asarray(cur[n], np.float32).T
62
+ for n in ax["out"]:
63
+ gain += np.asarray(sd_ref[n], np.float32).T @ np.asarray(cur[n], np.float32)
64
+ p, kind = _fast_assignment(gain)
65
+ perms[pre] = p
66
+ info["assign_kinds"][pre] = kind
67
+ info["identity_frac_hidden"].append(float(np.mean(p == np.arange(len(p)))))
68
+ del gain
69
+ if verbose:
70
+ print(f" hidden {pre} f={ax['f']} {kind} id_frac={info['identity_frac_hidden'][-1]:.4f} "
71
+ f"{time.time()-t:.1f}s", flush=True)
72
+ if perms:
73
+ cand = AL.apply_hidden_perms(cur, perms, hidden_dim)
74
+ d1 = AL.block_normalised_distance(sd_ref, cand, keys)
75
+ if d1 <= d0:
76
+ g["hidden"] = perms; cur = cand; d0 = d1; info["hidden"] = len(perms)
77
+ else:
78
+ info["rejected"].append("hidden")
79
+ info["bnd_after_hidden"] = d1
80
+
81
+ # attention heads. For GQA we use the group-respecting action (see below); the flat
82
+ # head permutation in mergeschool.alignment is not exact when n_kv_heads < n_heads.
83
+ if n_heads:
84
+ gqa = n_kv_heads is not None and n_kv_heads < n_heads
85
+ hp = (gqa_head_match(sd_ref, cur, hidden_dim, n_heads, n_kv_heads) if gqa
86
+ else AL.head_match(sd_ref, cur, hidden_dim, n_heads))
87
+ info["head_group"] = "gqa" if gqa else "flat"
88
+ if hp:
89
+ for pre, p in hp.items():
90
+ pp = p[0] if gqa else p
91
+ info["identity_frac_heads"].append(float(np.mean(pp == np.arange(len(pp)))))
92
+ cand = (apply_gqa_head_perms(cur, hp, hidden_dim, n_heads, n_kv_heads) if gqa
93
+ else AL.apply_head_perms(cur, hp, hidden_dim, n_heads))
94
+ d1 = AL.block_normalised_distance(sd_ref, cand, keys)
95
+ if d1 <= d0:
96
+ g["heads"] = hp; g["heads_gqa"] = gqa; g["n_kv_heads"] = n_kv_heads
97
+ cur = cand; d0 = d1; info["heads"] = len(hp)
98
+ else:
99
+ info["rejected"].append("heads")
100
+ info["bnd_after_heads"] = d1
101
+ info["bnd_final"] = d0
102
+ info["coord_share_bn"] = float((info["bnd_raw"] - d0) / info["bnd_raw"]) if info["bnd_raw"] else float("nan")
103
+ def _all_id(d, gqa=False):
104
+ for v in d.values():
105
+ if gqa:
106
+ gp, wp = v
107
+ if not (np.array_equal(gp, np.arange(len(gp))) and
108
+ all(np.array_equal(w, np.arange(len(w))) for w in wp)):
109
+ return False
110
+ elif not np.array_equal(v, np.arange(len(v))):
111
+ return False
112
+ return True
113
+ # A factor can be "accepted" and still be the identity map (equality passes the <= test), which
114
+ # is exactly what we expect from a continued-pretrained fork: nothing was permuted, so the
115
+ # weight matching recovers the identity. Judge on the permutations themselves.
116
+ info["hidden_is_identity"] = _all_id(g["hidden"])
117
+ info["heads_is_identity"] = _all_id(g["heads"], g.get("heads_gqa", False))
118
+ info["is_identity"] = (g["residual"] is None and info["hidden_is_identity"]
119
+ and info["heads_is_identity"])
120
+ return g, info
121
+
122
+
123
+ def apply_g(sd, g, hidden_dim, n_heads, method="permutation", strict=False):
124
+ """Apply a fitted g. LINEAR in sd, which is what lets us carry the chat VECTOR."""
125
+ out = dict(sd)
126
+ if g.get("residual") is not None:
127
+ kind, obj = g["residual"]
128
+ out = AL.align_state_dict(out, perm=(obj if kind == "perm" else None),
129
+ R=(obj if kind == "R" else None), hidden_dim=hidden_dim,
130
+ method=("permutation" if kind == "perm" else "orthogonal"),
131
+ strict=strict)
132
+ if g.get("hidden"):
133
+ out = AL.apply_hidden_perms(out, g["hidden"], hidden_dim)
134
+ if g.get("heads"):
135
+ if g.get("heads_gqa"):
136
+ out = apply_gqa_head_perms(out, g["heads"], hidden_dim, n_heads, g["n_kv_heads"])
137
+ else:
138
+ out = AL.apply_head_perms(out, g["heads"], hidden_dim, n_heads)
139
+ return out
140
+
141
+
142
+ # --------------------------------------------------------------------------- GQA-exact head perms
143
+ # `alignment.apply_head_perms` permutes the query projection and the output projection but leaves
144
+ # k_proj / v_proj alone. Its docstring argues this is exact "because every query head sees the same
145
+ # K/V" -- true for MHA (permuted consistently) and for MQA (a single KV head), but NOT for GQA with
146
+ # G > 1 groups, where query head i reads KV group i // r. Measured on pythia-1.4b: permuting heads
147
+ # that way changes the logits by rel 1.26 (i.e. it destroys the model), while the free-hidden-axis
148
+ # permutation is exact to 1e-5. So we implement the group-respecting action here:
149
+ # * permute the G KV groups as units (k_proj, v_proj rows; q_proj and o_proj in blocks of r heads)
150
+ # * and, inside each group, permute the r query heads freely
151
+ # Both factors are exact for GQA, MQA and MHA.
152
+ def _attn_names(sd, pre):
153
+ q = k = v = o = None
154
+ for n in sd:
155
+ if not n.startswith(pre): continue
156
+ if n.endswith("q_proj.weight"): q = n
157
+ elif n.endswith("k_proj.weight"): k = n
158
+ elif n.endswith("v_proj.weight"): v = n
159
+ elif n.endswith("o_proj.weight"): o = n
160
+ return q, k, v, o
161
+
162
+
163
+ def gqa_head_match(sd_a, sd_b, hidden_dim, n_heads, n_kv_heads):
164
+ """{layer_prefix: (group_perm, within_perm (G, r))}, weight-matched B -> A."""
165
+ d, G = hidden_dim, n_kv_heads
166
+ r, hd = n_heads // G, hidden_dim // n_heads
167
+ out = {}
168
+ pres = sorted({n[:n.rfind("self_attn")] for n in sd_a if "self_attn" in n})
169
+ for pre in pres:
170
+ qa, ka, va, oa = _attn_names(sd_a, pre)
171
+ qb, kb, vb, ob = _attn_names(sd_b, pre)
172
+ if None in (qa, ka, va, oa, qb, kb, vb, ob):
173
+ continue
174
+ # group-level gain: k, v (per group) + q, o (summed over the r heads in the group)
175
+ gain = np.zeros((G, G), np.float64)
176
+ for na, nb, shp in ((ka, kb, (G, hd, d)), (va, vb, (G, hd, d))):
177
+ A = np.asarray(sd_a[na], np.float32).reshape(shp)
178
+ B = np.asarray(sd_b[nb], np.float32).reshape(shp)
179
+ gain += np.einsum("ixy,jxy->ij", A, B)
180
+ A = np.asarray(sd_a[qa], np.float32).reshape(G, r * hd, d)
181
+ B = np.asarray(sd_b[qb], np.float32).reshape(G, r * hd, d)
182
+ gain += np.einsum("ixy,jxy->ij", A, B)
183
+ A = np.asarray(sd_a[oa], np.float32).reshape(d, G, r * hd)
184
+ B = np.asarray(sd_b[ob], np.float32).reshape(d, G, r * hd)
185
+ gain += np.einsum("xiy,xjy->ij", A, B)
186
+ gp, _ = _fast_assignment(gain)
187
+ # within-group query-head perms, after the group map
188
+ wp = np.zeros((G, r), int)
189
+ Aq = np.asarray(sd_a[qa], np.float32).reshape(G, r, hd, d)
190
+ Bq = np.asarray(sd_b[qb], np.float32).reshape(G, r, hd, d)
191
+ Ao = np.asarray(sd_a[oa], np.float32).reshape(d, G, r, hd)
192
+ Bo = np.asarray(sd_b[ob], np.float32).reshape(d, G, r, hd)
193
+ for gi in range(G):
194
+ gsrc = gp[gi]
195
+ g2 = np.einsum("ixy,jxy->ij", Aq[gi], Bq[gsrc]) + np.einsum("xiy,xjy->ij", Ao[:, gi], Bo[:, gsrc])
196
+ wp[gi], _ = _fast_assignment(g2)
197
+ out[pre] = (gp, wp)
198
+ return out
199
+
200
+
201
+ def apply_gqa_head_perms(sd, perms, hidden_dim, n_heads, n_kv_heads):
202
+ d, G = hidden_dim, n_kv_heads
203
+ r, hd = n_heads // G, hidden_dim // n_heads
204
+ out = dict(sd)
205
+ for pre, (gp, wp) in perms.items():
206
+ q, k, v, o = _attn_names(sd, pre)
207
+ if None in (q, k, v, o): continue
208
+ for n, shp in ((k, (G, hd, d)), (v, (G, hd, d))):
209
+ out[n] = np.asarray(sd[n], np.float32).reshape(shp)[gp].reshape(-1, d)
210
+ Q = np.asarray(sd[q], np.float32).reshape(G, r, hd, d)[gp]
211
+ Q = np.stack([Q[gi][wp[gi]] for gi in range(G)])
212
+ out[q] = Q.reshape(-1, d)
213
+ O = np.asarray(sd[o], np.float32).reshape(d, G, r, hd)[:, gp]
214
+ O = np.stack([O[:, gi][:, wp[gi]] for gi in range(G)], axis=1)
215
+ out[o] = O.reshape(d, -1)
216
+ return out
217
+
218
+
219
+ def random_gqa_head_perms(sd, hidden_dim, n_heads, n_kv_heads, rng, only=None):
220
+ G, r = n_kv_heads, n_heads // n_kv_heads
221
+ pres = sorted({n[:n.rfind("self_attn")] for n in sd if "self_attn" in n})
222
+ return {p: (rng.permutation(G), np.stack([rng.permutation(r) for _ in range(G)]))
223
+ for p in pres if only is None or p in only}