File size: 12,624 Bytes
d1988f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4e317f
 
 
 
 
 
 
 
 
 
 
 
d1988f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4e317f
 
 
 
 
 
 
d1988f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4e317f
 
d1988f5
 
 
 
 
f87a628
 
 
dedf737
 
 
 
 
 
 
d1988f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4e317f
 
 
 
 
 
 
 
d1988f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4e317f
 
 
 
 
 
 
 
 
d1988f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
295
296
297
298
299
"""Unified training / evaluation loop for every neural model in the benchmark."""

from __future__ import annotations

import math
import time
from dataclasses import dataclass, field
from typing import Dict, Sequence

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

from . import metrics
from .store import FeatureStore


@dataclass
class TrainConfig:
    epochs: int = 80
    batch_size: int = 128
    lr: float = 3e-4
    weight_decay: float = 1e-5
    patience: int = 15
    warmup_epochs: int = 3
    grad_clip: float = 5.0
    seed: int = 0
    device: str = "cuda"
    eval_batch: int = 1024
    verbose: bool = False
    # "pooled": Spearman over the whole validation split (the standard choice)
    # "per_study": mean of the per-source-study Spearman values.  A random
    # validation split is drawn from the *same* studies as the training set, so
    # pooled validation rewards models that memorise study-specific signal; the
    # study-balanced score is a much better proxy for transfer to a new study.
    val_mode: str = "pooled"
    # Draw each mini-batch so that every *source study* contributes with equal
    # probability, instead of sampling proportionally to study size.  The
    # database is dominated by a few large studies, so uniform sampling makes
    # the model fit those and ignore the small ones -- exactly the source
    # studies whose held-out counterparts are hardest.
    study_balance: bool = False
    extra: dict = field(default_factory=dict)


def set_seed(seed: int) -> None:
    import random

    random.seed(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    if torch.cuda.is_available():
        torch.cuda.manual_seed_all(seed)


# ---------------------------------------------------------------------------
# Batch construction
# ---------------------------------------------------------------------------


def build_batch(
    store: FeatureStore,
    idx: np.ndarray,
    need: Sequence[str],
    device: torch.device,
    norm: Dict[str, np.ndarray] | None = None,
) -> Dict[str, torch.Tensor]:
    idx = np.asarray(idx)
    out: Dict[str, torch.Tensor] = {}
    il_ids = store.il_id[idx]

    if "y" in need:
        out["y"] = torch.from_numpy(store.y[idx]).to(device)
    if "ctx" in need:
        out["ctx"] = torch.from_numpy(store.ctx[idx]).to(device)
    if "ratios" in need:
        out["ratios"] = torch.from_numpy(store.ratios[idx]).to(device)
    if "study_id" in need:
        out["study_id"] = torch.from_numpy(store.study_id[idx]).to(device)
    if "md_flag" in need:
        out["md_flag"] = torch.from_numpy(store.md_flag[idx]).to(device)
        out["md_stable"] = torch.from_numpy(store._md_stable_lookup(idx)).to(device)
    if "fp" in need:
        out["fp"] = torch.from_numpy(store.il_fp[il_ids].astype(np.float32)).to(device)
    if "fp_prot" in need:
        out["fp_prot"] = torch.from_numpy(store.protonated_fp()[il_ids].astype(np.float32)).to(device)
    if "desc" in need:
        d = store.il_desc[il_ids]
        if norm is not None:
            d = np.clip(d, norm["desc_lo"], norm["desc_hi"])
            d = (d - norm["desc_mu"]) / norm["desc_sd"]
        out["desc"] = torch.from_numpy(d).to(device)
    if "cpp" in need:
        c = store.il_cpp[il_ids]
        if norm is not None:
            c = (c - norm["cpp_mu"]) / norm["cpp_sd"]
        out["cpp"] = torch.from_numpy(c.astype(np.float32)).to(device)
    if "graph" in need:
        out["graph"] = store.collate_graphs(il_ids, device)
    if "tokens" in need:
        # Truncate to the longest sequence actually present in this mini-batch.
        # SMILES are padded to 256 tokens, but the median lipid uses 67 and a
        # batch-wide slice to the observed maximum cuts the state-space memory
        # and compute by 2-4x with no change to the model.
        lens = store.il_token_len[il_ids]
        L = int(max(16, lens.max())) if len(lens) else 16
        L = min(L, store.il_tokens.shape[1])
        out["tokens"] = torch.from_numpy(store.il_tokens[il_ids, :L]).to(device)
        out["token_mask"] = torch.from_numpy(
            (np.arange(L)[None, :] < lens[:, None]).astype(np.float32)
        ).to(device)

    if "nodes" in need:
        slot_names = ["head", "linker", "tail1", "tail2", "tail3", "tail4"]
        fps, fps_prot, phys, masks = [], [], [], []
        for si, slot in enumerate(slot_names):
            ids = store.frag_ids[idx, si]
            fp = store.frag_fp32(slot)
            ph = store.frag_phys[slot]
            if len(fp) == 0:  # slot never populated in LNPDB (e.g. tail3/tail4)
                fp = np.zeros((1, store.il_fp.shape[1]), dtype=np.float32)
                ph = np.zeros((1, ph.shape[1]), dtype=np.float32)
                ids = np.full_like(ids, -1)
            safe = np.clip(ids, 0, len(fp) - 1)
            # Invalid nodes point at row 0; they are removed by the attention
            # mask downstream.  Multiplying by a validity indicator here used to
            # allocate five extra (B, 2048) arrays per mini-batch and dominated
            # the wall clock of the set-based models.
            fps.append(fp.take(safe, axis=0))
            fps_prot.append(fp.take(safe, axis=0))
            phys.append(ph.take(safe, axis=0))
            masks.append(ids >= 0)
        fps.append(store.il_fp[il_ids].astype(np.float32))
        fps_prot.append(store.protonated_fp()[il_ids].astype(np.float32))
        phys.append(store.il_phys[il_ids])
        masks.append(np.ones(len(idx), dtype=bool))
        out["node_fp"] = torch.from_numpy(np.stack(fps, axis=1)).to(device)
        if "nodes_prot" in need:
            out["node_fp_prot"] = torch.from_numpy(np.stack(fps_prot, axis=1)).to(device)
        out["node_phys"] = torch.from_numpy(np.stack(phys, axis=1)).to(device)
        out["node_mask"] = torch.from_numpy(~np.stack(masks, axis=1)).to(device)

    if "helpers" in need:
        hf, hp, hm = [], [], []
        for si, slot in enumerate(["HL", "CHL", "PEG"]):
            ids = store.helper_ids[idx, si]
            fp = store.frag_fp32(slot)
            ph = store.frag_phys[slot]
            if len(fp) == 0:  # slot never populated in LNPDB (e.g. tail3/tail4)
                fp = np.zeros((1, store.il_fp.shape[1]), dtype=np.float32)
                ph = np.zeros((1, ph.shape[1]), dtype=np.float32)
                ids = np.full_like(ids, -1)
            safe = np.clip(ids, 0, len(fp) - 1)
            hf.append(fp.take(safe, axis=0))
            hp.append(ph.take(safe, axis=0))
            hm.append(ids >= 0)
        out["helper_fp"] = torch.from_numpy(np.stack(hf, axis=1)).to(device)
        out["helper_phys"] = torch.from_numpy(np.stack(hp, axis=1)).to(device)
        out["helper_mask"] = torch.from_numpy(~np.stack(hm, axis=1)).to(device)

    if "aux" in need:
        out["aux"] = torch.from_numpy(store.aux[idx]).to(device)
        out["aux_mask"] = torch.from_numpy(store.aux_mask[idx]).to(device)
    if "onto" in need:
        from .ontology import node_onto

        out["node_onto"] = torch.from_numpy(node_onto(store, idx)).to(device)
    if "glob" in need:
        out["glob"] = torch.from_numpy(store.global_codebook()[idx]).to(device)

    out["row"] = torch.from_numpy(idx).to(device)
    return out


def compute_norm_stats(store: FeatureStore, train_idx: np.ndarray) -> Dict[str, np.ndarray]:
    il = np.unique(store.il_id[train_idx])
    desc = store.il_desc[il]
    cpp = store.il_cpp[il]
    lo = np.percentile(desc, 0.5, axis=0)
    hi = np.percentile(desc, 99.5, axis=0)
    desc = np.clip(desc, lo, hi)
    return {
        "desc_mu": desc.mean(0),
        "desc_sd": desc.std(0) + 1e-6,
        "desc_lo": lo,
        "desc_hi": hi,
        "cpp_mu": cpp.mean(0),
        "cpp_sd": cpp.std(0) + 1e-6,
    }


# ---------------------------------------------------------------------------
# Trainer
# ---------------------------------------------------------------------------


class NeuralModel:
    name = "neural"

    def __init__(self, **kwargs):
        self.kwargs = kwargs
        self.history = []

    def build(self, store: FeatureStore, cfg: TrainConfig) -> nn.Module:  # pragma: no cover
        raise NotImplementedError

    def need(self) -> Sequence[str]:  # pragma: no cover
        raise NotImplementedError

    @torch.no_grad()
    def predict(self, store: FeatureStore, idx: np.ndarray) -> np.ndarray:
        self.module.eval()
        preds = []
        for start in range(0, len(idx), self.cfg.eval_batch):
            chunk = idx[start : start + self.cfg.eval_batch]
            batch = build_batch(store, chunk, self.need(), self.device, self.norm)
            out = self.module(batch)
            preds.append(out["y_hat"].detach().cpu().numpy())
        return np.concatenate(preds) if preds else np.zeros(0)

    def fit(self, store: FeatureStore, train_idx: np.ndarray, val_idx: np.ndarray, cfg: TrainConfig) -> Dict:
        self.cfg = cfg
        set_seed(cfg.seed)
        self.device = torch.device(cfg.device if (cfg.device == "cpu" or torch.cuda.is_available()) else "cpu")
        self.norm = compute_norm_stats(store, train_idx)
        self.module = self.build(store, cfg).to(self.device)
        optim = torch.optim.AdamW(self.module.parameters(), lr=cfg.lr, weight_decay=cfg.weight_decay)
        steps_per_epoch = max(1, math.ceil(len(train_idx) / cfg.batch_size))
        total_steps = cfg.epochs * steps_per_epoch
        warmup = max(1, cfg.warmup_epochs * steps_per_epoch)

        def lr_lambda(step):
            if step < warmup:
                return (step + 1) / warmup
            progress = (step - warmup) / max(1, total_steps - warmup)
            return 0.5 * (1.0 + math.cos(math.pi * min(1.0, progress)))

        sched = torch.optim.lr_scheduler.LambdaLR(optim, lr_lambda)

        best = -1e9
        best_state = None
        bad = 0
        rng = np.random.default_rng(cfg.seed)

        for epoch in range(cfg.epochs):
            self.module.train()
            if cfg.study_balance:
                st = store.study_id[train_idx]
                cnt = np.bincount(st, minlength=store.n_studies).astype(np.float64)
                w = 1.0 / np.maximum(cnt[st], 1.0)
                w = w / w.sum()
                order = rng.choice(len(train_idx), size=len(train_idx), replace=True, p=w)
            else:
                order = rng.permutation(len(train_idx))
            t0 = time.time()
            losses = []
            for start in range(0, len(order), cfg.batch_size):
                sel = order[start : start + cfg.batch_size]
                if len(sel) < 4:
                    continue
                batch = build_batch(store, train_idx[sel], self.need(), self.device, self.norm)
                optim.zero_grad(set_to_none=True)
                out = self.module(batch)
                loss, logs = self.module.compute_loss(batch, out, epoch=epoch, n_epochs=cfg.epochs)
                if not torch.isfinite(loss):
                    continue
                loss.backward()
                if cfg.grad_clip > 0:
                    torch.nn.utils.clip_grad_norm_(self.module.parameters(), cfg.grad_clip)
                optim.step()
                sched.step()
                losses.append(float(loss.detach()))
            val_pred = self.predict(store, val_idx)
            if cfg.val_mode == "per_study":
                st = store.study_id[val_idx]
                per = [metrics.spearman(store.y[val_idx][st == u], val_pred[st == u])
                       for u in np.unique(st)
                       if (st == u).sum() >= 5]
                per = [v for v in per if np.isfinite(v)]
                val_score = float(np.mean(per)) if per else float("nan")
            else:
                val_score = metrics.spearman(store.y[val_idx], val_pred)
            self.history.append(
                {"epoch": epoch, "loss": float(np.mean(losses)) if losses else float("nan"), "val_spearman": val_score}
            )
            if cfg.verbose:
                print(f"    epoch {epoch:3d} loss={np.mean(losses):.4f} val_rho={val_score:.4f} ({time.time()-t0:.1f}s)")
            if np.isfinite(val_score) and val_score > best + 1e-5:
                best = val_score
                best_state = {k: v.detach().clone() for k, v in self.module.state_dict().items()}
                bad = 0
            else:
                bad += 1
                if bad >= cfg.patience:
                    break

        if best_state is not None:
            self.module.load_state_dict(best_state)
        return {"best_val_spearman": best, "epochs_run": len(self.history)}