File size: 9,071 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 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 | # MIT License, Bryan Cheng, 2026.
"""Merges: admixture from weights (RESEARCH_PLAN 5.5) and merge phenotype prediction (12, last line).
Candidates = the adapter population plus the rank-64 reductions of full fine-tunes (merges excluded). Pass 1: expressed
cross-Gram merges x candidates (summed over modules) and the merges' genotype coordinates on the population loci
(g = sum_i u_i (<E_m, E_i> - mean_j <E_j, E_i>) / sqrt(lambda)). Pass 2: Gram among the union of each merge's top-20
candidates by expressed cosine. Non-negative least squares of each merge's expressed delta on its 20 candidates gives
admixture proportions and the residual share. Predictions (transformed scale, population ECDF): admixture
(base + sum_p w_p (y_p - base)) and ridge on locus coordinates fitted on the adapter population.
python src/analysis/admixture.py --geno data/processed/qwen05 --adapters_dir data/raw/adapters/Qwen__Qwen2.5-0.5B-Instruct
--ft_dir data/raw/ft_reduced/Qwen__Qwen2.5-0.5B-Instruct --merge_index data/raw/hf_index/<base>.merge.jsonl
--pheno results/phenotypes/qwen05 --pheno_ft results/phenotypes/qwen05_finetune
--pheno_merge results/phenotypes/qwen05_merge --scan results/scans/qwen05 --out results/e1/merges_qwen05.json
"""
import argparse
import glob
import json
import os
import sys
import numpy as np
import torch
from scipy.optimize import nnls
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
from src.analysis.calibrate import ecdf_map # noqa: E402
from src.analysis.population import build # noqa: E402
from src.lorapop.adapters import load_module_factors # noqa: E402
from src.lorapop.basecov import P_for # noqa: E402
def cross_gram(f1, f2, P, dev, chunk=16384):
n1, n2 = len(f1), len(f2)
out = torch.zeros(n1, n2, dtype=torch.float64)
i1 = [i for i, f in enumerate(f1) if f is not None]
i2 = [i for i, f in enumerate(f2) if f is not None]
if not i1 or not i2:
return out
Pd = P.to(dev, torch.float32)
A1 = torch.cat([f1[i][0] for i in i1]).to(dev) @ Pd
B1 = torch.cat([f1[i][1] for i in i1], 1).to(dev)
s1 = torch.cat([torch.full((f1[i][0].shape[0],), j) for j, i in enumerate(i1)]).to(dev)
S1 = torch.zeros(A1.shape[0], len(i1), device=dev)
S1[torch.arange(A1.shape[0], device=dev), s1] = 1
res = torch.zeros(len(i1), len(i2), dtype=torch.float64)
for c0 in range(0, len(i2), 256):
sub = i2[c0:c0 + 256]
A2 = torch.cat([f2[i][0] for i in sub]).to(dev) @ Pd
B2 = torch.cat([f2[i][1] for i in sub], 1).to(dev)
s2 = torch.cat([torch.full((f2[i][0].shape[0],), j) for j, i in enumerate(sub)]).to(dev)
S2 = torch.zeros(A2.shape[0], len(sub), device=dev)
S2[torch.arange(A2.shape[0], device=dev), s2] = 1
M = (B1.T @ B2) * (A1 @ A2.T)
res[:, c0:c0 + len(sub)] = (S1.T @ M @ S2).double().cpu()
out[np.ix_(i1, i2)] = res
return out
def sq_norm(f, P, dev):
if f is None:
return 0.0
AP = f[0].to(dev) @ P.to(dev, torch.float32)
B = f[1].to(dev)
return float(((B.T @ B) * (AP @ AP.T)).sum())
def load_pheno(d, names):
out = {}
for x in names:
f = os.path.join(d, x + ".json")
if os.path.exists(f):
r = json.load(open(f))
if r.get("status") == "ok":
out[x] = r["traits"]
return out
def main():
ap = argparse.ArgumentParser()
for k in ("geno", "adapters_dir", "ft_dir", "merge_index", "pheno", "pheno_ft", "pheno_merge", "scan", "out"):
ap.add_argument("--" + k, required=True)
ap.add_argument("--top", type=int, default=20)
ap.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
a = ap.parse_args()
dev = a.device
A = json.load(open(os.path.join(a.geno, "adapters.json")))
names_all = A["names"]
merge_ids = {json.loads(l)["id"].replace("/", "__") for l in open(a.merge_index)}
red = sorted(os.path.basename(os.path.dirname(p)) for p in glob.glob(os.path.join(a.ft_dir, "*/_ok")))
merges = [x for x in red if x in merge_ids]
fts = [x for x in red if x not in merge_ids]
cands = [(a.adapters_dir, x) for x in names_all] + [(a.ft_dir, x) for x in fts]
cov = torch.load(os.path.join(a.geno, "basecov.pt"))
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")
m, N = len(merges), len(cands)
C = np.zeros((m, N))
dm, dc = np.zeros(m), np.zeros(N)
gm_cols, gm_meta = [], []
for mi, key in enumerate(mods):
layer, mod = key.split(".")
P = P_for(cov, int(layer), mod).float()
fm = [load_module_factors(os.path.join(a.ft_dir, x), {key}).get(key) for x in merges]
fc = [load_module_factors(os.path.join(d, x), {key}).get(key) for d, x in cands]
X = cross_gram(fm, fc, P, dev).numpy()
C += X
dm += np.diag(cross_gram(fm, fm, P, dev).numpy())
dc[: len(names_all)] += np.diag(np.asarray(ge[mi]))
dc[len(names_all):] += [sq_norm(f, P, dev) for f in fc[len(names_all):]]
lo = loci.get(key)
if lo is not None and lo["n_loci"]:
colmean = np.asarray(ge[mi]).mean(0)
U, lam = lo["U"].double().numpy(), lo["lam"].double().numpy()
for l in range(lo["n_loci"]):
gm_cols.append((X[:, : len(names_all)] - colmean[None]) @ U[:, l] / np.sqrt(lam[l]))
gm_meta.append((key, l))
print(key, flush=True)
cosC = C / np.sqrt(np.maximum(dm, 1e-300))[:, None] / np.sqrt(np.maximum(dc, 1e-300))[None]
top = np.argsort(-cosC, 1)[:, : a.top]
U_ = sorted(set(top.ravel().tolist()))
pos = {j: k for k, j in enumerate(U_)}
GU = np.zeros((len(U_), len(U_)))
for key in mods:
layer, mod = key.split(".")
P = P_for(cov, int(layer), mod).float()
f = [load_module_factors(os.path.join(cands[j][0], cands[j][1]), {key}).get(key) for j in U_]
GU += cross_gram(f, f, P, dev).numpy()
res = {"n_merges": m, "n_candidates": N, "n_ft_candidates": len(fts), "merges": []}
W = np.zeros((m, N))
for i in range(m):
J = top[i]
Gp = GU[np.ix_([pos[j] for j in J], [pos[j] for j in J])] + 1e-9 * np.eye(len(J)) * np.trace(GU) / len(U_)
R = np.linalg.cholesky(Gp).T
w, _ = nnls(R, np.linalg.solve(R.T, C[i, J]))
resid = (dm[i] - 2 * w @ C[i, J] + w @ Gp @ w) / dm[i]
W[i, J] = w
res["merges"].append({"top_cos": float(cosC[i, J[0]]), "n_parents_w_gt_0.05": int((w / max(w.sum(), 1e-12) > 0.05).sum()),
"sum_w": float(w.sum()), "residual_share": float(resid),
"parent_kinds": ["adapter" if j < len(names_all) else "finetune" for j in J[w > 0]]})
rs = np.array([r["residual_share"] for r in res["merges"]])
res["residual_share_median"] = float(np.median(rs)) if len(rs) else None
# phenotype prediction
Ppop = build(a.geno, a.pheno)
prim = json.load(open(os.path.join(a.scan, "primary_traits.json")))["primary"]
ph_c = {**load_pheno(a.pheno, names_all), **load_pheno(a.pheno_ft, fts)}
ph_m = load_pheno(a.pheno_merge, merges)
base = json.load(open(os.path.join(a.pheno, "__base__.json")))["traits"]
Gm = np.column_stack(gm_cols) if gm_cols else np.zeros((m, 0))
meta_idx = {(l["module"], l["l"]): j for j, l in enumerate(Ppop["loci"])}
cols = [k for k, mm in enumerate(gm_meta) if mm in meta_idx]
Gpop = Ppop["G"][:, [meta_idx[gm_meta[k]] for k in cols]]
pred = {}
for t in prim:
f = ecdf_map(Ppop["Y"][0, :, Ppop["traits"].index(t)])[0]
y_true, y_adm, y_loc = [], [], []
y = Ppop["Yt"][:, Ppop["traits"].index(t)]
ok = np.isfinite(y)
Z = Gpop[ok] - Gpop[ok].mean(0)
lam = 1.0 * len(Z)
beta = np.linalg.solve(Z.T @ Z + lam * np.eye(Z.shape[1]), Z.T @ (y[ok] - y[ok].mean()))
for i, x in enumerate(merges):
if x not in ph_m or t not in ph_m[x]:
continue
J = np.where(W[i] > 0)[0]
vals = [(W[i, j], ph_c.get(cands[j][1], {}).get(t)) for j in J]
vals = [(w, v[0]) for w, v in vals if v is not None]
if not vals:
continue
y_true.append(f(ph_m[x][t][0]))
y_adm.append(f(base[t][0] + sum(w * (v - base[t][0]) for w, v in vals)))
y_loc.append(y[ok].mean() + (Gm[i, cols] - Gpop[ok].mean(0)) @ beta)
if len(y_true) > 3:
pred[t] = {"n": len(y_true), "r_admixture": float(np.corrcoef(y_true, y_adm)[0, 1]),
"r_loci_ridge": float(np.corrcoef(y_true, y_loc)[0, 1])}
res["prediction"] = pred
os.makedirs(os.path.dirname(a.out), exist_ok=True)
json.dump(res, open(a.out, "w"), indent=1, default=float)
print(json.dumps({k: v for k, v in res.items() if k != "merges"}, default=float)[:2000], flush=True)
if __name__ == "__main__":
main()
|