File size: 11,432 Bytes
a8b5668
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# MIT License, Bryan Cheng, 2026.
"""Spike-ins (RESEARCH_PLAN 10; E5), GPU part: build each spike direction, its expressed projections onto every
population adapter (per module, for the genotype shift of carriers) and its population SD, then measure carriers at
doses 0 and c x SD (c in plan["doses"]) with the battery. The base is measured at 0 and 1 SD.
--target_only (D-032): the base is measured at 0 and 1 SD with the full battery; the target trait (primary trait with the
largest |ECDF-mapped change|, the rule of src/analysis/spikein.py) fixes one item set, and carriers are measured on that
item set only, c = 0 once per (item set, carrier) under out/__zero__[_h<half>]/. --gen_half as in intervene.py (plan 4.5).

Directions (unit total expressed norm):
  opposite  mean update of the side-a fine-tunes minus mean of side-b (all modules; plan 6.2)
  locus     allele of a validated locus (one module)
  random    rank-4 Gaussian product in one module (seeded)

  python src/run/spikein.py --plan results/spikein/plan_qwen05.json --out results/spikein/qwen05 [--shard i --nshards n]
plan: {"base", "adapters_dir", "geno_dir", "doses", "carriers": [names],
       "directions": [{"id", "kind", "module", "l", "seed", "side_a": [dirs], "side_b": [dirs]}]}
"""
import argparse
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 load_adapter, load_module_factors  # noqa: E402
from src.lorapop.basecov import P_for  # noqa: E402
from src.lorapop.battery import Battery, build_items  # noqa: E402
from src.lorapop.deltas import adapter_updates, clear, merge_updates, patch_model, set_bank  # noqa: E402
from src.lorapop.genotype import allele, lowrank  # noqa: E402
from src.run.intervene import Vk, restrict_gen_half  # noqa: E402
from src.run.phenotype import FULL, PILOT, TINY, summarise_raw  # noqa: E402

GEN_SETS = {"gen.": "gen_general", "ife.": "gen_ifeval", "json.": "gen_json"}


def itemset_of(trait, items):
    """Battery item set that produces a trait (gen./ife./json. traits; item-set name; or name before the last dot)."""
    for p, s in GEN_SETS.items():
        if trait.startswith(p):
            return s
    if trait in items:
        return trait
    s = trait.rsplit(".", 1)[0]
    if s in items:
        return s
    raise KeyError(trait)


def pop_maps(pheno, prim, names):
    """ECDF maps of the primary traits over the population's ok records (as population.build / calibrate.ecdf_map)."""
    from src.analysis.calibrate import ecdf_map
    ys = {t: [] for t in prim}
    for n in names:
        f = os.path.join(pheno, n + ".json")
        if not os.path.exists(f):
            continue
        r = json.load(open(f))
        if r.get("status") != "ok":
            continue
        for t in prim:
            v = r["traits"].get(t)
            ys[t].append(v[0] if v is not None else np.nan)
    return {t: ecdf_map(np.array(v, float))[0] for t, v in ys.items()}


def build_direction(d, plan, cov, loci, names, table, nL, dev):
    """Returns {module: dense D (p x q) on dev} with unit total expressed norm."""
    D = {}
    if d["kind"] == "locus":
        key = d["module"]
        f = [load_module_factors(os.path.join(plan["adapters_dir"], n), {key}).get(key) for n in names]
        V, _ = Vk(cov, key)
        D[key] = allele(f, loci[key]["U"][:, d["l"]], loci[key]["lam"][d["l"]], V, device=dev).float()
    elif d["kind"] == "random":
        key = d["module"]
        gen = torch.Generator().manual_seed(int(d["seed"]))
        p, q = table[key].lin.weight.shape
        D[key] = (torch.randn(p, 4, generator=gen) @ torch.randn(4, q, generator=gen)).to(dev)
    else:
        for side, sgn in (("side_a", 1.0), ("side_b", -1.0)):
            for path in d[side]:
                for key, (A, B) in load_adapter(path, n_layers=nL)["mods"].items():
                    M = (B.to(dev) @ A.to(dev)) * (sgn / len(d[side]))
                    D[key] = D[key] + M if key in D else M
    tot = 0.0
    for key, M in D.items():
        layer, mod = key.split(".")
        tot += float(((M @ P_for(cov, int(layer), mod).to(dev)) ** 2).sum())
    return {k: M / np.sqrt(tot) for k, M in D.items()}


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--plan", required=True)
    ap.add_argument("--out", required=True)
    ap.add_argument("--shard", type=int, default=0)
    ap.add_argument("--nshards", type=int, default=1)
    ap.add_argument("--group", type=int, default=8)
    ap.add_argument("--sizes", default="full", choices=["full", "pilot", "tiny"])
    ap.add_argument("--device", default="cuda")
    ap.add_argument("--bs", type=int, default=128)
    ap.add_argument("--gbs", type=int, default=256)
    ap.add_argument("--target_only", action="store_true", help="D-032: carriers on the target trait's item set only")
    ap.add_argument("--pheno", default="results/phenotypes/qwen05", help="population phenotypes (target-trait maps)")
    ap.add_argument("--primary", default="results/scans/qwen05/primary_traits.json")
    ap.add_argument("--gen_half", type=int, default=-1, choices=[-1, 0, 1], help="plan 4.5 (as intervene.py)")
    a = ap.parse_args()
    plan = json.load(open(a.plan))
    dev = a.device
    from transformers import AutoModelForCausalLM, AutoTokenizer
    tok = AutoTokenizer.from_pretrained(plan["base"])
    tok.padding_side = "left"
    model = AutoModelForCausalLM.from_pretrained(plan["base"], dtype=torch.bfloat16 if dev == "cuda" else torch.float32)
    model = model.to(dev).eval()
    nL = len(model.model.layers)
    table = patch_model(model)
    items = build_items("data/raw", sizes={"full": FULL, "pilot": PILOT, "tiny": TINY}[a.sizes], seed=0)
    if a.gen_half >= 0:
        restrict_gen_half(items, a.gen_half)
    bat = Battery(model, tok, items, device=dev, batch_size=a.bs, gen_batch_size=a.gbs)
    G = plan["geno_dir"]
    cov = torch.load(os.path.join(G, "basecov.pt"))
    loci = torch.load(os.path.join(G, "loci.pt"))
    A = json.load(open(os.path.join(G, "adapters.json")))
    names = A["names"]
    mods = json.load(open(os.path.join(G, "modules.json")))
    if a.target_only:
        prim = json.load(open(a.primary))["primary"]
        maps = pop_maps(a.pheno, prim, [n for n in names if not A["info"][n]["flags"].get("dora")])
    for d in plan["directions"][a.shard::a.nshards]:
        od = os.path.join(a.out, d["id"])
        os.makedirs(od, exist_ok=True)
        pf = os.path.join(od, "direction.npz")
        Dm = build_direction(d, plan, cov, loci, names, table, nL, dev)
        fac = {k: lowrank(M) for k, M in Dm.items()}
        if not os.path.exists(pf):
            proj = np.zeros((len(mods), len(names)))
            for mi, key in enumerate(mods):
                if key not in Dm:
                    continue
                layer, mod = key.split(".")
                Pm = P_for(cov, int(layer), mod).to(dev).float()
                DP = Dm[key] @ Pm
                for i, n in enumerate(names):
                    f = load_module_factors(os.path.join(plan["adapters_dir"], n), {key}).get(key)
                    if f is not None:
                        proj[mi, i] = float(((f[1].to(dev) @ (f[0].to(dev) @ Pm)) * DP).sum())
            sigma = float(proj.sum(0).std())
            np.savez(pf, proj=proj, sigma=sigma, modules=np.array(mods),
                     lowrank_residual=np.array([float(v[2]) for v in fac.values()]))
        sigma = float(np.load(pf)["sigma"])
        ups_d = {k: [(A.cpu(), B.cpu())] for k, (A, B, _) in fac.items()}

        def run(grp, sets=None):
            ups = []
            for name, c in grp:
                base_up = {} if name == "__base__" else adapter_updates(
                    load_adapter(os.path.join(plan["adapters_dir"], name), n_layers=nL)["mods"])
                spike = {k: [(A, B, c * sigma)] for k, [(A, B)] in ups_d.items()} if c != 0 else {}
                ups.append(merge_updates(base_up, spike))
            set_bank(table, ups, device=dev)
            bat.nb = len(ups)
            raws = bat.run_multi(sets)
            clear(table)
            bat.nb = 1
            return [summarise_raw(items, raw)[0] for raw in raws]

        t0 = time.time()
        if not a.target_only:
            combos = [("__base__", 0.0), ("__base__", 1.0)] + [(c, x) for c in plan["carriers"] for x in [0.0] + plan["doses"]]
            todo = [cb for cb in combos if not os.path.exists(os.path.join(od, f"{cb[0]}.json"))]
            by = {}
            for g0 in range(0, len(todo), a.group):
                grp = todo[g0:g0 + a.group]
                for (name, c), summ in zip(grp, run(grp)):
                    by.setdefault(name, {})[str(c)] = summ
                for name in list(by):
                    need = [0.0, 1.0] if name == "__base__" else [0.0] + plan["doses"]
                    if all(str(x) in by[name] for x in need):
                        json.dump({"name": name, "sigma": sigma, "doses": by.pop(name)},
                                  open(os.path.join(od, f"{name}.json"), "w"))
            print(d["id"], len(todo), "combos", round(time.time() - t0), "s", flush=True)
            continue
        # D-032: full battery on the base (0, 1 SD) fixes the target trait; carriers are measured on its item set only,
        # with c = 0 shared across directions that share the item set (out/__zero__/<item set>/<carrier>.json)
        bf = os.path.join(od, "__base__.json")
        if not os.path.exists(bf):
            s0, s1 = run([("__base__", 0.0), ("__base__", 1.0)])
            json.dump({"name": "__base__", "sigma": sigma, "doses": {"0.0": s0, "1.0": s1}}, open(bf, "w"))
        bse = json.load(open(bf))["doses"]
        tr = max(prim, key=lambda t: abs(maps[t](bse["1.0"][t][0]) - maps[t](bse["0.0"][t][0])))
        S = itemset_of(tr, items)
        json.dump({"target": tr, "itemset": S, "gen_half": a.gen_half}, open(os.path.join(od, "target.json"), "w"))
        zd = os.path.join(a.out, "__zero__" + (f"_h{a.gen_half}" if a.gen_half >= 0 else ""), S)
        os.makedirs(zd, exist_ok=True)
        todo = []
        for c in plan["carriers"]:
            if os.path.exists(os.path.join(od, f"{c}.json")):
                continue
            todo += ([] if os.path.exists(os.path.join(zd, f"{c}.json")) else [(c, 0.0)]) + [(c, x) for x in plan["doses"]]
        by = {}
        for g0 in range(0, len(todo), a.group):
            grp = todo[g0:g0 + a.group]
            for (name, c), summ in zip(grp, run(grp, [S])):
                if c == 0:
                    json.dump({"name": name, "itemset": S, "traits": summ}, open(os.path.join(zd, f"{name}.json"), "w"))
                else:
                    by.setdefault(name, {})[str(c)] = summ
            for name in list(by):
                zf = os.path.join(zd, f"{name}.json")
                if all(str(x) in by[name] for x in plan["doses"]) and os.path.exists(zf):
                    doses = {"0.0": json.load(open(zf))["traits"], **by.pop(name)}
                    json.dump({"name": name, "sigma": sigma, "target": tr, "itemset": S, "doses": doses},
                              open(os.path.join(od, f"{name}.json"), "w"))
        print(d["id"], "target", tr, len(todo), "combos", round(time.time() - t0), "s", flush=True)
    print("SHARDDONE", flush=True)


if __name__ == "__main__":
    main()