"""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) 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)}