| """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 |
| |
| |
| |
| |
| |
| 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": |
| |
| |
| |
| |
| |
| |
| 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 |
|
|
| |
| 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 |
|
|
| |
| |
| 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 |
| |
| |
| |
| 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 |
|
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| 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 |
| |
| 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) |
| |
| 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} |
|
|