File size: 15,782 Bytes
a4054b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
# MIT License, Bryan Cheng, 2026.
"""Designed crosses: parent choice and analysis (RESEARCH_PLAN 9.1, 9.3, 9.4, 9.5; E4, H4).

parents  30 adapters from different descent families with all 7 module types adapted in every layer, chosen by greedy
         max-min Euclidean distance on the transformed primary-trait vector (first pick at random, seed 0), + base.
layers   the 4 segments with the largest additive variance (mean over primary traits): on a layer design -> layers for
         module resolution; on a module design -> modules for direction resolution (plan 9.3).
analyze  traits on the population's transformed scale (ECDF map); offspring with reference perplexity > 3x base are
         reported and excluded. Additive OLS (segment x parent one-hot, base parent = reference) fitted on 80 percent,
         held-out R^2 on 20 percent relative to split-half reliability in offspring; adjacent-segment interaction
         (product of fitted additive contributions); gradient boosting on parent indicators. Segment calibration:
         measured alpha_{s,p} vs alpha_obs_{s,p} = sum over loci in the segment of beta_l x <E_p, e_l> (uncentred
         projection, i.e. relative to the base), per estimator; errors-in-variables slope through the origin.

  python src/analysis/crosses.py parents --geno ... --pheno ... --scan ... --adapters_dir ... --base ... --out parents.json
  python src/analysis/crosses.py layers  --design results/crosses/q05_layer/design.json --geno ... --pheno ... --scan ... --out parents_module.json
  python src/analysis/crosses.py analyze --design results/crosses/q05_layer/design.json --geno ... --pheno ... --scan ... --out x.json
"""
import argparse
import glob
import json
import os
import sys

import numpy as np
import torch

sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
from src.analysis.calibrate import deming0, ecdf_map  # noqa: E402
from src.analysis.population import build, reliability  # noqa: E402

EST = ["naive", "pc", "mm_f", "mm_fd", "wf_d", "wf_r", "dup_afe"]
MODS = ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]


def load_offspring(design_path, P, prim):
    D = json.load(open(design_path))
    recs = [json.load(open(f)) for f in glob.glob(os.path.join(os.path.dirname(design_path), "offspring", "*.json"))]
    recs = sorted(recs, key=lambda r: r["offspring"])
    maps = {t: ecdf_map(P["Y"][0, :, P["traits"].index(t)])[0] for t in prim}
    A = np.array([r["assign"] for r in recs], int).reshape(len(recs), len(D["segments"]))
    Y = np.full((3, len(recs), len(prim)), np.nan)
    for i, r in enumerate(recs):
        for j, t in enumerate(prim):
            v = r["traits"].get(t)
            if v is not None:
                Y[:, i, j] = [float(maps[t](x)) if x is not None and np.isfinite(x) else np.nan for x in v]
    deg = np.array([r.get("ppl_ratio", 1.0) > 3 for r in recs])
    hw = np.array([f"{r.get('gpu', '?')}|{r.get('bs', '?')}" for r in recs])
    return D, A, Y, deg, hw


def hw_center(Y, hw, rows):
    """Offspring are measured on several GPU models / batch sizes (D-035, D-038). Parents are assigned at random, so
    hardware is independent of genotype; each hardware group is shifted to the overall mean, with group and overall
    means estimated on `rows` only (training rows in analyze, so held-out offspring do not inform the adjustment)."""
    out = Y.copy()
    groups = np.unique(hw)
    if len(groups) < 2:
        return out
    with np.errstate(all="ignore"):
        mu = np.nanmean(Y[:, rows], 1)
        for g in groups:
            gm = hw == g
            if (gm & rows).sum() == 0:
                continue
            out[:, gm] = Y[:, gm] - np.nanmean(Y[:, gm & rows], 1)[:, None] + mu[:, None]
    return out


def direction_inner(D, geno, names_all, par_cols):
    """{(module, j): [n_parents, n_all]} expressed inner products <E_p^(j), E_i> of each parent's direction piece j
    (src/run/cross.py direction_pieces) with every population member i, computed from LoRA factors."""
    from src.lorapop.adapters import load_adapter
    from src.run.cross import NDIR, direction_pieces
    from src.run.intervene import Vk
    cov = torch.load(os.path.join(geno, "basecov.pt"))
    mks = sorted({k.split("#")[0] for g in D["segments"] for k in g if "#" in k})
    VL = {}
    for mk in mks:
        V, lam = Vk(cov, mk)
        VL[mk] = (V.double() * lam.double().clamp(min=0).sqrt()[None, :])
    pop = {}
    for i, x in enumerate(names_all):
        try:
            m = load_adapter(os.path.join(D["adapters_dir"], x), n_layers=24)["mods"]
        except Exception:
            continue
        pop[i] = {mk: (m[mk][0].double() @ VL[mk], m[mk][1].double()) for mk in mks if mk in m}  # (A V L^1/2, B)
    out = {}
    for mk in mks:
        for j in range(NDIR + 1):
            out[(mk, j)] = np.zeros((len(par_cols), len(names_all)))
        for r, pc in enumerate(par_cols):
            par = load_adapter(os.path.join(D["adapters_dir"], D["parents"][pc]), n_layers=24)["mods"]
            if mk not in par:
                continue
            V, lam = Vk(cov, mk)
            for j, piece in enumerate(direction_pieces(par[mk][0], par[mk][1], V, lam)):
                if piece is None:
                    continue
                Aj, Bj = piece[0].double() @ VL[mk], piece[1].double()
                for i, f in pop.items():
                    if mk in f:
                        out[(mk, j)][r, i] = float(((Bj.T @ f[mk][1]) * (Aj @ f[mk][0].T)).sum())
    return out


def onehot(A, npar, ref):
    n, S = A.shape
    cols = [p for p in range(npar) if p != ref]
    Xm = np.zeros((n, S * len(cols)))
    for s in range(S):
        for k, p in enumerate(cols):
            Xm[:, s * len(cols) + k] = A[:, s] == p
    return Xm, cols


def ols(X, y):
    Xc = np.column_stack([np.ones(len(X)), X])
    coef, *_ = np.linalg.lstsq(Xc, y, rcond=None)
    r = y - Xc @ coef
    s2 = r @ r / max(len(y) - np.linalg.matrix_rank(Xc), 1)
    cov = s2 * np.linalg.pinv(Xc.T @ Xc)
    return coef, np.sqrt(np.clip(np.diag(cov), 0, None))


def r2(y, yh):
    return float(1 - np.sum((y - yh) ** 2) / np.sum((y - y.mean()) ** 2))


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("cmd", choices=["parents", "layers", "analyze"])
    for k in ("geno", "pheno", "scan", "out"):
        ap.add_argument("--" + k, required=True)
    ap.add_argument("--design")
    ap.add_argument("--adapters_dir")
    ap.add_argument("--base")
    ap.add_argument("--n_parents", type=int, default=30)
    ap.add_argument("--seed", type=int, default=0)
    a = ap.parse_args()
    P = build(a.geno, a.pheno)
    prim = json.load(open(os.path.join(a.scan, "primary_traits.json")))["primary"]
    if a.cmd == "parents":
        Yp = np.column_stack([P["Yt"][:, P["traits"].index(t)] for t in prim])
        # every layer x module type adapted: nonzero expressed norm (diagonal of the per-module expressed gram) in all
        # 24 x 7 modules (info["modules"] lists module types only)
        mods = json.load(open(os.path.join(a.geno, "modules.json")))
        names_all = json.load(open(os.path.join(a.geno, "adapters.json")))["names"]
        pos = {x: i for i, x in enumerate(names_all)}
        ge = np.load(os.path.join(a.geno, "grams_exp.npy"), mmap_mode="r")
        diag = np.stack([np.diagonal(np.asarray(ge[mi])) for mi in range(len(mods))])
        assert set(mods) == set(f"{l}.{m}" for l in range(24) for m in MODS), "modules.json is not 24 x 7"
        ok = [i for i, x in enumerate(P["names"]) if np.all(diag[:, pos[x]] > 0) and np.all(np.isfinite(Yp[i]))]
        rng = np.random.default_rng(a.seed)
        sel = [int(rng.choice(ok))]
        while len(sel) < a.n_parents:
            used = {P["fam_d"][i] for i in sel}
            cand = [i for i in ok if P["fam_d"][i] not in used]
            if not cand:
                break
            dmin = np.min(np.linalg.norm(Yp[cand][:, None] - Yp[sel][None], axis=2), 1)
            sel.append(cand[int(np.argmax(dmin))])
        out = {"base": a.base, "adapters_dir": a.adapters_dir, "n_layers": 24,
               "parents": [P["names"][i] for i in sel] + ["__base__"], "n_eligible": len(ok)}
        json.dump(out, open(a.out, "w"), indent=1)
        print("parents", len(sel), "eligible", len(ok), flush=True)
        return
    D, A, Y, deg, hw = load_offspring(a.design, P, prim)
    npar, S = len(D["parents"]), A.shape[1]
    ref = D["parents"].index("__base__")
    keep = ~deg
    hw_groups = {g: int((hw[keep] == g).sum()) for g in np.unique(hw[keep])}
    Xm, cols = onehot(A[keep], npar, ref)
    if a.cmd == "layers":
        Y = hw_center(Y, hw, keep)
        var = np.zeros(S)
        for j in range(len(prim)):
            y = Y[0, keep, j]
            m = np.isfinite(y)
            coef, _ = ols(Xm[m], y[m])
            al = coef[1:].reshape(S, len(cols))
            var += np.var(np.column_stack([al, np.zeros(S)]), 1) / len(prim)
        top = sorted(np.argsort(-var)[:4].tolist())
        layers = [int(D["segments"][s][0].split(".")[0]) for s in top]
        # on a module-resolution design the top segments are modules -> direction-resolution parents (plan 9.3)
        out = {"base": D["base"], "adapters_dir": D["adapters_dir"], "n_layers": 24, "parents": D["parents"],
               "layers": sorted(set(layers)), "modules": [D["segments"][s][0] for s in top], "geno_dir": a.geno,
               "segment_additive_variance": var.tolist(), "resolution_in": D.get("resolution")}
        json.dump(out, open(a.out, "w"), indent=1)
        print("layers", layers, flush=True)
        return
    # analyze
    rng = np.random.default_rng(a.seed)
    n = int(keep.sum())
    te = np.zeros(n, bool)
    te[rng.permutation(n)[: n // 5]] = True
    train_full = keep.copy()
    train_full[keep] = ~te
    Y = hw_center(Y, hw, train_full)
    names_all = json.load(open(os.path.join(a.geno, "adapters.json")))["names"]
    pos = {x: i for i, x in enumerate(names_all)}
    loci = torch.load(os.path.join(a.geno, "loci.pt"))
    mods = json.load(open(os.path.join(a.geno, "modules.json")))
    ge = np.load(os.path.join(a.geno, "grams_exp.npy"), mmap_mode="r")
    lidx = {(l["module"], l["l"]): j for j, l in enumerate(P["loci"])}
    par_rows = [pos[p] for p in D["parents"] if p != "__base__"]
    par_cols = [k for k, p in enumerate(D["parents"]) if p != "__base__"]
    # uncentred projections of each parent on each locus, per segment
    proj = {}  # segment -> list of (locus index, [n_parents] projections)
    dip = direction_inner(D, a.geno, names_all, par_cols) if any("#" in k for g in D["segments"] for k in g) else {}
    for s, seg in enumerate(D["segments"]):
        proj[s] = []
        for key in seg:
            if "#" in key:  # direction piece: <E_p^(j), E_i> from factors, then the same locus projection
                mk, j = key.split("#")
                lo = loci.get(mk)
                if lo is None or not lo["n_loci"]:
                    continue
                U, lam = lo["U"].double().numpy(), lo["lam"].double().numpy()
                for l in range(lo["n_loci"]):
                    if (mk, l) in lidx:
                        proj[s].append((lidx[(mk, l)], dip[(mk, int(j))] @ U[:, l] / np.sqrt(lam[l])))
                continue
            lo = loci.get(key)
            if lo is None or not lo["n_loci"]:
                continue
            Gm = np.asarray(ge[mods.index(key)])[par_rows]
            U, lam = lo["U"].double().numpy(), lo["lam"].double().numpy()
            for l in range(lo["n_loci"]):
                if (key, l) in lidx:
                    proj[s].append((lidx[(key, l)], Gm @ U[:, l] / np.sqrt(lam[l])))
    scans = {t: np.load(os.path.join(a.scan, f"{t}.npz")) for t in prim}
    split = np.array(json.load(open(os.path.join(a.scan, "population.json")))["split"])
    pname = {x: i for i, x in enumerate(P["names"])}
    res = {"n_offspring": int(len(A)), "n_degenerate": int(deg.sum()), "segments": S, "parents": npar - 1,
           "resolution": D.get("resolution"), "hardware_groups": hw_groups, "traits": {}}
    pool = {e: ([], [], [], []) for e in EST}
    for j, t in enumerate(prim):
        y, h0, h1 = Y[0, keep, j], Y[1, keep, j], Y[2, keep, j]
        m = np.isfinite(y)
        rel = reliability(h0[m], h1[m])
        coef, _ = ols(Xm[m & ~te], y[m & ~te])
        Xc = np.column_stack([np.ones(n), Xm])
        r2_add = r2(y[m & te], Xc[m & te] @ coef)
        al = coef[1:].reshape(S, len(cols))
        contrib = np.stack([np.where(A[keep][:, s] == ref, 0.0, al[s, np.searchsorted(cols, np.where(A[keep][:, s] == ref, cols[0], A[keep][:, s]))])
                            for s in range(S)], 1)
        inter = np.column_stack([contrib[:, s] * contrib[:, s + 1] for s in range(S - 1)])
        coef_i, _ = ols(np.column_stack([Xm, inter])[m & ~te], y[m & ~te])
        r2_int = r2(y[m & te], np.column_stack([np.ones(n), Xm, inter])[m & te] @ coef_i)
        from sklearn.ensemble import HistGradientBoostingRegressor
        gb = HistGradientBoostingRegressor(categorical_features=list(range(S)), random_state=a.seed, max_iter=300)
        gb.fit(A[keep][m & ~te], y[m & ~te])
        r2_gb = r2(y[m & te], gb.predict(A[keep][m & te]))
        cf, se = ols(Xm[m], y[m])
        al_all, se_all = cf[1:].reshape(S, len(cols)), se[1:].reshape(S, len(cols))
        cal = {}
        for ei, e in enumerate(EST):
            for sub_name, sub_i in (("full", 0), ("other_half", None)):
                ao, vo = np.zeros((S, len(par_cols))), np.zeros((S, len(par_cols)))
                for s in range(S):
                    for li, pr in proj[s]:
                        for k, pc in enumerate(par_cols):
                            si = sub_i if sub_i is not None else (2 if split[pname[D["parents"][pc]]] == 0 else 1)
                            b, sb = scans[t]["beta"][ei, si, li], scans[t]["se"][ei, si, li]
                            if np.isfinite(b):
                                ao[s, k] += b * pr[k]
                                vo[s, k] += (sb * pr[k]) ** 2
                am = np.stack([al_all[:, cols.index(pc)] for pc in par_cols], 1)
                vm = np.stack([se_all[:, cols.index(pc)] ** 2 for pc in par_cols], 1)
                okk = np.isfinite(ao) & np.isfinite(am)
                cal[f"{e}:{sub_name}"] = deming0(ao[okk], vo[okk], am[okk], vm[okk])
                if sub_name == "full":
                    for L_, arr in zip(pool[e], (ao[okk], vo[okk], am[okk], vm[okk])):
                        L_.append(arr)
        res["traits"][t] = {"reliability_offspring": rel, "r2_additive_heldout": r2_add, "r2_with_interactions": r2_int,
                            "r2_gradient_boosting": r2_gb, "r2_additive_over_reliability": r2_add / rel if rel > 0 else None,
                            "segment_slope": cal, "alpha_sd": float(np.std(al_all))}
        print(t, "R2 add", round(r2_add, 3), "rel", round(rel, 3), "int", round(r2_int, 3), "gb", round(r2_gb, 3),
              "slope mm_fd", round(cal["mm_fd:full"], 3), flush=True)
    res["pooled_segment_slope"] = {e: deming0(*[np.concatenate(x) for x in pool[e]]) for e in EST}
    rr = [v["r2_additive_over_reliability"] for v in res["traits"].values() if v["r2_additive_over_reliability"] is not None]
    res["H4"] = {"median_r2_over_rel": float(np.median(rr)) if rr else None,
                 "slope_mm_fd": res["pooled_segment_slope"]["mm_fd"],
                 "supported": bool(rr and np.median(rr) >= 0.5 and 0.8 <= res["pooled_segment_slope"]["mm_fd"] <= 1.2)}
    json.dump(res, open(a.out, "w"), indent=1, default=float)
    print(json.dumps(res["H4"]), json.dumps(res["pooled_segment_slope"]), flush=True)


if __name__ == "__main__":
    main()