File size: 8,014 Bytes
525b620
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# MIT License, Bryan Cheng, 2026.
"""Phase 2 feasibility probe on Qwen2.5-0.5B-Instruct adapters.

1. load and check the downloaded adapters; 2. raw (descent) relatedness from factors; 3. base input second
moments and expressed (function) relatedness; 4. similarity-law simulation with real C; 5. timed mini-battery
on the base and a few adapters. Writes results/probe/*.json.
"""
import argparse
import glob
import json
import os
import sys
import time

import numpy as np
import torch

sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
from src.lorapop.adapters import AdapterError, check_shapes, load_adapter  # noqa: E402
from src.lorapop.basecov import eig_summary, input_moments, P_for, reference_texts  # noqa: E402
from src.lorapop.kinship import cosine, total_gram  # noqa: E402

BASE = "Qwen/Qwen2.5-0.5B-Instruct"


def law(r1, r2, d):
    return np.sqrt(r1 * r2) / np.sqrt((r1 + 1 + d) * (r2 + 1 + d))


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--adapters", default="data/raw/adapters/Qwen__Qwen2.5-0.5B-Instruct")
    ap.add_argument("--out", default="results/probe")
    ap.add_argument("--n_ref", type=int, default=600)
    ap.add_argument("--n_battery_adapters", type=int, default=8)
    a = ap.parse_args()
    os.makedirs(a.out, exist_ok=True)
    from transformers import AutoModelForCausalLM, AutoTokenizer
    dev = "cuda"
    print("GPU", torch.cuda.get_device_name(0), flush=True)
    tok = AutoTokenizer.from_pretrained(BASE)
    model = AutoModelForCausalLM.from_pretrained(BASE, torch_dtype=torch.bfloat16).to(dev).eval()
    shapes = {}
    for n, mod in model.model.layers[0].named_modules():
        if isinstance(mod, torch.nn.Linear):
            shapes[n.split(".")[-1]] = tuple(mod.weight.shape)
    nL = len(model.model.layers)

    # 1. adapters
    t0 = time.time()
    ads, names, fails = [], [], {}
    for d in sorted(glob.glob(os.path.join(a.adapters, "*/_ok"))):
        d = os.path.dirname(d)
        try:
            ad = load_adapter(d, n_layers=nL)
            check_shapes(ad, shapes)
            ads.append(ad)
            names.append(os.path.basename(d))
        except (AdapterError, Exception) as e:
            fails[os.path.basename(d)] = f"{type(e).__name__}: {e}"[:200]
    cfg_base = [json.load(open(os.path.join(a.adapters, n, "adapter_config.json"))).get("base_model_name_or_path")
                for n in names]
    load_info = {"n_ok": len(ads), "n_fail": len(fails), "fails": fails, "load_s": time.time() - t0,
                 "ranks": {n: ad["ranks"] for n, ad in zip(names, ads)},
                 "modules": {n: ad["modules"] for n, ad in zip(names, ads)},
                 "flags": {n: ad["flags"] for n, ad in zip(names, ads)}, "declared_base": dict(zip(names, cfg_base))}
    print("adapters ok", len(ads), "fail", len(fails), flush=True)

    # 2. raw relatedness
    keys = sorted({k for ad in ads for k in ad["mods"]}, key=lambda k: (int(k.split(".")[0]), k))
    mods = [ad["mods"] for ad in ads]
    t0 = time.time()
    Graw, per_raw = total_gram(mods, keys, None, dev)
    Kraw = cosine(Graw).numpy()
    t_raw = time.time() - t0

    # 3. base covariances and expressed relatedness
    t0 = time.time()
    texts = reference_texts(tok, "data/raw", n_total=a.n_ref, seed=0)
    allt = texts["plain"] + texts["chat"] + texts["instruction"]
    C, ntok = input_moments(model, tok, allt, max_len=512, batch_size=16, device=dev)
    cov = {k: eig_summary(v) for k, v in C.items()}
    t_cov = time.time() - t0
    torch.save(cov, os.path.join(a.out, "basecov_probe.pt"))
    cov_info = {k: {"k99": v["k99"], "deff": v["deff"], "trace": v["trace"], "dim": int(v["V"].shape[0])}
                for k, v in cov.items()}
    t0 = time.time()
    Pcache = {}

    def Pmap(k):
        layer, mod = k.split(".")
        if k not in Pcache:
            Pcache[k] = P_for(cov, int(layer), mod)
        return Pcache[k]

    Gexp, per_exp = total_gram(mods, keys, Pmap, dev)
    Kexp = cosine(Gexp).numpy()
    t_exp = time.time() - t0
    iu = np.triu_indices(len(ads), 1)
    np.savez(os.path.join(a.out, "kinship_probe.npz"), Kraw=Kraw, Kexp=Kexp, names=np.array(names))

    def q(x):
        return {p: float(np.quantile(x, p / 100)) for p in (5, 25, 50, 75, 95, 99)}

    kin = {"n": len(ads), "raw_offdiag_quantiles": q(Kraw[iu]), "exp_offdiag_quantiles": q(Kexp[iu]),
           "n_pairs": int(len(iu[0])), "raw_pairs_gt": {t: int((Kraw[iu] > t).sum()) for t in (0.01, 0.05, 0.1, 0.5, 0.9)},
           "corr_raw_exp_offdiag": float(np.corrcoef(Kraw[iu], Kexp[iu])[0, 1]),
           "t_raw_s": t_raw, "t_cov_s": t_cov, "t_exp_s": t_exp, "ntok_ref": {k: int(v) for k, v in ntok.items()}}
    print(json.dumps(kin, indent=1), flush=True)

    # 4. similarity-law simulation with real C (layer 12 attention input, q_proj-shaped output)
    sim = []
    gen = torch.Generator(device="cpu").manual_seed(0)
    Cm = C["12.attn_in"].float().to(dev)
    qd = Cm.shape[0]
    pdim = shapes["q_proj"][0]
    Z = torch.randn(pdim, qd, generator=gen).to(dev)
    for Gname, Gmat in (("G=Z (isotropic rows)", Z), ("G=Z C (rows in data span)", Z @ Cm)):
        dI = float(qd * (Gmat ** 2).sum() / (Gmat @ Gmat.T).trace())
        dC = float(Cm.trace() * (Gmat ** 2).sum() / (Gmat @ Cm @ Gmat.T).trace())
        for r in (4, 8, 16, 32, 64):
            cr, cc = [], []
            for rep in range(100):
                A1 = torch.randn(r, qd, generator=gen).to(dev)
                A2 = torch.randn(r, qd, generator=gen).to(dev)
                D1, D2 = Gmat @ A1.T @ A1, Gmat @ A2.T @ A2
                cr.append(float((D1 * D2).sum() / D1.norm() / D2.norm()))
                n1 = (D1 @ Cm @ D1.T).trace().sqrt()
                n2 = (D2 @ Cm @ D2.T).trace().sqrt()
                cc.append(float((D1 @ Cm @ D2.T).trace() / n1 / n2))
            sim.append({"G": Gname, "r": r, "raw_mean": float(np.mean(cr)), "raw_se": float(np.std(cr) / 10),
                        "raw_law": float(law(r, r, dI)), "dI": dI, "C_mean": float(np.mean(cc)),
                        "C_se": float(np.std(cc) / 10), "C_law": float(law(r, r, dC)), "dC": dC})
            print(sim[-1], flush=True)
    del Cm, Z

    # 5. timed mini-battery
    from src.lorapop.battery import Battery, build_items, per_item_scores, summarize
    from src.lorapop.deltas import adapter_updates, clear, patch_model, set_updates
    items = build_items("data/raw", sizes={"mmlu_per_subject": 10, "mwe_per_set": 100, "gen_general": 64,
                                           "gen_json": 30, "gen_ifeval": 64, "ifeval_max_new": 384})
    table = patch_model(model)
    bat = Battery(model, tok, items, device=dev, batch_size=32, gen_batch_size=64)
    timing, summaries = {}, {}
    order = ["__base__"] + names[:a.n_battery_adapters]
    for i, nm in enumerate(order):
        if nm == "__base__":
            clear(table)
        else:
            set_updates(table, adapter_updates(ads[names.index(nm)]["mods"]), device=dev)
        t_tr = {}
        raw = {}
        for tr in items:
            t0 = time.time()
            raw.update(bat.run(traits=[tr]))
            torch.cuda.synchronize()
            t_tr[tr] = time.time() - t0
        timing[nm] = t_tr
        summaries[nm] = summarize(per_item_scores(items, raw))
        if i < 2:
            ex = {k: v["text"][:3] for k, v in raw.items() if "text" in v}
            json.dump(ex, open(os.path.join(a.out, f"gen_examples_{i}.json"), "w"), indent=1)
        print(nm, {k: round(v, 1) for k, v in t_tr.items()}, flush=True)
    n_items = {k: len(v.get("prompts") or v.get("items")) for k, v in items.items()}
    json.dump({"load": load_info, "kinship": kin, "law_sim": sim, "battery_timing_s": timing,
               "battery_items": n_items, "battery_summaries": summaries,
               "gpu": torch.cuda.get_device_name(0)}, open(os.path.join(a.out, "probe_feasibility.json"), "w"), indent=1)
    print("PROBEDONE", flush=True)


if __name__ == "__main__":
    main()