File size: 7,147 Bytes
795ea23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""POSITIVE CONTROL with GROUND TRUTH.

Take a real fork and act on it by a RANDOM element of the model's own symmetry group (per-layer
free-hidden-axis permutation + attention-head permutation). The permuted fork is *functionally
identical* -- same accuracy on every benchmark, exactly -- but it now lives in a different
parameterisation. The base model's chat vector is therefore being added in the wrong frame.

Ground truth: naive must collapse, and alignment must recover EXACTLY the unpermuted naive result.
This is the only cell in the study where we know the right answer in advance, so it tells us
whether the diagnostic's decision rule fires when it should, and calibrates the threshold.

usage: cv_control.py <forks.json> <gpu> <lambda> <fractions e.g. 0.125,0.25,0.5,1.0>
"""
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, tasks as TK, gmap
from mergeschool.core import alignment as AL, metrics as MT

FORKS = json.load(open(sys.argv[1]))
LAM = float(sys.argv[3])
FRACS = [float(x) for x in (sys.argv[4] if len(sys.argv) > 4 else "1.0").split(",")]
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, DT = "cuda", torch.bfloat16
done = C.jload(LEDGER)

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}={v:.4f}" for t, v in rec.get("acc", {}).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

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()
tok_base = C.load_tok(BASE); sents = C.flores_lines("eng_Latn", 256)
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()
print("base+tau ready", flush=True)

F = FORKS[0]
mf = C.load_model(F["repo"], dev="cpu", dtype=torch.float32)
sd_fork0 = C.sd_np(mf); del mf; gc.collect()
tok_f = C.load_tok(F["repo"]); lang = F["lang"]
mm = C.load_model(F["repo"], dev=DEV, dtype=DT)
LAYER_PRES = sorted({p for p in (AL._layer_prefix(n) for n in sd_fork0) if p})
AXES = AL.free_hidden_axes(sd_fork0, HID)

for frac in FRACS:
    name = f'{F["name"]}_PERM{frac}'
    try:
        rng = np.random.default_rng(int(frac * 1000))
        npick = max(1, int(round(frac * len(LAYER_PRES))))
        picked = set(rng.choice(LAYER_PRES, size=npick, replace=False).tolist())
        hperm = {pre: rng.permutation(ax["f"]) for pre, ax in AXES.items() if pre in picked}
        sd_fork = AL.apply_hidden_perms(sd_fork0, hperm, HID)
        aperm = gmap.random_gqa_head_perms(sd_fork0, HID, NH, NKV, rng, only=picked)
        sd_fork = gmap.apply_gqa_head_perms(sd_fork, aperm, HID, NH, NKV)
        print(f"### {name}: permuted {npick}/{len(LAYER_PRES)} layers", flush=True)

        k = f"{name}|fork_alone"
        if k not in done:
            C.sd_load(mm, sd_fork, dtype=DT)
            put(k, {"kind": "control", "fork": name, "arm": "fork_alone", "lam": None, "lang": lang,
                    "frac_layers_permuted": frac, "model": F["repo"],
                    "acc": evaluate(mm, tok_f, [lang]),
                    "note": "random symmetry-group action: must match the unpermuted fork exactly"})

        C.sd_load(mm, sd_fork, dtype=DT)
        acts_f = C.capture_acts_sent(mm, tok_f, sents, DEV)

        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", verbose=False, n_kv_heads=NKV)
            a = np.concatenate([sd_base[x].ravel() for x in KEYS]); b = np.concatenate([sd_fork[x].ravel() for x in KEYS])
            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)); del a, b; gc.collect()
            L = sorted(set(acts_f) & set(acts_base))
            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["fit_seconds"] = time.time() - t0
            info["frac_layers_permuted"] = frac
            info = {kk: (v.tolist() if isinstance(v, np.ndarray) else v) for kk, v in info.items()}
            np.save(f"/root/merge-accuracy/results/g_{name}.npy", np.array([g], dtype=object), allow_pickle=True)
            put(kd, {"kind": "diag", "fork": name, "arm": "diag", "lang": lang, "diag": info})
            print(f"  DIAG {name}: coord_share={info['coord_share']:.4f} identity={info['is_identity']} "
                  f"hidden={info['hidden']} heads={info['heads']} {info['fit_seconds']:.0f}s", flush=True)
        else:
            g = np.load(f"/root/merge-accuracy/results/g_{name}.npy", allow_pickle=True)[0]
        diag = done[kd]["diag"]
        del acts_f; gc.collect()

        tau_al = gmap.apply_g(tau, g, HID, NH)
        for arm, tv in (("naive", tau), ("aligned", tau_al)):
            k = f"{name}|{arm}|lam{LAM}"
            if k in done: continue
            sd_m = {kk: sd_fork[kk] + LAM * tv[kk] for kk in KEYS}
            C.sd_load(mm, sd_m, dtype=DT)
            put(k, {"kind": "control", "fork": name, "arm": arm, "lam": LAM, "lang": lang,
                    "frac_layers_permuted": frac, "coord_share": diag["coord_share"],
                    "acc": evaluate(mm, tok_f, [lang])})
            del sd_m; gc.collect()
        del tau_al, sd_fork; gc.collect()
    except Exception:
        print(f"!! CONTROL FAIL {name}\n" + traceback.format_exc()[-2000:], flush=True)
        gc.collect(); torch.cuda.empty_cache()
print("CONTROL_DONE", flush=True)