lorapop / code /src /analysis /crosses.py
bryan7264's picture
Add files using upload-large-folder tool
aaba844 verified
Raw History Blame Contribute Delete
15.9 kB
# 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 of measured on
predicted (D-043).
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(am[okk], vm[okk], ao[okk], vo[okk]) # measured on predicted (D-043)
if sub_name == "full":
for L_, arr in zip(pool[e], (am[okk], vm[okk], ao[okk], vo[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()