Download code/src/lnpbench/models/backbone.py from eduzrh/LNPBench: direct link, hf CLI and curl.
- Browser
- Download file 17.7 kB
-
https://huggingface.co/datasets/eduzrh/LNPBench/resolve/4168d53fc6eb5ca3fc229a71f6501bdffe77af08/code/src/lnpbench/models/backbone.py
- Command line
-
hf download hf://datasets/eduzrh/LNPBench@4168d53fc6eb5ca3fc229a71f6501bdffe77af08/code/src/lnpbench/models/backbone.py
-
curl -L -o backbone.py https://huggingface.co/datasets/eduzrh/LNPBench/resolve/4168d53fc6eb5ca3fc229a71f6501bdffe77af08/code/src/lnpbench/models/backbone.py
17.7 kB
| """Shared chemistry backbone for the three proposed methods (v2). | |
| The first iteration of methods A and B encoded every formulation component with | |
| a *Morgan fingerprint of an isolated fragment*. That is strictly weaker than | |
| the message passing that LiON and AGILE apply to the intact ionizable lipid, and | |
| the external-generalisation numbers showed it: both methods landed well below | |
| the baselines. The v2 backbone fixes the representational gap while keeping the | |
| actual novelty of the proposal - the hierarchical, physically biased set | |
| attention over formulation components. | |
| Architecture | |
| ------------ | |
| :: | |
| ionizable lipid ---> GINE (atom/bond graph) --> g_il [d] | |
| \\--> RDKit descriptors --> d_il [128] | |
| {head, linker, tail1..4, IL, HL, Chol, PEG} | |
| x_i = proj(Morgan fragment) + MLP(phys 16) + MLP(ratio/type) + type_emb | |
| x_IL += g_il (chemistry reaches the set) | |
| PhysicallyBiasedSetAttention x L -> PMA -> z_lnp | |
| condition cross-attention (ctx) -> z_cond | |
| z_form = LayerNorm(z_lnp + z_cond) | |
| y = MLP([z_form ; g_il ; d_il]) | |
| The final concatenation makes the model *contain* a pure graph+descriptor | |
| predictor, so it cannot be worse than AGILE for representational reasons; the | |
| set branch has to earn its keep. | |
| """ | |
| from __future__ import annotations | |
| from typing import Sequence | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| from ..featurize import ATOM_DIM, BOND_DIM | |
| from ..store import FeatureStore | |
| from ..trainer import NeuralModel, TrainConfig | |
| from .blocks import GINEEncoder, grad_reverse | |
| from .set_base import ( | |
| IDX_CCPP, | |
| IDX_CHARGE, | |
| IDX_HBA, | |
| IDX_HBD, | |
| IDX_LOGP, | |
| N_NODES, | |
| PHYS_DIM, | |
| PMA, | |
| ConditionCrossAttention, | |
| PhysicallyBiasedSetAttention, | |
| assemble_nodes, | |
| pair_bias, | |
| ) | |
| class FormulationEncoder(nn.Module): | |
| """Chemistry backbone + hierarchical physically biased set attention.""" | |
| def __init__( | |
| self, | |
| fp_dim: int, | |
| ctx_dim: int, | |
| desc_dim: int, | |
| d_model: int = 192, | |
| n_heads: int = 6, | |
| n_layers: int = 3, | |
| gnn_layers: int = 3, | |
| desc_dim_out: int = 128, | |
| dropout: float = 0.1, | |
| dual_state: bool = False, | |
| use_physics: bool = True, | |
| use_condition: bool = True, | |
| use_graph: bool = True, | |
| use_desc: bool = True, | |
| cond_mode: str = "cross", | |
| use_helpers: bool = True, | |
| comp_dropout: float = 0.0, | |
| node_mode: str = "fp", | |
| ): | |
| super().__init__() | |
| self.dual_state = dual_state | |
| # "fp" : each set node is identified by a Morgan fingerprint. This | |
| # makes the set a near-unique code for the ionisable lipid and | |
| # the model memorises lipid -> effect for the training studies | |
| # (measured: external Spearman collapses 0.192 -> 0.014 while | |
| # validation rises 0.253 -> 0.314). | |
| # "phys" : nodes carry only the 16 physics/physchem descriptors, their | |
| # type, the composition ratio, and (for the whole-lipid node) | |
| # the message-passed graph embedding. Identity is not | |
| # recoverable, so the set can only express physical | |
| # regularities - which is what the mechanism is meant to do. | |
| self.node_mode = node_mode | |
| # Helper lipid / cholesterol / PEG identity plus their molar ratios are | |
| # a near-unique fingerprint of the study that produced the formulation | |
| # (each library screens its own fixed grid of helpers and ratios). With | |
| # them the model fits the training studies much better and transfers | |
| # much worse; ``comp_dropout`` randomly hides the whole composition | |
| # block during training so the model cannot build a study-specific rule | |
| # on top of it, and ``use_helpers=False`` removes it outright. | |
| self.use_helpers = use_helpers | |
| self.comp_dropout = comp_dropout | |
| self.use_physics = use_physics | |
| self.use_condition = use_condition | |
| self.use_graph = use_graph | |
| self.use_desc = use_desc | |
| # "cross": experiment context queries the formulation set (multiplicative | |
| # gating - high capacity, but lets a study-specific rule form) | |
| # "concat": context is appended to the pooled representation (additive, | |
| # as in LiON / AGILE) | |
| # "none": chemistry only | |
| self.cond_mode = cond_mode if use_condition else "none" | |
| self.d_model = d_model | |
| self.desc_dim_out = desc_dim_out | |
| # --- chemistry stream ------------------------------------------------- | |
| self.gnn = GINEEncoder(ATOM_DIM, BOND_DIM, d_model, gnn_layers, dropout) | |
| if dual_state: | |
| self.gnn_prot = GINEEncoder(ATOM_DIM, BOND_DIM, d_model, gnn_layers, dropout) | |
| self.desc_enc = nn.Sequential( | |
| nn.Linear(desc_dim, 192), nn.SiLU(), nn.Dropout(dropout), | |
| nn.Linear(192, desc_dim_out), nn.SiLU(), | |
| ) | |
| self.desc_delta = nn.Sequential(nn.Linear(desc_dim_out, desc_dim_out), nn.SiLU()) | |
| # --- formulation set -------------------------------------------------- | |
| in_fp = fp_dim * (2 if dual_state else 1) | |
| self.fp_proj = nn.Sequential(nn.Linear(in_fp, d_model), nn.LayerNorm(d_model), nn.SiLU()) | |
| self.phys_proj = nn.Sequential(nn.Linear(PHYS_DIM, 64), nn.SiLU(), nn.Linear(64, d_model)) | |
| self.ratio_proj = nn.Sequential(nn.Linear(2, 32), nn.SiLU(), nn.Linear(32, d_model)) | |
| self.type_emb = nn.Embedding(N_NODES, d_model) | |
| self.il_graph_proj = nn.Linear(d_model, d_model) | |
| self.in_norm = nn.LayerNorm(d_model) | |
| self.layers = nn.ModuleList( | |
| [PhysicallyBiasedSetAttention(d_model, n_heads, 5, dropout) for _ in range(n_layers)] | |
| ) | |
| self.pma = PMA(d_model, n_heads, dropout) | |
| if self.cond_mode == "cross": | |
| self.cond = ConditionCrossAttention(d_model, ctx_dim, n_heads, dropout) | |
| elif self.cond_mode == "concat": | |
| self.ctx_proj = nn.Sequential(nn.Linear(ctx_dim, d_model), nn.SiLU(), nn.Linear(d_model, d_model)) | |
| self.fuse = nn.LayerNorm(d_model) | |
| # ------------------------------------------------------------------ | |
| def encode(self, batch: dict) -> dict: | |
| n = assemble_nodes(batch) | |
| B = n["fp"].shape[0] | |
| g_il = self.gnn(batch["graph"]) | |
| d_il = self.desc_enc(batch["desc"]) | |
| if not self.use_graph: | |
| g_il = torch.zeros_like(g_il) | |
| if not self.use_desc: | |
| d_il = torch.zeros_like(d_il) | |
| if self.dual_state: | |
| # helpers (HL, cholesterol, PEG) are not ionisable, so their | |
| # protonated representation is the neutral one. | |
| prot_nodes = torch.cat([batch["node_fp_prot"], batch["helper_fp"]], dim=1) | |
| fp = torch.cat([n["fp"], prot_nodes], dim=-1) | |
| g_il_prot = self.gnn_prot(batch["graph"]) | |
| # the protonation shift is what the dual state is meant to expose | |
| g_il_dual = torch.cat([g_il, g_il_prot], dim=-1) | |
| else: | |
| fp = n["fp"] | |
| g_il_dual = g_il | |
| x = ( | |
| self.phys_proj(n["phys"]) | |
| + self.ratio_proj(torch.stack([n["ratio"], n["il_na"]], dim=-1)) | |
| + self.type_emb(n["type"]) | |
| ) | |
| if self.node_mode == "fp": | |
| x = x + self.fp_proj(fp) | |
| # node 6 is the whole ionisable lipid: inject message-passed chemistry | |
| il_slot = torch.zeros(B, N_NODES, self.d_model, device=x.device, dtype=x.dtype) | |
| il_slot[:, 6] = 1.0 | |
| x = x + il_slot * self.il_graph_proj(g_il).unsqueeze(1) | |
| mask = n["mask"] | |
| if not self.use_helpers: | |
| mask = mask.clone() | |
| mask[:, 7:] = True | |
| elif self.comp_dropout > 0 and self.training: | |
| drop = torch.rand(B, 1, device=mask.device) < self.comp_dropout | |
| mask = mask.clone() | |
| mask[:, 7:] = mask[:, 7:] | drop | |
| x = self.in_norm(x) | |
| bias = pair_bias(n["phys"], n["ratio"]) if self.use_physics else None | |
| for layer in self.layers: | |
| x, _ = layer(x, bias, mask) | |
| z_lnp = self.pma(x, mask) | |
| if self.cond_mode == "cross": | |
| z_cond = self.cond(batch["ctx"], x, mask) | |
| z_form = self.fuse(z_lnp + z_cond) | |
| elif self.cond_mode == "concat": | |
| z_cond = self.ctx_proj(batch["ctx"]) | |
| z_form = self.fuse(z_lnp + z_cond) | |
| else: | |
| z_cond = torch.zeros_like(z_lnp) | |
| z_form = self.fuse(z_lnp) | |
| return { | |
| "z_form": z_form, "z_lnp": z_lnp, "z_cond": z_cond, | |
| "g_il": g_il, "g_il_dual": g_il_dual, "d_il": d_il, "nodes": n, | |
| } | |
| def out_dim(self) -> int: | |
| extra = self.d_model * (2 if self.dual_state else 1) | |
| return self.d_model + extra + self.desc_dim_out | |
| # --------------------------------------------------------------------------- | |
| # Shared loss: Huber + within-study pairwise ranking (+ optional adversarial) | |
| # --------------------------------------------------------------------------- | |
| class _BackboneLoss: | |
| lam_rank: float = 0.5 | |
| lam_adv: float = 0.0 | |
| lam_env: float = 0.0 | |
| lam_ortho: float = 0.0 | |
| lam_phys: float = 0.0 | |
| rank_gamma: float = 2.0 | |
| def _rank_loss(self, y_hat, batch): | |
| study = batch["study_id"] | |
| same = study[:, None] == study[None, :] | |
| diff = batch["y"][:, None] - batch["y"][None, :] | |
| valid = same & (diff > 1e-4) | |
| if not bool(valid.any()): | |
| return torch.zeros((), device=y_hat.device) | |
| pred_diff = y_hat[:, None] - y_hat[None, :] | |
| return F.softplus(-self.rank_gamma * pred_diff[valid]).mean() | |
| # --------------------------------------------------------------------------- | |
| # Method A (v2) - PhyCausal-LNP | |
| # --------------------------------------------------------------------------- | |
| class PhyCausalModule(nn.Module, _BackboneLoss): | |
| """v2: strong chemistry backbone + physics-biased set + optional disentanglement.""" | |
| def __init__( | |
| self, | |
| fp_dim: int, | |
| ctx_dim: int, | |
| desc_dim: int, | |
| n_studies: int, | |
| d_model: int = 192, | |
| n_heads: int = 6, | |
| n_layers: int = 3, | |
| z_dim: int = 128, | |
| dropout: float = 0.1, | |
| lam_rank: float = 0.5, | |
| lam_adv: float = 0.0, | |
| lam_env: float = 0.0, | |
| lam_ortho: float = 0.0, | |
| rank_gamma: float = 2.0, | |
| use_physics: bool = True, | |
| use_condition: bool = True, | |
| disentangle: bool = False, | |
| use_graph: bool = True, | |
| use_desc: bool = True, | |
| cond_mode: str = "cross", | |
| use_helpers: bool = True, | |
| comp_dropout: float = 0.0, | |
| node_mode: str = "fp", | |
| **kw, | |
| ): | |
| super().__init__() | |
| self.enc = FormulationEncoder( | |
| fp_dim=fp_dim, ctx_dim=ctx_dim, desc_dim=desc_dim, d_model=d_model, | |
| n_heads=n_heads, n_layers=n_layers, dropout=dropout, | |
| use_physics=use_physics, use_condition=use_condition, | |
| use_graph=use_graph, use_desc=use_desc, cond_mode=cond_mode, | |
| use_helpers=use_helpers, comp_dropout=comp_dropout, node_mode=node_mode, | |
| ) | |
| self.lam_rank, self.lam_adv, self.lam_env, self.lam_ortho = lam_rank, lam_adv, lam_env, lam_ortho | |
| self.rank_gamma = rank_gamma | |
| self.use_physics, self.use_condition = use_physics, use_condition | |
| self.disentangle = disentangle | |
| out = self.enc.out_dim | |
| self.trunk = nn.Sequential( | |
| nn.Linear(out, 256), nn.LayerNorm(256), nn.SiLU(), nn.Dropout(dropout), | |
| ) | |
| self.causal = nn.Sequential(nn.Linear(256, z_dim), nn.LayerNorm(z_dim), nn.SiLU()) | |
| self.predictor = nn.Sequential(nn.Linear(z_dim, 64), nn.SiLU(), nn.Linear(64, 1)) | |
| if disentangle: | |
| self.env = nn.Sequential(nn.Linear(256, z_dim), nn.LayerNorm(z_dim), nn.SiLU()) | |
| self.dom_c = nn.Sequential(nn.Linear(z_dim, 64), nn.SiLU(), nn.Linear(64, n_studies)) | |
| self.dom_e = nn.Sequential(nn.Linear(z_dim, 64), nn.SiLU(), nn.Linear(64, n_studies)) | |
| def forward(self, batch, grl_alpha: float = 1.0): | |
| e = self.enc.encode(batch) | |
| h = torch.cat([e["z_form"], e["g_il"], e["d_il"]], dim=-1) | |
| h = self.trunk(h) | |
| z_c = self.causal(h) | |
| out = {"y_hat": self.predictor(z_c).squeeze(-1), "z_c": z_c, "z": h} | |
| if self.disentangle: | |
| z_e = self.env(h) | |
| out["z_e"] = z_e | |
| out["d_c"] = self.dom_c(grad_reverse(z_c, grl_alpha)) | |
| out["d_e"] = self.dom_e(z_e) | |
| return out | |
| def compute_loss(self, batch, out, epoch=0, n_epochs=1): | |
| reg = F.smooth_l1_loss(out["y_hat"], batch["y"]) | |
| rank = self._rank_loss(out["y_hat"], batch) | |
| total = reg + self.lam_rank * rank | |
| logs = {"reg": float(reg.detach()), "rank": float(rank.detach())} | |
| if self.disentangle: | |
| p = min(1.0, epoch / max(1.0, 0.3 * n_epochs)) | |
| alpha = 2.0 / (1.0 + torch.exp(torch.tensor(-10.0 * p))).item() - 1.0 | |
| study = batch["study_id"] | |
| adv = F.cross_entropy(out["d_c"], study) | |
| env = F.cross_entropy(out["d_e"], study) | |
| zc, ze = out["z_c"], out["z_e"] | |
| zc = (zc - zc.mean(0)) / (zc.std(0) + 1e-6) | |
| ze = (ze - ze.mean(0)) / (ze.std(0) + 1e-6) | |
| ortho = ((zc.t() @ ze) / max(1, zc.shape[0])).pow(2).mean() | |
| total = total + self.lam_adv * adv + self.lam_env * env + self.lam_ortho * ortho | |
| logs.update(adv=float(adv.detach()), env=float(env.detach()), ortho=float(ortho.detach())) | |
| return total, logs | |
| class PhyCausalLNP(NeuralModel): | |
| name = "phcausal" | |
| def build(self, store: FeatureStore, cfg: TrainConfig) -> nn.Module: | |
| return PhyCausalModule( | |
| fp_dim=store.il_fp.shape[1], ctx_dim=store.ctx_dim, | |
| desc_dim=store.il_desc.shape[1], n_studies=store.n_studies, **self.kwargs | |
| ) | |
| def need(self) -> Sequence[str]: | |
| return ("y", "ctx", "ratios", "nodes", "helpers", "study_id", "graph", "desc") | |
| # --------------------------------------------------------------------------- | |
| # Method B (v2) - PhysSet-LNP : dual protonation state + MD/physics head | |
| # --------------------------------------------------------------------------- | |
| class PhysSetModule(nn.Module, _BackboneLoss): | |
| def __init__( | |
| self, | |
| fp_dim: int, | |
| ctx_dim: int, | |
| desc_dim: int, | |
| d_model: int = 192, | |
| n_heads: int = 6, | |
| n_layers: int = 3, | |
| z_dim: int = 128, | |
| dropout: float = 0.1, | |
| lam_rank: float = 0.5, | |
| lam_phys: float = 0.2, | |
| rank_gamma: float = 2.0, | |
| dual_state: bool = True, | |
| use_md_aux: bool = True, | |
| use_physics: bool = True, | |
| use_condition: bool = True, | |
| cond_mode: str = "cross", | |
| use_helpers: bool = True, | |
| comp_dropout: float = 0.0, | |
| node_mode: str = "fp", | |
| **kw, | |
| ): | |
| super().__init__() | |
| self.enc = FormulationEncoder( | |
| fp_dim=fp_dim, ctx_dim=ctx_dim, desc_dim=desc_dim, d_model=d_model, | |
| n_heads=n_heads, n_layers=n_layers, dropout=dropout, | |
| dual_state=dual_state, use_physics=use_physics, use_condition=use_condition, | |
| cond_mode=cond_mode, use_helpers=use_helpers, comp_dropout=comp_dropout, | |
| node_mode=node_mode, | |
| ) | |
| self.lam_rank, self.lam_phys, self.rank_gamma = lam_rank, lam_phys, rank_gamma | |
| self.use_md_aux, self.dual_state = use_md_aux, dual_state | |
| out = self.enc.out_dim | |
| self.trunk = nn.Sequential( | |
| nn.Linear(out, 256), nn.LayerNorm(256), nn.SiLU(), nn.Dropout(dropout), | |
| ) | |
| self.predictor = nn.Sequential(nn.Linear(256, 64), nn.SiLU(), nn.Linear(64, 1)) | |
| self.phys_head = nn.Sequential(nn.Linear(out, 96), nn.SiLU(), nn.Linear(96, 3)) | |
| def forward(self, batch): | |
| e = self.enc.encode(batch) | |
| feats = torch.cat([e["z_form"], e["g_il_dual"], e["d_il"]], dim=-1) | |
| h = self.trunk(feats) | |
| return { | |
| "y_hat": self.predictor(h).squeeze(-1), | |
| "phys": self.phys_head(feats), | |
| "z": h, | |
| } | |
| def compute_loss(self, batch, out, epoch=0, n_epochs=1): | |
| reg = F.smooth_l1_loss(out["y_hat"], batch["y"]) | |
| rank = self._rank_loss(out["y_hat"], batch) | |
| total = reg + self.lam_rank * rank | |
| logs = {"reg": float(reg.detach()), "rank": float(rank.detach())} | |
| if self.use_md_aux: | |
| target = batch["cpp"][:, [2, 3]] | |
| phys = F.l1_loss(out["phys"][:, :2], target) | |
| stable = torch.sigmoid(out["phys"][:, 2]) | |
| flag = batch["md_flag"] > 0 | |
| if bool(flag.any()): | |
| phys = phys + F.binary_cross_entropy( | |
| stable[flag].clamp(1e-6, 1 - 1e-6), batch["md_stable"][flag], reduction="mean" | |
| ) | |
| total = total + self.lam_phys * phys | |
| logs["phys"] = float(phys.detach()) | |
| return total, logs | |
| 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, | |
| desc_dim=store.il_desc.shape[1], **self.kwargs | |
| ) | |
| def need(self) -> Sequence[str]: | |
| return ("y", "ctx", "ratios", "nodes", "nodes_prot", "helpers", "study_id", | |
| "graph", "desc", "cpp", "md_flag") |