File size: 3,948 Bytes
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 | """Method B - PhysSet-LNP.
Dual protonation-state substructure encoding + multi-physics interaction bias +
permutation-invariant pooling + a physics-alignment auxiliary head trained on
(i) the 54 MD-derived bilayer stability labels shipped with LNPDB and (ii) the
conformer packing descriptors, which the model must predict from the intrinsic
formulation representation alone.
"""
from __future__ import annotations
from typing import Sequence
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..store import FeatureStore
from ..trainer import NeuralModel, TrainConfig
from .set_base import HierarchicalSetEncoder, PHYS_DIM
class PhysSetModule(nn.Module):
def __init__(
self,
fp_dim: int,
ctx_dim: int,
d_model: int = 192,
n_heads: int = 6,
n_layers: int = 3,
dropout: float = 0.1,
lam_rank: float = 0.4,
lam_phys: float = 0.25,
lam_stab: float = 0.1,
rank_gamma: float = 2.0,
dual_state: bool = True,
use_md_aux: bool = True,
):
super().__init__()
self.encoder = HierarchicalSetEncoder(
fp_dim=fp_dim, ctx_dim=ctx_dim, d_model=d_model, n_heads=n_heads,
n_layers=n_layers, dropout=dropout, phys_dim=PHYS_DIM, dual_state=dual_state,
)
self.dual_state = dual_state
self.pred = nn.Sequential(nn.Linear(d_model, 128), nn.SiLU(), nn.Dropout(dropout), nn.Linear(128, 1))
self.phys_head = nn.Sequential(nn.Linear(d_model, 64), nn.SiLU(), nn.Linear(64, 2))
self.stab_head = nn.Sequential(nn.Linear(d_model, 64), nn.SiLU(), nn.Linear(64, 1))
self.lam_rank, self.lam_phys, self.lam_stab = lam_rank, lam_phys, lam_stab
self.rank_gamma = rank_gamma
self.use_md_aux = use_md_aux
def forward(self, batch, **kwargs):
if self.dual_state:
batch = {
**batch,
"node_fp": torch.cat([batch["node_fp"], batch["node_fp_prot"]], dim=-1),
"helper_fp": torch.cat([batch["helper_fp"], batch["helper_fp"]], dim=-1),
}
z, z_lnp, z_cond, nodes = self.encoder(batch)
y_hat = self.pred(z).squeeze(-1)
phys = self.phys_head(z_lnp)
stab = self.stab_head(z_lnp).squeeze(-1)
return {"y_hat": y_hat, "phys": phys, "stab": stab, "z": z, "z_lnp": z_lnp}
def compute_loss(self, batch, out, epoch=0, n_epochs=1):
reg = F.smooth_l1_loss(out["y_hat"], batch["y"])
study = batch["study_id"]
same = study[:, None] == study[None, :]
diff = batch["y"][:, None] - batch["y"][None, :]
valid = same & (diff > 1e-4)
if valid.any():
pd_ = out["y_hat"][:, None] - out["y_hat"][None, :]
rank = F.softplus(-self.rank_gamma * pd_[valid]).mean()
else:
rank = torch.zeros((), device=reg.device)
phys_loss = torch.zeros((), device=reg.device)
if self.use_md_aux:
target = batch["cpp"][:, [2, 3]]
phys_loss = F.l1_loss(out["phys"], target)
mask = batch["md_flag"] > 0
if mask.any():
bce = F.binary_cross_entropy_with_logits(
out["stab"][mask], batch["md_stable"][mask], reduction="mean"
)
phys_loss = phys_loss + self.lam_stab * bce
total = reg + self.lam_rank * rank + self.lam_phys * phys_loss
return total, {
"reg": float(reg.detach()), "rank": float(rank.detach()), "phys": float(phys_loss.detach()),
}
class PhysSetLNP(NeuralModel):
name = "physset"
def build(self, store: FeatureStore, cfg: TrainConfig) -> nn.Module:
return PhysSetModule(fp_dim=store.il_fp.shape[1], ctx_dim=store.ctx_dim, **self.kwargs)
def need(self) -> Sequence[str]:
return ("y", "ctx", "ratios", "nodes", "nodes_prot", "helpers", "study_id", "cpp", "md_flag") |