File size: 4,846 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
"""Pretrain the formulation encoder on LNP Atlas absolute properties.

Stage 1 of the external-supervision experiment: train the shared encoder to
predict four independently measured physical quantities (particle size, PDI,
zeta potential, encapsulation efficiency) on a corpus that shares almost no
chemistry with LNPDB.  Stage 2 (scripts/run_benchmark.py with the
``physset_ext`` registry entry) fine-tunes on LNPDB activity.

    python scripts/pretrain_atlas.py --epochs 60 --out cache/atlas_pretrain.pt
"""
from __future__ import annotations

import argparse
import time
from pathlib import Path

import numpy as np
import torch

from lnpbench.models.backbone import PhysSetModule
from lnpbench.store import FeatureStore
from lnpbench.trainer import TrainConfig, build_batch, compute_norm_stats, set_seed

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


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--epochs", type=int, default=60)
    ap.add_argument("--batch-size", type=int, default=64)
    ap.add_argument("--lr", type=float, default=3e-4)
    ap.add_argument("--wd", type=float, default=1e-5)
    ap.add_argument("--seed", type=int, default=0)
    ap.add_argument("--out", default=str(ROOT / "cache" / "atlas_pretrain.pt"))
    ap.add_argument("--aux-dim", type=int, default=4)
    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()
    print(f"[atlas] {len(atlas)} rows, aux dim {atlas.aux.shape[1]} "
          f"{atlas.aux_names}, coverage {atlas.aux_mask.sum(0).astype(int)}")
    # use the LNPDB descriptor / cCPP statistics so the pretrained weights see
    # exactly the input scaling they will see during fine-tuning
    norm = compute_norm_stats(lnpdb, np.arange(len(lnpdb)))

    cfg = TrainConfig(epochs=args.epochs, batch_size=args.batch_size, lr=args.lr,
                      weight_decay=args.wd, seed=args.seed)
    model = PhysSetModule(
        fp_dim=atlas.il_fp.shape[1], ctx_dim=atlas.ctx_dim,
        desc_dim=atlas.il_desc.shape[1], d_model=192, n_heads=6, n_layers=3,
        node_mode="phys", cond_mode="concat", use_physics=True, use_helpers=True,
        lam_rank=0.5, lam_phys=0.2, use_md_aux=False, aux_dim=args.aux_dim,
    ).to(device)
    opt = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=args.wd)
    n = len(atlas)
    steps = max(1, int(np.ceil(n / args.batch_size)))
    total = args.epochs * steps
    warm = 3 * steps

    def lr_at(step: int) -> float:
        if step < warm:
            return (step + 1) / warm
        p = (step - warm) / max(1, total - warm)
        return 0.5 * (1.0 + np.cos(np.pi * min(1.0, p)))

    sched = torch.optim.lr_scheduler.LambdaLR(opt, lr_at)
    need = ["ctx", "ratios", "nodes", "nodes_prot", "helpers", "graph", "desc", "cpp", "aux"]
    rng = np.random.default_rng(args.seed)
    best = 1e9
    best_state = None
    t0 = time.time()

    for epoch in range(args.epochs):
        model.train()
        order = rng.permutation(n)
        losses = []
        for s in range(steps):
            sel = order[s * args.batch_size:(s + 1) * args.batch_size]
            if len(sel) == 0:
                continue
            batch = build_batch(atlas, sel, need, device, norm)
            m = batch["aux_mask"] > 0
            if not bool(m.any()):
                continue
            out = model(batch)
            loss = torch.nn.functional.smooth_l1_loss(out["aux"][m], batch["aux"][m])
            opt.zero_grad()
            loss.backward()
            torch.nn.utils.clip_grad_norm_(model.parameters(), 5.0)
            opt.step()
            sched.step()
            losses.append(float(loss.detach()))
        model.eval()
        with torch.no_grad():
            batch = build_batch(atlas, np.arange(n), need, device, norm)
            m = batch["aux_mask"] > 0
            out = model(batch)
            val = float(torch.nn.functional.smooth_l1_loss(out["aux"][m], batch["aux"][m]))
            per = {}
            for j, name in enumerate(atlas.aux_names):
                mj = batch["aux_mask"][:, j] > 0
                per[name] = float(torch.nn.functional.l1_loss(out["aux"][mj, j], batch["aux"][mj, j]))
        print(f"[epoch {epoch:3d}] train {np.mean(losses):.4f} full {val:.4f} "
              f"{per} ({time.time() - t0:.0f}s)", flush=True)
        if val < best:
            best = val
            best_state = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}

    Path(args.out).parent.mkdir(parents=True, exist_ok=True)
    torch.save(best_state or model.state_dict(), args.out)
    print(f"[done] best full-set loss {best:.4f} -> {args.out}")


if __name__ == "__main__":
    main()