Download scripts/crossmodel_native_merge.py from Cross-Mergeability/crossarch-1b-diagnostics: direct link, hf CLI and curl.
- Browser
- Download file 4.18 kB
-
https://huggingface.co/datasets/Cross-Mergeability/crossarch-1b-diagnostics/resolve/main/scripts/crossmodel_native_merge.py
- Command line
-
hf download hf://datasets/Cross-Mergeability/crossarch-1b-diagnostics/scripts/crossmodel_native_merge.py
-
curl -L -o crossmodel_native_merge.py https://huggingface.co/datasets/Cross-Mergeability/crossarch-1b-diagnostics/resolve/main/scripts/crossmodel_native_merge.py
4.18 kB
| """The one natively weight-mergeable cross-model pair: Pythia-1.4B EN x Zh-Pythia-1.4B ZH. | |
| Both are GPT-NeoX 2048/24/16, so every transformer-block tensor has an identical shape and an | |
| identical role -- the parameter space IS shared for the blocks. It is NOT shared for `embed_in` | |
| and `embed_out`: Zh-Pythia was retokenised to 49 953 entries against Pythia's 50 304. So we merge | |
| the blocks and keep each host's own embedding matrices, then evaluate the merged blocks under | |
| BOTH hosts. Nothing is padded or truncated. | |
| Task-vector operators (TIES/TA/DARE) are NOT applicable: the two models have no shared | |
| pre-trained ancestor, so `theta - theta_base` has no meaning across them. Only the base-free | |
| operators (linear interpolation, SLERP) are defined, and those are what we run. | |
| """ | |
| import json, os, sys | |
| import numpy as np, torch | |
| torch.set_num_threads(8) | |
| sys.path.insert(0, "/root/crossarch-diagnostics/scripts") | |
| from ckpt_merge import load_sd, Evaluator, op_lerp | |
| ROOT = "/root/crossarch-diagnostics" | |
| EN, ZH = "EleutherAI/pythia-1.4b", "SJTU-CL/Zh-Pythia-1.4B" | |
| def slerp(A, B, t, eps=1e-7): | |
| out = {} | |
| for k in A: | |
| a, b = A[k].reshape(-1), B[k].reshape(-1) | |
| na, nb = a.norm(), b.norm() | |
| if na < eps or nb < eps: | |
| out[k] = ((1 - t) * A[k] + t * B[k]); continue | |
| cos = torch.clamp((a / na) @ (b / nb), -1 + 1e-7, 1 - 1e-7) | |
| om = torch.acos(cos); so = torch.sin(om) | |
| v = (torch.sin((1 - t) * om) / so) * a + (torch.sin(t * om) / so) * b | |
| out[k] = v.reshape(A[k].shape) | |
| return out | |
| def main(): | |
| dev = "cuda" | |
| A = load_sd(EN, "main", dev) | |
| B = load_sd(ZH, "main", dev) | |
| shared = sorted(k for k in A if k in B and A[k].shape == B[k].shape) | |
| excl = sorted(set(A) ^ set(B)) + sorted(k for k in A if k in B and A[k].shape != B[k].shape) | |
| fa = torch.cat([A[k].reshape(-1) for k in shared]) | |
| fb = torch.cat([B[k].reshape(-1) for k in shared]) | |
| geom = dict( | |
| n_shared_tensors=len(shared), n_shared_params=int(fa.numel()), | |
| excluded_tensors=excl, | |
| w_cos=float(torch.nn.functional.cosine_similarity(fa, fb, dim=0)), | |
| w_l2_rel=float((fa - fb).norm() / (0.5 * (fa.norm() + fb.norm()))), | |
| norm_ratio=float(min(fa.norm(), fb.norm()) / max(fa.norm(), fb.norm()))) | |
| print(json.dumps(geom, indent=2)[:600]) | |
| del fa, fb; torch.cuda.empty_cache() | |
| rows = [] | |
| for host, repo, lang, host_sd, other_sd in (("EN", EN, "EN", A, B), ("ZH", ZH, "ZH", B, A)): | |
| ev = Evaluator(repo, "main", lang, 256, 16, 256, dev) | |
| for opname in ("lerp", "slerp"): | |
| for t in (0.0, 0.1, 0.25, 0.5, 0.75, 0.9, 1.0): | |
| sub_h = {k: host_sd[k] for k in shared} | |
| sub_o = {k: other_sd[k] for k in shared} | |
| m = op_lerp(sub_h, sub_o, t) if opname == "lerp" else slerp(sub_h, sub_o, t) | |
| ev.load(host_sd) # restore host embeddings + everything | |
| ev.load(m) # overwrite shared blocks with the merged ones | |
| nll = ev.nll() | |
| rows.append(dict(host=host, host_lang=lang, operator=opname, t=t, nll=nll)) | |
| print(f"{host} {opname} t={t} nll={nll:.4f}", flush=True) | |
| del m, sub_h, sub_o; torch.cuda.empty_cache() | |
| del ev; torch.cuda.empty_cache() | |
| import pandas as pd | |
| df = pd.DataFrame(rows) | |
| df.to_csv(f"{ROOT}/results/crossmodel_native_merge.csv", index=False) | |
| # barrier per host/operator, relative to the linear baseline between the two endpoints | |
| out = [] | |
| for (h, o), g in df.groupby(["host", "operator"]): | |
| g = g.set_index("t").nll | |
| base = lambda t: (1 - t) * g[0.0] + t * g[1.0] | |
| bar = max(g[t] - base(t) for t in g.index if 0 < t < 1) | |
| out.append(dict(host=h, operator=o, nll_host_only=g[0.0], nll_donor_blocks=g[1.0], | |
| nll_half=g[0.5], barrier=bar)) | |
| pd.DataFrame(out).to_csv(f"{ROOT}/results/crossmodel_native_merge_summary.csv", index=False) | |
| json.dump(geom, open(f"{ROOT}/results/crossmodel_native_geometry.json", "w"), indent=2) | |
| print(pd.DataFrame(out).to_string(index=False)) | |
| if __name__ == "__main__": | |
| main() | |