File size: 7,582 Bytes
aaba844
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# MIT License, Bryan Cheng, 2026.
"""E1 on trained seed siblings (RESEARCH_PLAN 5.2, 5.3, 6.1; hypothesis H1).

Law: cos ~ sqrt(r_i r_j) / sqrt((r_i + 1 + d)(r_j + 1 + d)); raw d = q_m (input dim), expressed
d_C = tr(C) |G|^2 / tr(G C G^T) with G the base gradient of the task at B = 0 and C the base input second moment
(top-k truncation, as used for K_func). Totals are norm-weighted module averages, so the prediction for a pair is
sum_m law_m |D_i,m| |D_j,m| / (|D_i| |D_j|).
Outputs: law test per rank cell (independent-init same-task pairs, raw and expressed), H1 verdicts, AUC of K_func for
same- vs different-task pairs (independent init), descent-rule detection of shared-init pairs, and the recipe threshold
(1 - 99th percentile of K_func between different-task independent-init pairs; plan 5.3).

  python src/analysis/e1_siblings.py --runs data/raw/train_data/runs_siblings.jsonl --trained data/raw/trained/siblings
         --geno data/processed/qwen05 --out results/e1/siblings_qwen05.json
"""
import argparse
import json
import os
import sys

import numpy as np
import torch
from sklearn.metrics import roc_auc_score

sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
from src.lorapop.adapters import load_module_factors  # noqa: E402
from src.lorapop.basecov import P_for  # noqa: E402
from src.lorapop.kinship import module_gram  # noqa: E402


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("--runs", required=True)
    ap.add_argument("--trained", required=True)
    ap.add_argument("--geno", required=True)
    ap.add_argument("--out", required=True)
    ap.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
    a = ap.parse_args()
    runs = [json.loads(l) for l in open(a.runs)]
    runs = [r for r in runs if os.path.exists(os.path.join(a.trained, r["name"], "adapter_model.safetensors"))]
    n = len(runs)
    names = [r["name"] for r in runs]
    rk = np.array([r["r"] for r in runs], float)
    task = np.array([r["task"] for r in runs])
    shared = np.array([r["shared_init"] for r in runs])
    seed = np.array([r["seed"] for r in runs])
    cov = torch.load(os.path.join(a.geno, "basecov.pt"))
    mods = json.load(open(os.path.join(a.geno, "modules.json")))
    grads = {}
    for t in sorted(set(task)):
        gf = os.path.join(a.trained, "grad_task_" + t.replace(" ", "") + ".pt")
        grads[t] = torch.load(gf, mmap=True) if os.path.exists(gf) else None  # memory-mapped: 8 x 0.7 GB files
    Graw, Gexp = np.zeros((n, n)), np.zeros((n, n))
    Praw, Pexp = np.zeros((n, n)), np.zeros((n, n))  # law-predicted inner products
    dC_log = {}
    for key in mods:
        layer, mod = key.split(".")
        f = [load_module_factors(os.path.join(a.trained, x), {key}).get(key) for x in names]
        if all(v is None for v in f):
            continue
        P = P_for(cov, int(layer), mod).float()
        gr = module_gram(f, None, a.device).numpy()
        ge = module_gram(f, P, a.device).numpy()
        Graw += gr
        Gexp += ge
        q = next(v[0].shape[1] for v in f if v is not None)
        nr, ne = np.sqrt(np.clip(np.diag(gr), 0, None)), np.sqrt(np.clip(np.diag(ge), 0, None))
        Praw += law(rk[:, None], rk[None], q) * nr[:, None] * nr[None]
        dC = np.full(n, np.nan)
        for t, G in grads.items():
            if G is None or key not in G:
                continue
            Gm = G[key].float().to(a.device)
            Pd = P.to(a.device)
            val = float((Pd ** 2).sum() * (Gm ** 2).sum() / ((Gm @ Pd) ** 2).sum())
            dC[task == t] = val
            dC_log.setdefault(t, {})[key] = val
        dd = 0.5 * (dC[:, None] + dC[None])  # same-task pairs share d_C exactly
        Pexp += law(rk[:, None], rk[None], dd) * ne[:, None] * ne[None]
    d1, d2 = np.sqrt(np.diag(Graw)), np.sqrt(np.diag(Gexp))
    Kd, Kf = Graw / d1[:, None] / d1[None], Gexp / d2[:, None] / d2[None]
    Ld, Lf = Praw / d1[:, None] / d1[None], Pexp / d2[:, None] / d2[None]
    iu = np.triu_indices(n, 1)
    same_t = (task[:, None] == task[None])[iu]
    both_ind = (~shared[:, None] & ~shared[None])[iu]
    same_r = (rk[:, None] == rk[None])[iu]
    both_sh = (shared[:, None] & shared[None])[iu]
    diff_seed = (seed[:, None] != seed[None])[iu]
    out = {"n_adapters": n, "law_cells": [], "d_C_median_by_task": {t: float(np.median(list(v.values())))
                                                                  for t, v in dC_log.items()}}
    sib = same_t & both_ind
    for r1 in sorted(set(rk)):
        for r2 in sorted(set(rk)):
            if r2 < r1:
                continue
            m = sib & (np.minimum(rk[iu[0]], rk[iu[1]]) == r1) & (np.maximum(rk[iu[0]], rk[iu[1]]) == r2)
            if r1 == r2:
                m &= diff_seed
            if m.sum() == 0:
                continue
            cell = {"r1": int(r1), "r2": int(r2), "n_pairs": int(m.sum()),
                    "raw_obs": float(Kd[iu][m].mean()), "raw_law": float(Ld[iu][m].mean()),
                    "exp_obs": float(Kf[iu][m].mean()), "exp_law": float(np.nanmean(Lf[iu][m]))}
            cell["raw_ratio"] = cell["raw_obs"] / cell["raw_law"]
            cell["exp_ratio"] = cell["exp_obs"] / cell["exp_law"]
            out["law_cells"].append(cell)
    rr = np.array([c["raw_ratio"] for c in out["law_cells"]])
    er = np.array([c["exp_ratio"] for c in out["law_cells"]])
    pr = Kd[iu][sib] / Ld[iu][sib]
    out["raw_ratio_geomean"] = float(np.exp(np.mean(np.log(np.abs(rr))))) if len(rr) else None
    out["exp_ratio_geomean"] = float(np.exp(np.nanmean(np.log(np.abs(er))))) if len(er) else None
    out["raw_pairs_within_factor2"] = float(np.mean((pr >= 0.5) & (pr <= 2))) if len(pr) else None
    out["auc_Kfunc_same_vs_diff_task_indep"] = float(roc_auc_score(same_t[both_ind], Kf[iu][both_ind]))
    out["auc_Kdesc_same_vs_diff_task_indep"] = float(roc_auc_score(same_t[both_ind], Kd[iu][both_ind]))
    m = same_r & ~same_t & (both_sh | both_ind)
    out["auc_Kdesc_shared_vs_indep_init_difftask_samerank"] = float(roc_auc_score(both_sh[m], Kd[iu][m]))
    thr = 3 * law(rk[iu[0]], rk[iu[1]], 896)
    flag = Kd[iu] > thr
    out["descent_rule"] = {"flag_rate_shared_init_same_rank": float(flag[both_sh & same_r].mean()),
                           "flag_rate_indep_diff_task": float(flag[both_ind & ~same_t].mean()),
                           "flag_rate_indep_same_task": float(flag[sib].mean())}
    kf_diff = Kf[iu][both_ind & ~same_t]
    out["recipe_threshold_kfunc_p99"] = float(np.quantile(kf_diff, 0.99))
    out["recipe_threshold_distance"] = 1 - out["recipe_threshold_kfunc_p99"]
    out["H1"] = {"raw_cells_within_factor2": bool(np.all((rr >= 0.5) & (rr <= 2))) if len(rr) else None,
                 "auc_ge_0.8": out["auc_Kfunc_same_vs_diff_task_indep"] >= 0.8}
    out["H1"]["supported"] = bool(out["H1"]["raw_cells_within_factor2"] and out["H1"]["auc_ge_0.8"])
    os.makedirs(os.path.dirname(a.out), exist_ok=True)
    json.dump(out, open(a.out, "w"), indent=1)
    np.savez(a.out.replace(".json", "_K.npz"), K_desc=Kd, K_func=Kf, law_raw=Ld, law_exp=Lf, names=np.array(names))
    print(json.dumps({k: v for k, v in out.items() if k not in ("law_cells", "d_C_median_by_task")}, indent=0))
    for c in out["law_cells"]:
        print(c["r1"], c["r2"], c["n_pairs"], round(c["raw_obs"], 4), round(c["raw_law"], 4), round(c["exp_obs"], 4),
              round(c["exp_law"], 4), flush=True)


if __name__ == "__main__":
    main()