LNPBench / code /src /lnpbench /models /backbone.py
eduzrh's picture
LNPBench: code, caches, results and figures
6a39e70 verified
Raw History Blame Contribute Delete
23.6 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,
schema_edge_mask,
)
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",
use_onto: bool = False,
onto_dim: int = 48,
use_edge_mask: bool = False,
use_global: bool = False,
global_dim: int = 75,
use_rel_mode: bool = False,
rel_kw: dict | None = None,
rel_use_ratio: bool = True,
):
super().__init__()
self.dual_state = dual_state
self.use_onto = use_onto
self.use_edge_mask = use_edge_mask
self.use_global = use_global
# "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)
if use_onto:
# role-aware ontology attributes: head class, linker chemistry,
# tail topology, helper class -- information the whole-molecule
# descriptor vector cannot express
self.onto_proj = nn.Sequential(
nn.Linear(onto_dim, 64), nn.SiLU(), nn.Linear(64, d_model)
)
if use_edge_mask:
self.register_buffer("edge_mask", schema_edge_mask(), persistent=False)
if use_global:
# position in the label-free global chemical codebook
self.glob_proj = nn.Sequential(
nn.Linear(global_dim, 64), nn.SiLU(), nn.Linear(64, d_model)
)
# LaRIN-style discrete latent relation modes over node pairs: the pair
# representation is quantised to K prototypes and the residual expert
# posterior is marginalised into the attention logits.
self.rel_use_ratio = rel_use_ratio
self.rel_mode = None
if use_rel_mode:
from .physmode import PairRelationModes
self.rel_mode = PairRelationModes(d_model=d_model, **(rel_kw or {}))
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, node_drop_p: float = 0.0) -> 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
ratio_part = self.ratio_proj(torch.stack([n["ratio"], n["il_na"]], dim=-1))
x = self.phys_proj(n["phys"]) + ratio_part + self.type_emb(n["type"])
if self.node_mode == "fp":
x = x + self.fp_proj(fp)
if self.use_onto and "node_onto" in batch:
x = x + self.onto_proj(batch["node_onto"])
# 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 node_drop_p > 0 and self.training:
# CoDiffGRN TASS analogue: supervise random node subsets so the set
# encoder cannot rely on any single component slot. The whole-lipid
# node (6) always stays, since it carries the chemistry stream.
drop = torch.rand(B, N_NODES, device=mask.device) < node_drop_p
drop[:, 6] = False
mask = mask | drop
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
em = self.edge_mask if self.use_edge_mask else None
rel_bias, self._rel_stats = (None, None)
if self.rel_mode is not None:
# inferred once from the input node embeddings, as in LaRIN, so the
# discrete relation is a property of the formulation, not of depth.
# ``rel_use_ratio=False`` drops the molar-composition channel, which
# is a near-unique fingerprint of the source study (Section 3.3.3).
x_rel = x if self.rel_use_ratio else x - ratio_part
rel_bias, self._rel_stats = self.rel_mode(x_rel, mask)
for layer in self.layers:
x, _ = layer(x, bias, mask, em, extra_bias=rel_bias)
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)
if self.use_global and "glob" in batch:
z_form = self.fuse(z_form + self.glob_proj(batch["glob"]))
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,
}
@property
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",
use_onto: bool = False,
onto_dim: int = 48,
use_edge_mask: bool = False,
use_global: bool = False,
global_dim: int = 75,
**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",
use_onto: bool = False,
onto_dim: int = 48,
use_edge_mask: bool = False,
use_global: bool = False,
global_dim: int = 75,
aux_dim: int = 0,
lam_aux: float = 1.0,
**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, use_onto=use_onto, onto_dim=onto_dim,
use_edge_mask=use_edge_mask, use_global=use_global, global_dim=global_dim,
)
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))
# external multi-task head (size / PDI / zeta / EE); aux_dim = 0 disables it
self.aux_dim, self.lam_aux = aux_dim, lam_aux
self.aux_head = (
nn.Sequential(nn.Linear(out, 96), nn.SiLU(), nn.Linear(96, aux_dim))
if aux_dim > 0 else None
)
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)
out = {
"y_hat": self.predictor(h).squeeze(-1),
"phys": self.phys_head(feats),
"z": h,
}
if self.aux_head is not None:
out["aux"] = self.aux_head(feats)
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.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())
if self.aux_head is not None and "aux" in batch:
m = batch["aux_mask"] > 0
if bool(m.any()):
aux = F.smooth_l1_loss(out["aux"][m], batch["aux"][m])
total = total + self.lam_aux * aux
logs["aux"] = float(aux.detach())
return total, logs
class PhysSetLNP(NeuralModel):
name = "physset"
def build(self, store: FeatureStore, cfg: TrainConfig) -> nn.Module:
kw = dict(self.kwargs)
pretrained = kw.pop("pretrained", None)
freeze_gnn = kw.pop("freeze_gnn", False)
if kw.get("use_onto") and "onto_dim" not in kw:
from ..ontology import ONTO_DIM
kw["onto_dim"] = ONTO_DIM
if kw.get("use_global") and "global_dim" not in kw:
kw["global_dim"] = int(store.global_codebook().shape[1])
module = PhysSetModule(
fp_dim=store.il_fp.shape[1], ctx_dim=store.ctx_dim,
desc_dim=store.il_desc.shape[1], **kw
)
if pretrained:
import torch as _torch
state = _torch.load(pretrained, map_location="cpu")
own = module.state_dict()
# the external corpus has a shorter context vector, so the first
# context layer differs in shape; transfer everything else.
keep = {k: v for k, v in state.items() if k in own and own[k].shape == v.shape}
dropped = [k for k in state if k not in keep]
module.load_state_dict(keep, strict=False)
print(f"[pretrained] {pretrained}: {len(keep)} tensors loaded, {len(dropped)} skipped")
if freeze_gnn:
# the graph encoder is the component that can memorise study identity;
# keeping the externally pretrained weights fixed removes that channel
frozen = 0
for name in ("gnn", "gnn_prot"):
net = getattr(module.enc, name, None)
if net is None:
continue
for p_ in net.parameters():
p_.requires_grad = False
frozen += 1
print(f"[freeze] {frozen} graph-encoder tensors frozen")
return module
def need(self) -> Sequence[str]:
need = ["y", "ctx", "ratios", "nodes", "nodes_prot", "helpers", "study_id",
"graph", "desc", "cpp", "md_flag"]
if int(self.kwargs.get("aux_dim", 0)) > 0:
need.append("aux")
if self.kwargs.get("use_onto"):
need.append("onto")
if self.kwargs.get("use_global"):
need.append("glob")
return tuple(need)