File size: 5,000 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
# MIT License, Bryan Cheng, 2026.
"""Repair of carriers of validated safety directions (RESEARCH_PLAN 13; E8).

For each carrier: the adapter as published; knockout of the validated direction (carrier moved to the population mean,
coefficient -(g - mean) on the unit-expressed-norm allele); a random direction in the same module with the same
expressed norm and the same coefficient; uniform shrinkage of the whole adapter at each factor in "shrink".
Aggregates only are reported downstream (src/analysis/audit.py).

  python src/run/repair.py --plan results/audit/repair_plan_qwen05.json --out results/audit/repair_qwen05
plan: {"base", "adapters_dir", "geno_dir", "shrink": [...], "carriers": [{"name", "module", "l", "gm", "direction_id"}]}
"""
import argparse
import json
import os
import sys
import time

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.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, expressed_norm  # noqa: E402
from src.run.phenotype import FULL, PILOT, TINY, summarise_raw  # noqa: E402


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)
    a = ap.parse_args()
    plan = json.load(open(a.plan))
    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)
    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"))
    names = json.load(open(os.path.join(G, "adapters.json")))["names"]
    car = sorted(plan["carriers"], key=lambda c: c["module"])[a.shard::a.nshards]
    fcache, acache = {}, {}
    for c in car:
        fn = os.path.join(a.out, f"{c['name']}__{c['direction_id']}.json")
        if os.path.exists(fn):
            continue
        t0 = time.time()
        key, l = c["module"], c["l"]
        if (key, l) not in acache:
            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]
            V, _ = Vk(cov, key)
            D = allele(fcache[key], loci[key]["U"][:, l], loci[key]["lam"][l], V, device=dev)
            gen = torch.Generator().manual_seed(7000 + l)
            p, q = table[key].lin.weight.shape
            R = (torch.randn(p, 16, generator=gen) @ torch.randn(16, q, generator=gen)).to(dev)
            R = R * (expressed_norm(D, cov, key) / expressed_norm(R, cov, key))
            acache[(key, l)] = [tuple(x.cpu() if torch.is_tensor(x) else x for x in lowrank(M.float())[:2]) for M in (D, R)]
        (Ad, Bd), (Ar, Br) = acache[(key, l)]
        bm = load_adapter(os.path.join(plan["adapters_dir"], c["name"]), n_layers=nL)["mods"]
        base_up = adapter_updates(bm)
        combos = [("orig", base_up), ("ko", merge_updates(base_up, {key: [(Ad, Bd, -float(c["gm"]))]})),
                  ("random_ko", merge_updates(base_up, {key: [(Ar, Br, -float(c["gm"]))]}))]
        combos += [(f"shrink_{s}", adapter_updates(bm, coef=float(s))) for s in plan["shrink"]]
        res = []
        for g0 in range(0, len(combos), a.group):
            grp = combos[g0:g0 + a.group]
            set_bank(table, [u for _, u in grp], device=dev)
            bat.nb = len(grp)
            raws = bat.run_multi()
            clear(table)
            bat.nb = 1
            for (lab, _), raw in zip(grp, raws):
                res.append({"arm": lab, "traits": summarise_raw(items, raw)[0]})
        json.dump({**c, "arms": res, "seconds": time.time() - t0}, open(fn + ".tmp", "w"))
        os.replace(fn + ".tmp", fn)
        print(c["name"][:40], c["direction_id"], round(time.time() - t0), flush=True)
    print("SHARDDONE", flush=True)


if __name__ == "__main__":
    main()