File size: 7,705 Bytes
e142e0c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""CHAT-VECTOR EXPERIMENT.

    theta_new = theta_fork + lambda * (theta_instruct - theta_base)          [naive]
    theta_new = theta_fork + lambda * g(theta_instruct - theta_base)         [aligned]

g is fitted from (fork, base) -- i.e. it is the map that carries the BASE model's parameterisation
into the FORK's frame. The falsifiable prediction, recorded before any merged model is scored:
a fork whose frame has drifted (high coordinate share) is one where the naive chat vector is being
added in the wrong basis, and alignment should rescue it; a fork that never left base's frame
(coordinate share ~ 0) should show no benefit at all.

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

FORKS = json.load(open(sys.argv[1]))
LAMS = [float(x) for x in sys.argv[3].split(",")]
SHARD, NSH = (int(sys.argv[4]), int(sys.argv[5])) if len(sys.argv) > 5 else (0, 1)
LEDGER = os.environ.get("MA_LEDGER", "/root/merge-accuracy/results/chatvec.jsonl")
NBEL = int(os.environ.get("MA_NBEL", "300"))
NENG = int(os.environ.get("MA_NENG", "500"))
BS = int(os.environ.get("MA_BS", "16"))
NIF = int(os.environ.get("MA_NIF", "200"))
BASE = "meta-llama/Llama-3.1-8B"; INST = "meta-llama/Llama-3.1-8B-Instruct"
DEV = "cuda"
DT = torch.bfloat16

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


def evaluate(model, tok, langs):
    """Three axes: target-language capability, instruction following, English retention."""
    out = {}
    if isinstance(langs, str): langs = [langs]
    for lg in langs:
        out[f"belebele_{lg}"] = C.eval_task(model, tok, TK.belebele(lg, NBEL), DEV, bs=BS)["acc"]
    out["belebele_eng_Latn"] = C.eval_task(model, tok, TK.belebele("eng_Latn", NBEL), DEV, bs=BS)["acc"]
    out["arc_easy"] = C.eval_task(model, tok, TK.arc_easy(NENG), DEV, bs=BS)["acc"]
    ife, _ = C.eval_ifeval(model, tok, DEV, n=NIF, bs=max(BS // 2, 4))
    out["ifeval_prompt"] = ife["ifeval_prompt"]; out["ifeval_inst"] = ife["ifeval_inst"]
    return out


print("loading base + instruct ...", flush=True)
mb = C.load_model(BASE, dev="cpu", dtype=torch.float32)
sd_base = C.sd_np(mb); cfg = mb.config
HID, NH = cfg.hidden_size, cfg.num_attention_heads
NKV = getattr(cfg, "num_key_value_heads", NH)
del mb; gc.collect()
mi = C.load_model(INST, dev="cpu", dtype=torch.float32)
sd_inst = C.sd_np(mi); del mi; gc.collect()
KEYS = C.shared_keys(sd_base, sd_inst)
tau = {k: sd_inst[k] - sd_base[k] for k in KEYS}
del sd_inst; gc.collect()
print(f"base+tau ready, {len(KEYS)} keys", flush=True)

tok_base = C.load_tok(BASE); tok_inst = C.load_tok(INST)
sents = C.flores_lines("eng_Latn", 256)

# ---- references (evaluated once, shared by every fork) -------------------------------------
for tag, repo, tk in (("REF_base", BASE, tok_base), ("REF_instruct", INST, tok_inst)):
    k = f"{tag}"
    if k in done: continue
    m = C.load_model(repo, dev=DEV, dtype=DT)
    langs = sorted({f["lang"] for f in FORKS})
    acc = evaluate(m, tk, langs)
    put(k, {"kind": "reference", "fork": None, "arm": tag, "lam": None, "model": repo, "acc": acc})
    del m; gc.collect(); torch.cuda.empty_cache()

# base activations for the residual-basis factor of g
m = C.load_model(BASE, dev=DEV, dtype=DT)
acts_base = C.capture_acts_sent(m, tok_base, sents, DEV)
del m; gc.collect(); torch.cuda.empty_cache()

for fi, F in enumerate(FORKS):
    if fi % NSH != SHARD: continue
    name, repo, lang = F["name"], F["repo"], F["lang"]
    try:
        print(f"### fork {name} ({repo}) lang={lang}", flush=True)
        tok_f = C.load_tok(repo)
        mf = C.load_model(repo, dev=DEV, dtype=DT)
        acts_f = C.capture_acts_sent(mf, tok_f, sents, DEV)
        kf = f"{name}|fork_alone"
        if kf not in done:
            put(kf, {"kind": "fork", "fork": name, "arm": "fork_alone", "lam": None,
                     "model": repo, "lang": lang, "acc": evaluate(mf, tok_f, [lang])})
        del mf; gc.collect(); torch.cuda.empty_cache()

        mf_cpu = C.load_model(repo, dev="cpu", dtype=torch.float32)
        sd_fork = C.sd_np(mf_cpu); del mf_cpu; gc.collect()

        # ---------------- PRE-MERGE DIAGNOSTIC + RECORDED PREDICTION ----------------
        kd = f"{name}|diag"
        if kd not in done:
            t0 = time.time()
            g, info = gmap.fit_g(sd_fork, sd_base, HID, NH, acts_f, acts_base, "permutation", n_kv_heads=NKV)
            info["fit_seconds"] = time.time() - t0
            # provenance check by weight geometry, not by the model card
            a = np.concatenate([sd_base[k].ravel() for k in KEYS[:40]])
            b = np.concatenate([sd_fork[k].ravel() for k in KEYS[:40]])
            info["weight_cosine_vs_base"] = float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b)))
            info["rel_drift"] = float(np.linalg.norm(a - b) / np.linalg.norm(a))
            L = sorted(set(acts_f) & set(acts_base))
            from mergeschool.core import metrics as MT
            info["cka_mean"] = float(np.mean([MT.cka(acts_base[l], acts_f[l]) for l in L]))
            info["cka_last"] = float(MT.cka(acts_base[L[-1]], acts_f[L[-1]]))
            info["coord_share"] = info["coord_share_bn"]
            info["PREDICTION_align_helps"] = bool(info["coord_share"] >= 0.01)
            info = {k: (v if not isinstance(v, np.ndarray) else v.tolist()) for k, v in info.items()}
            put(kd, {"kind": "diag", "fork": name, "arm": "diag", "lang": lang, "diag": info})
            np.save(f"/root/merge-accuracy/results/g_{name}.npy", np.array([g], dtype=object),
                    allow_pickle=True)
        else:
            g = np.load(f"/root/merge-accuracy/results/g_{name}.npy", allow_pickle=True)[0]
        diag = done[kd]["diag"]
        print(f"  DIAG {name}: coord_share={diag['coord_share']:.4f} identity={diag['is_identity']} "
              f"PREDICT_align_helps={diag['PREDICTION_align_helps']} cka={diag['cka_mean']:.3f}", flush=True)

        tau_al = gmap.apply_g(tau, g, HID, NH) if not diag["is_identity"] else None

        # reload a bf16 shell we can overwrite repeatedly
        mm = C.load_model(repo, dev=DEV, dtype=DT)
        for lam in LAMS:
            for arm, tv in (("naive", tau), ("aligned", tau_al)):
                k = f"{name}|{arm}|lam{lam}"
                if k in done: continue
                if tv is None:
                    put(k, {"kind": "merge", "fork": name, "arm": arm, "lam": lam, "lang": lang,
                            "acc": dict(done[f"{name}|naive|lam{lam}"]["acc"]) if f"{name}|naive|lam{lam}" in done else None,
                            "note": "g is the identity -> aligned chat vector is bitwise the naive one"})
                    continue
                sd_m = {kk: sd_fork[kk] + lam * tv[kk] for kk in KEYS}
                C.sd_load(mm, sd_m, dtype=DT)
                acc = evaluate(mm, tok_f, [lang])
                put(k, {"kind": "merge", "fork": name, "arm": arm, "lam": lam, "lang": lang,
                        "coord_share": diag["coord_share"], "acc": acc})
                del sd_m; gc.collect()
        del mm, sd_fork, tau_al, acts_f; gc.collect(); torch.cuda.empty_cache()
    except Exception:
        print(f"!! FORK FAIL {name}\n{traceback.format_exc()[-2000:]}", flush=True)
        gc.collect(); torch.cuda.empty_cache()
print("CHATVEC_DONE", flush=True)