File size: 7,323 Bytes
7e354e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Per-pair worker: pre-merge diagnostic -> recorded prediction -> merge (naive / aligned) ->
DOWNSTREAM ACCURACY for parent A, parent B, naive merge, aligned merge.

usage: run_pairs.py <pairs.json> <gpu> [<shard> <nshards>]
"""
from __future__ import annotations
import os, sys, json, time, gc, traceback
gpu = sys.argv[2]
os.environ["CUDA_VISIBLE_DEVICES"] = gpu
import numpy as np, torch
import ma_common as C
import tasks as TK

PAIRS = json.load(open(sys.argv[1]))
SHARD, NSH = (int(sys.argv[3]), int(sys.argv[4])) if len(sys.argv) > 4 else (0, 1)
LEDGER = os.environ.get("MA_LEDGER", "/root/merge-accuracy/results/ledger.jsonl")
NDOC = int(os.environ.get("MA_NDOC", "500"))
CORE = os.environ.get("MA_TASKS", "sciq,piqa,arc_easy,lambada").split(",")
DEV = "cuda"

_docs = {}
def docs(t):
    if t not in _docs:
        _docs[t] = TK.TASKS[t](NDOC)
    return _docs[t]

done = C.jload(LEDGER)
def have(k): return k in done
def put(k, rec):
    rec["key"] = k; rec["t"] = time.time()
    C.jappend(LEDGER, rec); done[k] = rec
    print(f"[{time.strftime('%H:%M:%S')}] {k}  " +
          " ".join(f"{t}={rec['acc'][t]:.4f}" for t in rec.get("acc", {})), flush=True)

def eval_sd(model, tok, sd=None):
    if sd is not None:
        C.sd_load(model, sd)
    out, items = {}, {}
    for t in CORE:
        r = C.eval_task(model, tok, docs(t), DEV, bs=int(os.environ.get("MA_BS", "16")))
        out[t] = r["acc"]; out[t + "_norm"] = r["acc_norm"]; items[t] = r["items"]
    out["mean"] = float(np.mean([out[t] for t in CORE]))
    return out, items


for pi, P in enumerate(PAIRS):
    if pi % NSH != SHARD:
        continue
    name = P["name"]; rung = P["rung"]
    t_pair = time.time()
    try:
        # ---------------------------------------------------------- parents
        ma = C.load_model(P["a"]["repo"], P["a"].get("rev"))
        ta = C.load_tok(P["a"]["repo"], P["a"].get("rev"))
        sents = C.flores_lines("eng_Latn", 256)
        acts_a = C.capture_acts_sent(ma, ta, sents, DEV)
        sd_a = C.sd_np(ma)
        ka = f"{rung}|{name}|parentA"
        if not have(ka):
            acc, _ = eval_sd(ma, ta)
            put(ka, {"rung": rung, "pair": name, "arm": "parentA", "alpha": None,
                     "model": P["a"]["repo"], "rev": P["a"].get("rev"), "acc": acc})
        accA = done[ka]["acc"]

        mb = C.load_model(P["b"]["repo"], P["b"].get("rev"))
        tb = C.load_tok(P["b"]["repo"], P["b"].get("rev"))
        acts_b = C.capture_acts_sent(mb, tb, sents, DEV)
        sd_b = C.sd_np(mb)
        kb = f"{rung}|{name}|parentB"
        if not have(kb):
            acc, _ = eval_sd(mb, tb)
            put(kb, {"rung": rung, "pair": name, "arm": "parentB", "alpha": None,
                     "model": P["b"]["repo"], "rev": P["b"].get("rev"), "acc": acc})
        accB = done[kb]["acc"]
        del mb; gc.collect(); torch.cuda.empty_cache()

        cfg = ma.config
        hid = getattr(cfg, "hidden_size", None); nh = getattr(cfg, "num_attention_heads", None)

        # ---------------------------------------------------------- mergeable keys
        mk = C.body_keys(sd_a, sd_b)
        full = C.shared_keys(sd_a, sd_b)
        emb_ok = len(full) > len(mk) and P.get("same_tokenizer", True)
        keys = full if emb_ok else mk
        scope = "full" if emb_ok else "body_only"

        # ---------------------------------------------------------- ALIGN (B -> A's frame)
        t0 = time.time()
        sd_b_perm, info_p = C.align_pair(sd_a, sd_b, hid, nh, acts_a, acts_b, "permutation")
        sd_b_orth, info_o = C.align_pair(sd_a, sd_b, hid, nh, acts_a, acts_b, "orthogonal")
        t_align = time.time() - t0

        # ---------------------------------------------------------- PRE-MERGE DIAGNOSTIC
        kd = f"{rung}|{name}|diag"
        if not have(kd):
            d = C.diagnostics({k: sd_a[k] for k in keys}, {k: sd_b[k] for k in keys},
                              {k: sd_b_perm[k] for k in keys}, {k: sd_b_orth[k] for k in keys},
                              acts_a, acts_b)
            d["align_info_perm"] = info_p; d["align_info_orth"] = info_o
            d["align_seconds"] = t_align; d["merge_scope"] = scope; d["n_merge_keys"] = len(keys)
            # PREDICTION, recorded BEFORE any merged model is scored.
            d["predicted_align_helps"] = bool(d["coord_share"] >= 0.02)
            put(kd, {"rung": rung, "pair": name, "arm": "diag", "diag": d})
        diag = done[kd]["diag"]

        # pick the better of the two aligners by scale-free residual distance
        use_orth = diag.get("qmd_bn_orth", 9e9) < diag.get("qmd_bn_perm", 9e9)
        sd_b_al = sd_b_orth if use_orth else sd_b_perm
        aligner = "orthogonal" if use_orth else "permutation"

        # ---------------------------------------------------------- MERGES
        for alpha in P.get("alphas", [0.5]):
            for arm, sdb in (("naive", sd_b), ("aligned", sd_b_al)):
                k = f"{rung}|{name}|{arm}|a{alpha}"
                if have(k):
                    continue
                sd_m = dict(sd_a)
                for kk in keys:
                    sd_m[kk] = (1 - alpha) * sd_a[kk] + alpha * np.asarray(sdb[kk], float)
                acc, _ = eval_sd(ma, ta, sd_m)
                put(k, {"rung": rung, "pair": name, "arm": arm, "alpha": alpha,
                        "aligner": aligner if arm == "aligned" else None,
                        "scope": scope, "acc": acc,
                        "coord_share": diag["coord_share"],
                        "accA_mean": accA["mean"], "accB_mean": accB["mean"]})
                del sd_m; gc.collect()
                C.sd_load(ma, sd_a)   # restore A for the next merge
        # ---------------------------------------------------------- TIES (alpha-free)
        if P.get("ties", True):
            for arm, sdb in (("ties_naive", sd_b), ("ties_aligned", sd_b_al)):
                k = f"{rung}|{name}|{arm}"
                if have(k):
                    continue
                try:
                    base = {kk: np.zeros_like(sd_a[kk]) for kk in keys}
                    tv = C.MG.ties(base, [{kk: sd_a[kk] for kk in keys},
                                          {kk: np.asarray(sdb[kk], float) for kk in keys}],
                                   density=0.2)
                    sd_m = dict(sd_a); sd_m.update(tv)
                    acc, _ = eval_sd(ma, ta, sd_m)
                    put(k, {"rung": rung, "pair": name, "arm": arm, "alpha": None,
                            "scope": scope, "acc": acc, "coord_share": diag["coord_share"],
                            "accA_mean": accA["mean"], "accB_mean": accB["mean"]})
                    del sd_m, tv; gc.collect()
                    C.sd_load(ma, sd_a)
                except Exception as e:
                    print("TIES fail", name, arm, repr(e)[:200], flush=True)
        print(f"== pair {name} done in {time.time()-t_pair:.0f}s", flush=True)
    except Exception as e:
        print(f"!! PAIR FAIL {name}: {traceback.format_exc()[-1500:]}", flush=True)
    finally:
        for v in ("ma", "mb", "sd_a", "sd_b", "sd_b_perm", "sd_b_orth", "acts_a", "acts_b"):
            if v in dir(): pass
        try: del ma
        except Exception: pass
        gc.collect(); torch.cuda.empty_cache()
print("ALLDONE", flush=True)