File size: 6,024 Bytes
f87a628
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Lipid-level external pretraining on LNP Atlas properties.

The formulation-level pretraining run (scripts/pretrain_atlas.py) transfers
weights into a 10-node set model, but Atlas has no head/linker/tail
decomposition and no assay context, so the transferred encoder sees a
different input structure.  This script removes that mismatch: it aggregates
the Atlas measurements to the *ionisable lipid* (mean over the formulations
that contain it) and pretrains only the molecular streams -- the GINE graph
encoder and the RDKit descriptor MLP -- with four absolute property targets.

Weights are saved with the ``enc.`` prefix so that PhysSetLNP can load them
directly.

    python scripts/pretrain_lipid.py --epochs 200
"""
from __future__ import annotations

import argparse
from pathlib import Path

import numpy as np
import torch
import torch.nn as nn

from lnpbench.models.backbone import ATOM_DIM, BOND_DIM
from lnpbench.models.blocks import GINEEncoder
from lnpbench.store import FeatureStore
from lnpbench.trainer import build_batch, compute_norm_stats, set_seed

ROOT = Path(__file__).resolve().parents[1]
ATLAS_CACHE = ROOT / "cache" / "atlas"


class LipidEncoder(nn.Module):
    """Mirror of the two molecular streams inside FormulationEncoder."""

    def __init__(self, desc_dim: int, d_model: int = 192, dual: bool = True, dropout: float = 0.1):
        super().__init__()
        self.gnn = GINEEncoder(ATOM_DIM, BOND_DIM, d_model, 3, dropout)
        self.gnn_prot = GINEEncoder(ATOM_DIM, BOND_DIM, d_model, 3, dropout) if dual else None
        self.desc_enc = nn.Sequential(
            nn.Linear(desc_dim, 192), nn.SiLU(), nn.Dropout(dropout),
            nn.Linear(192, 128), nn.SiLU(),
        )
        feat = d_model + 128  # dual-state graphs are averaged before the head
        self.head = nn.Sequential(nn.Linear(feat, 256), nn.SiLU(), nn.Dropout(dropout), nn.Linear(256, 4))

    def forward(self, batch):
        g = self.gnn(batch["graph"])
        if self.gnn_prot is not None:
            g = 0.5 * (g + self.gnn_prot(batch["graph"]))
        d = self.desc_enc(batch["desc"])
        return self.head(torch.cat([g, d], dim=-1))


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--epochs", type=int, default=200)
    ap.add_argument("--lr", type=float, default=3e-4)
    ap.add_argument("--wd", type=float, default=1e-4)
    ap.add_argument("--seed", type=int, default=0)
    ap.add_argument("--out", default=str(ROOT / "cache" / "atlas_pretrain_lipid.pt"))
    ap.add_argument("--shuffle-labels", action="store_true",
                    help="control: permute the property targets so the model learns no signal")
    args = ap.parse_args()

    set_seed(args.seed)
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    atlas = FeatureStore(cache_dir=ATLAS_CACHE)
    lnpdb = FeatureStore()
    norm = compute_norm_stats(lnpdb, np.arange(len(lnpdb)))

    # one representative row per ionisable lipid + mean target over its rows
    il = atlas.il_id
    uniq = np.unique(il)
    first = np.array([np.where(il == u)[0][0] for u in uniq])
    aux = np.zeros((len(uniq), atlas.aux.shape[1]), dtype=np.float32)
    mask = np.zeros_like(aux)
    for j, u in enumerate(uniq):
        rows = np.where(il == u)[0]
        w = atlas.aux_mask[rows]
        vals = atlas.aux[rows]
        m = w > 0
        for c in range(aux.shape[1]):
            mc = m[:, c]
            if mc.any():
                aux[j, c] = vals[mc, c].mean()
                mask[j, c] = 1.0
    if args.shuffle_labels:
        rng0 = np.random.default_rng(123)
        for c in range(aux.shape[1]):
            m = mask[:, c] > 0
            vals = aux[m, c].copy()
            rng0.shuffle(vals)
            aux[m, c] = vals
        print("[control] property targets permuted across lipids")
    print(f"[lipid] {len(uniq)} unique ionisable lipids, coverage "
          f"{mask.sum(0).astype(int)} / {len(uniq)}")

    model = LipidEncoder(atlas.il_desc.shape[1]).to(device)
    opt = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=args.wd)
    need = ["graph", "desc", "cpp"]
    aux_t = torch.from_numpy(aux).to(device)
    mask_t = torch.from_numpy(mask).to(device)

    rng = np.random.default_rng(args.seed)
    n = len(uniq)
    best, best_state = 1e9, None
    for epoch in range(args.epochs):
        model.train()
        order = rng.permutation(n)
        tot = 0.0
        for s in range(0, n, 128):
            sel = order[s:s + 128]
            batch = build_batch(atlas, first[sel], need, device, norm)
            m = mask_t[sel] > 0
            out = model(batch)
            loss = torch.nn.functional.smooth_l1_loss(out[m], aux_t[sel][m])
            opt.zero_grad()
            loss.backward()
            torch.nn.utils.clip_grad_norm_(model.parameters(), 5.0)
            opt.step()
            tot += float(loss.detach()) * len(sel)
        model.eval()
        with torch.no_grad():
            full = build_batch(atlas, first, need, device, norm)
            out = model(full)
            m = mask_t > 0
            val = float(torch.nn.functional.smooth_l1_loss(out[m], aux_t[m]))
            per = {}
            for j, name in enumerate(atlas.aux_names):
                mj = mask_t[:, j] > 0
                per[name] = round(float(torch.nn.functional.l1_loss(out[mj, j], aux_t[mj, j])), 3)
        if epoch % 20 == 0 or epoch == args.epochs - 1:
            print(f"[epoch {epoch:3d}] train {tot / n:.4f} full {val:.4f} {per}", flush=True)
        if val < best:
            best, best_state = val, {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}

    # prefix so that the keys map onto PhysSetModule.enc.*
    out_state = {}
    for k, v in (best_state or model.state_dict()).items():
        out_state[f"enc.{k}"] = v
    Path(args.out).parent.mkdir(parents=True, exist_ok=True)
    torch.save(out_state, args.out)
    print(f"[done] best {best:.4f} -> {args.out}")


if __name__ == "__main__":
    main()