File size: 14,685 Bytes
525b620
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.
"""Interventions (RESEARCH_PLAN 8): transplant a direction at doses into the base and into background adapters, and
knock it out of carriers. Directions: population loci (allele Delta* = L P^+), random low-rank directions matched in
expressed norm and module, and the same weight-space axis placed in another layer (renormalised there).

  python src/run/intervene.py --plan plan.json --out results/interventions/qwen05 [--shard i --nshards n]
plan.json: {"base", "adapters_dir", "geno_dir", "backgrounds": [names], "doses_base": [...], "doses_bg": [...],
            "directions": [{"id", "kind": "locus"|"random"|"other_layer", "module", "l", "target_module", "seed",
                            "knockout_carriers": [[name, g_minus_mean], ...]}]}
Every combo is a (background, dose) pair evaluated with the full battery (KO dose = -(g - mean) in genotype units, i.e. the
carrier moved to the population mean). A direction may carry its own "backgrounds" (subset; D-031).
--shared_zero (D-031): c = 0 is not re-measured inside every direction; reference units __ref__<hw>__NNN measure the base,
  every background and every knockout carrier once per hardware configuration hw = GPU model + batch sizes (D-035), so
  that c = 0 and the dosed combos it is compared with come from the same hardware (c = 0 has zero weight in the OLS dose
  slopes; calibrate.py reads the references for knockout differences and base curves). Without it, c = 0 is measured in
  every direction.
--gen_half h (plan 4.5): generation item sets restricted to their fixed half h (traits then equal that half's value).
Each record stores seconds per item set (battery.times summed over combos) for cost accounting.
Raw-coordinate plans (plan["coords"] == "raw", D-037): loci come from plan["loci_file"] (loci_raw.pt) and the allele is
  the raw weight-space direction sum_i u_il Delta_i / sqrt(lam_l) (V = identity), dosed in SDs of the raw genotype.
--claim: any number of processes or jobs share the unit list; a unit is claimed by atomically creating <id>.json.lock
  (removed when done or on SIGTERM; a lock older than --stale seconds is taken over). Use with --nshards 1.
"""
import argparse
import hashlib
import json
import os
import re
import signal
import socket
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 INPUT_OF  # 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.phenotype import FULL, PILOT, TINY, summarise_raw  # noqa: E402


def Vk(cov, key):
    layer, mod = key.split(".")
    e = cov[f"{layer}.{INPUT_OF[mod]}"]
    k = min(e["k99"], e["V"].shape[1])
    return e["V"][:, :k], e["lam"][:k]


def expressed_norm(D, cov, key):
    V, lam = Vk(cov, key)
    return float((D @ (V.to(D.device) * lam.sqrt().to(D.device)[None, :])).norm())


def restrict_gen_half(items, h):
    """Plan 4.5: keep only the fixed half h of every generation item set (in place)."""
    for spec in items.values():
        if spec["kind"] == "gen":
            keep = np.where(spec["half"] == h)[0]
            for k in ("prompts", "meta"):
                if k in spec:
                    spec[k] = [spec[k][i] for i in keep]
            spec["half"] = spec["half"][keep]
    return items


HELD = []  # lock files held by this process (released on exit, exception or SIGTERM)


def claim(lk, stale):
    """Atomically create lock file lk; take over a lock older than stale seconds. True if this process holds it."""
    try:
        if os.path.exists(lk) and time.time() - os.path.getmtime(lk) > stale:
            os.remove(lk)
    except FileNotFoundError:
        pass
    try:
        fd = os.open(lk, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
    except FileExistsError:
        return False
    os.write(fd, f"{socket.gethostname()} {os.getpid()} {time.time():.0f}".encode())
    os.close(fd)
    return True


def unlock(held):
    for lk in held:
        if os.path.exists(lk):
            os.remove(lk)
    held.clear()


def hw_tag(gpu, bs, gbs):
    """Hardware configuration tag (D-035): GPU model (alphanumerics) + scoring and generation batch sizes."""
    return re.sub(r"[^A-Za-z0-9]+", "_", gpu.replace("NVIDIA ", "")).strip("_") + f"_b{bs}g{gbs}"


def combo_hash(combos):
    """8-hex content hash of a reference unit's (background, dose) list (D-039)."""
    return hashlib.sha1(json.dumps([[b, float(c)] for b, c in combos]).encode()).hexdigest()[:8]


def make_units(plan, shared_zero, ref_size=48, hw=""):
    """Work units in execution order: c = 0 reference units for hardware tag hw (shared_zero), then tested loci (kind
    locus with a selection source), then controls (random, other-layer and high-variance non-associated loci), each in a
    fixed pseudo-random order (sha1 of the id; D-047), so that a finished subset (the interim calibration) is spread over
    modules rather than concentrated in the first modules in sort order."""
    units = []
    if shared_zero:
        carriers = sorted({n for d in plan["directions"] for n, _ in d.get("knockout_carriers", [])})
        used = {b for d in plan["directions"] for b in d.get("backgrounds", plan["backgrounds"])}
        zero = [("__base__", 0.0)] + [(b, 0.0) for b in plan["backgrounds"] if b in used] + [(f"KO::{n}", 0.0) for n in carriers]
        units = [{"id": f"__ref__{hw + '__' if hw else ''}{i // ref_size:03d}_{combo_hash(zero[i:i + ref_size])}", "kind": "ref",
                  "module": "", "combos": zero[i:i + ref_size]} for i in range(0, len(zero), ref_size)]
    tested = lambda d: d["kind"] == "locus" and bool(d.get("source"))  # noqa: E731
    return units + sorted(plan["directions"], key=lambda d: (not tested(d), hashlib.sha1(d["id"].encode()).hexdigest()))


def combos_of(d, plan, shared_zero):
    if d["kind"] == "ref":
        return d["combos"]
    keepc = (lambda c: c != 0) if shared_zero else (lambda c: True)
    combos = [("__base__", c) for c in plan["doses_base"] if keepc(c)] + [
        (b, c) for b in d.get("backgrounds", plan["backgrounds"]) for c in plan["doses_bg"] if keepc(c)]
    combos += [(f"KO::{n}", c) for n, gm in d.get("knockout_carriers", []) for c in (0.0, -float(gm)) if keepc(c)]
    return combos


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("--shared_zero", action="store_true")
    ap.add_argument("--gen_half", type=int, default=-1, choices=[-1, 0, 1])
    ap.add_argument("--dry_run", action="store_true", help="print units and battery-run counts per shard, then exit")
    ap.add_argument("--claim", action="store_true")
    ap.add_argument("--stale", type=float, default=14400)
    a = ap.parse_args()
    plan = json.load(open(a.plan))
    if a.dry_run:
        U = make_units(plan, a.shared_zero)
        for s in range(a.nshards):
            mine = U[s::a.nshards]
            print(json.dumps({"shard": s, "units": len(mine), "ref_units": sum(u["kind"] == "ref" for u in mine),
                              "battery_runs": sum(len(combos_of(u, plan, a.shared_zero)) for u in mine)}))
        print(json.dumps({"total_units": len(U), "total_runs": sum(len(combos_of(u, plan, a.shared_zero)) for u in U),
                          "example": {u["kind"]: combos_of(u, plan, a.shared_zero)[:12] for u in U}}))
        return
    os.makedirs(a.out, exist_ok=True)
    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, plan.get("loci_file", "loci.pt")))
    raw = plan.get("coords", "expressed") == "raw"
    names = json.load(open(os.path.join(G, "adapters.json")))["names"]
    bg_mods = {b: load_adapter(os.path.join(plan["adapters_dir"], b), n_layers=nL)["mods"] for b in plan["backgrounds"]}
    gpu = torch.cuda.get_device_name(0) if dev == "cuda" else "cpu"
    hw = hw_tag(gpu, bat.bs, bat.gbs)  # batch sizes after the GPU-memory cap (D-038)
    dirs = make_units(plan, a.shared_zero, hw=hw)[a.shard::a.nshards]
    fcache = {}
    print("GPU", gpu, "hw", hw, "units", len(dirs), flush=True)
    held = HELD

    def release(*_):
        for lk in held:
            if os.path.exists(lk):
                os.remove(lk)
        sys.exit(143)
    signal.signal(signal.SIGTERM, release)

    def peak_gb():
        return round(torch.cuda.max_memory_allocated() / 2 ** 30, 2) if dev == "cuda" else None
    for d in dirs:
        fn = os.path.join(a.out, d["id"] + ".json")
        if os.path.exists(fn):
            continue
        if a.claim and not claim(fn + ".lock", a.stale):
            continue
        if a.claim:
            held[:] = [fn + ".lock"]
            if os.path.exists(fn):  # finished by another worker meanwhile
                unlock(held)
                continue
        t0 = time.time()
        secs = {}
        if d["kind"] == "ref":
            res = []
            for g0 in range(0, len(d["combos"]), a.group):
                grp = d["combos"][g0:g0 + a.group]
                ups = []
                for bgname, _ in grp:
                    nm = bgname[4:] if bgname.startswith("KO::") else bgname
                    ups.append({} if nm == "__base__" else adapter_updates(
                        bg_mods[nm] if nm in bg_mods else load_adapter(os.path.join(plan["adapters_dir"], nm), n_layers=nL)["mods"]))
                set_bank(table, ups, device=dev)
                bat.nb = len(ups)
                raws = bat.run_multi()
                clear(table)
                bat.nb = 1
                for k, v in bat.times.items():
                    secs[k] = secs.get(k, 0.0) + v
                for (bgname, c), raw in zip(grp, raws):
                    summ, _, _ = summarise_raw(items, raw)
                    res.append({"background": bgname, "dose": c, "traits": summ})
            rec = {"id": d["id"], "kind": "ref", "combos": res, "seconds": time.time() - t0, "section_seconds": secs,
                   "gpu": gpu, "hw": hw, "bs": [bat.bs, bat.gbs], "sizes": a.sizes, "gen_half": a.gen_half, "peak_mem_gb": peak_gb()}
            json.dump(rec, open(fn + ".tmp", "w"))
            os.replace(fn + ".tmp", fn)
            unlock(held)
            print(d["id"], len(res), round(rec["seconds"]), "s", flush=True)
            continue
        key = d["module"]
        lo = loci[key]
        sigma = float(lo["g"][:, d.get("l", 0)].std()) if lo["n_loci"] else 1.0
        if d["kind"] in ("locus", "other_layer"):
            if key not in fcache:
                fcache.clear()
                fcache[key] = [load_module_factors(os.path.join(plan["adapters_dir"], n), {key}).get(key) for n in names]
            if raw:
                V = torch.eye(table[key].lin.weight.shape[1])
            else:
                V, _ = Vk(cov, key)
            D = allele(fcache[key], lo["U"][:, d["l"]], lo["lam"][d["l"]], V, device=dev)
            tkey = key
            if d["kind"] == "other_layer":
                tkey = d["target_module"]
                D = D / expressed_norm(D, cov, tkey)
        else:  # random low-rank direction, unit expressed norm, same module
            gen = torch.Generator().manual_seed(int(d.get("seed", 0)))
            p, q = table[key].lin.weight.shape
            D = (torch.randn(p, 16, generator=gen) @ torch.randn(16, q, generator=gen)).to(dev)
            D = D / expressed_norm(D, cov, key)
            tkey = key
        A_s, B_s, resid = lowrank(D.float())
        A_s, B_s = A_s.cpu(), B_s.cpu()
        combos = combos_of(d, plan, a.shared_zero)
        res = []
        for g0 in range(0, len(combos), a.group):
            grp = combos[g0:g0 + a.group]
            ups = []
            for bgname, c in grp:
                if bgname.startswith("KO::"):
                    bm = load_adapter(os.path.join(plan["adapters_dir"], bgname[4:]), n_layers=nL)["mods"]
                    ups.append(merge_updates(adapter_updates(bm), {tkey: [(A_s, B_s, c)]}))
                else:
                    base_up = {} if bgname == "__base__" else adapter_updates(bg_mods[bgname])
                    ups.append(merge_updates(base_up, {tkey: [(A_s, B_s, c * sigma)]}))
            set_bank(table, ups, device=dev)
            bat.nb = len(ups)
            raws = bat.run_multi()
            clear(table)
            bat.nb = 1
            for k, v in bat.times.items():
                secs[k] = secs.get(k, 0.0) + v
            for (bgname, c), raw in zip(grp, raws):
                summ, _, _ = summarise_raw(items, raw)
                res.append({"background": bgname, "dose": c, "traits": summ})
        rec = {**{k: v for k, v in d.items() if k != "knockout_carriers"}, "sigma": sigma, "allele_rank": int(A_s.shape[0]),
               "lowrank_residual": resid, "applied_module": tkey, "combos": res, "seconds": time.time() - t0, "gpu": gpu,
               "hw": hw, "bs": [bat.bs, bat.gbs], "peak_mem_gb": peak_gb(), "sizes": a.sizes, "section_seconds": secs, "gen_half": a.gen_half, "shared_zero": a.shared_zero}
        json.dump(rec, open(fn + ".tmp", "w"))
        os.replace(fn + ".tmp", fn)
        unlock(held)
        print(d["id"], len(res), round(rec["seconds"]), "s", flush=True)
    print("SHARDDONE", flush=True)


if __name__ == "__main__":
    try:
        main()
    finally:
        unlock(HELD)