suchirsalhan commited on
Commit
509efdd
·
verified ·
1 Parent(s): 949bd1a

Upload code/diag_only.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. code/diag_only.py +63 -0
code/diag_only.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pre-merge diagnostic ONLY, for all forks: is the fork still in the base model's frame?
2
+ Writes the diag records + the fitted g so chatvec_run.py reuses them."""
3
+ import os, sys, json, time, gc, traceback
4
+ os.environ["CUDA_VISIBLE_DEVICES"] = sys.argv[2]
5
+ import numpy as np, torch
6
+ import ma_common as C, gmap
7
+ from mergeschool.core import metrics as MT
8
+
9
+ FORKS = json.load(open(sys.argv[1]))
10
+ LEDGER = os.environ.get("MA_LEDGER", "/root/merge-accuracy/results/chatvec.jsonl")
11
+ BASE = "meta-llama/Llama-3.1-8B"
12
+ done = C.jload(LEDGER)
13
+
14
+ mb = C.load_model(BASE, dev="cpu", dtype=torch.float32)
15
+ sd_base = C.sd_np(mb); cfg = mb.config
16
+ HID, NH = cfg.hidden_size, cfg.num_attention_heads
17
+ NKV = getattr(cfg, "num_key_value_heads", NH)
18
+ del mb; gc.collect()
19
+ tok_base = C.load_tok(BASE)
20
+ sents = C.flores_lines("eng_Latn", 256)
21
+ m = C.load_model(BASE, dev="cuda", dtype=torch.bfloat16)
22
+ acts_base = C.capture_acts_sent(m, tok_base, sents, "cuda")
23
+ del m; gc.collect(); torch.cuda.empty_cache()
24
+ print("base ready", flush=True)
25
+
26
+ for F in FORKS:
27
+ name, repo, lang = F["name"], F["repo"], F["lang"]
28
+ if f"{name}|diag" in done: continue
29
+ try:
30
+ t0 = time.time()
31
+ tok_f = C.load_tok(repo)
32
+ mfg = C.load_model(repo, dev="cuda", dtype=torch.bfloat16)
33
+ acts_f = C.capture_acts_sent(mfg, tok_f, sents, "cuda")
34
+ del mfg; gc.collect(); torch.cuda.empty_cache()
35
+ mf = C.load_model(repo, dev="cpu", dtype=torch.float32)
36
+ sd_fork = C.sd_np(mf); del mf; gc.collect()
37
+ KEYS = C.shared_keys(sd_base, sd_fork)
38
+ g, info = gmap.fit_g(sd_fork, sd_base, HID, NH, acts_f, acts_base, "permutation", verbose=False, n_kv_heads=NKV)
39
+ a = np.concatenate([sd_base[k].ravel() for k in KEYS])
40
+ b = np.concatenate([sd_fork[k].ravel() for k in KEYS])
41
+ info["weight_cosine_vs_base"] = float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b)))
42
+ info["rel_drift"] = float(np.linalg.norm(a - b) / np.linalg.norm(a))
43
+ del a, b; gc.collect()
44
+ L = sorted(set(acts_f) & set(acts_base))
45
+ info["cka_mean"] = float(np.mean([MT.cka(acts_base[l], acts_f[l]) for l in L]))
46
+ info["cka_last"] = float(MT.cka(acts_base[L[-1]], acts_f[L[-1]]))
47
+ info["coord_share"] = info["coord_share_bn"]
48
+ info["PREDICTION_align_helps"] = bool(info["coord_share"] >= 0.01)
49
+ info["fit_seconds"] = time.time() - t0
50
+ info = {k: (v.tolist() if isinstance(v, np.ndarray) else v) for k, v in info.items()}
51
+ np.save(f"/root/merge-accuracy/results/g_{name}.npy", np.array([g], dtype=object), allow_pickle=True)
52
+ rec = {"key": f"{name}|diag", "kind": "diag", "fork": name, "arm": "diag", "lang": lang,
53
+ "t": time.time(), "diag": info}
54
+ C.jappend(LEDGER, rec)
55
+ print(f"DIAG {name}: coord_share={info['coord_share']:.5f} identity={info['is_identity']} "
56
+ f"bnd_raw={info['bnd_raw']:.4f} bnd_final={info['bnd_final']:.4f} "
57
+ f"wcos={info['weight_cosine_vs_base']:.4f} drift={info['rel_drift']:.4f} "
58
+ f"cka={info['cka_mean']:.3f} residual={info['residual']} hidden={info['hidden']} "
59
+ f"heads={info['heads']} rejected={info['rejected']} {info['fit_seconds']:.0f}s", flush=True)
60
+ del sd_fork, acts_f, g; gc.collect()
61
+ except Exception:
62
+ print(f"!! DIAG FAIL {name}\n{traceback.format_exc()[-1500:]}", flush=True)
63
+ print("DIAG_DONE", flush=True)