LNPBench / code /src /lnpbench /models /seq_backbone.py
eduzrh's picture
LNPBench: code, caches, results and figures
c4e317f verified
Raw History Blame Contribute Delete
7.04 kB
"""Method C (v2) - SeqCausal-LNP.
Dual-stream molecular encoder (GINE graph stream + bidirectional selective
state space over SMILES tokens), gated fusion, FiLM condition modulation and
GroupDRO across source studies.
Changes from v1, both driven by measurements rather than taste:
* the RDKit descriptor branch is added. v1 fed the graph/sequence streams
straight into the formulation MLP, which left the model without the feature
block that the strongest tabular baseline relies on.
* the adversarial domain classifier / environment-absorption / orthogonality
trio is removed. On the external protocol that mechanism *reduced* accuracy
(removing it moved method A from -0.108 to -0.009 on LM_2019), so keeping it
would only handicap method C. The causal story is carried by GroupDRO plus
the within-study ranking loss, which are preserved.
"""
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 .attention import BiMambaEncoder
from .blocks import GINEEncoder
class SeqCausalModule(nn.Module):
def __init__(
self,
ctx_dim: int,
vocab_size: int,
n_studies: int,
desc_dim: int = 217,
d_model: int = 160,
gnn_layers: int = 3,
mamba_layers: int = 2,
d_state: int = 8,
desc_out: int = 128,
dropout: float = 0.1,
lam_rank: float = 0.4,
rank_gamma: float = 2.0,
eta_q: float = 0.05,
c_adj: float = 1.0,
use_mamba: bool = True,
use_gdro: bool = True,
use_desc: bool = True,
**kw,
):
super().__init__()
self.gnn = GINEEncoder(ATOM_DIM, BOND_DIM, d_model, gnn_layers, dropout)
self.mamba = (
BiMambaEncoder(vocab_size, d_model=d_model, n_layers=mamba_layers, d_state=d_state)
if use_mamba else None
)
self.gate = nn.Linear(2 * d_model if use_mamba else d_model, d_model)
self.desc_enc = nn.Sequential(
nn.Linear(desc_dim, 192), nn.SiLU(), nn.Dropout(dropout),
nn.Linear(192, desc_out), nn.SiLU(),
)
self.lipid_fuse = nn.Sequential(
nn.Linear(d_model + 16 + desc_out, d_model), nn.LayerNorm(d_model), nn.SiLU()
)
self.helper_proj = nn.Sequential(nn.Linear(2048 + 16 + 1, d_model), nn.SiLU())
self.form_mlp = nn.Sequential(nn.Linear(4 * d_model + 5, d_model), nn.LayerNorm(d_model), nn.SiLU())
self.film_gamma = nn.Linear(ctx_dim, d_model)
self.film_beta = nn.Linear(ctx_dim, d_model)
head_in = d_model + d_model + desc_out
self.trunk = nn.Sequential(nn.Linear(head_in, 256), nn.LayerNorm(256), nn.SiLU(), nn.Dropout(dropout))
self.predictor = nn.Sequential(nn.Linear(256, 64), nn.SiLU(), nn.Linear(64, 1))
self.lam_rank, self.rank_gamma = lam_rank, rank_gamma
self.use_mamba, self.use_gdro, self.use_desc = use_mamba, use_gdro, use_desc
self.eta_q, self.c_adj, self.n_studies = eta_q, c_adj, n_studies
self.register_buffer("q", torch.ones(n_studies) / n_studies)
self.register_buffer("n_seen", torch.zeros(n_studies))
# ------------------------------------------------------------------
def _lipid_embedding(self, batch):
h_g = self.gnn(batch["graph"])
if self.mamba is not None:
h_s = self.mamba(batch["tokens"], batch["token_mask"])
alpha = torch.sigmoid(self.gate(torch.cat([h_g, h_s], dim=-1)))
h = alpha * h_g + (1.0 - alpha) * h_s
else:
h = h_g
return h, h_g
def _helper_embedding(self, batch, si: int):
ratio = batch["ratios"][:, si + 1 : si + 2]
x = torch.cat([batch["helper_fp"][:, si], batch["helper_phys"][:, si], ratio], dim=-1)
h = self.helper_proj(x)
return h * (~batch["helper_mask"][:, si]).float().unsqueeze(-1)
def forward(self, batch, **kwargs):
h_il, g_il = self._lipid_embedding(batch)
d_il = self.desc_enc(batch["desc"])
if not self.use_desc:
d_il = torch.zeros_like(d_il)
h_il = self.lipid_fuse(torch.cat([h_il, batch["cpp"], d_il], dim=-1))
h_hl = self._helper_embedding(batch, 0)
h_chl = self._helper_embedding(batch, 1)
h_peg = self._helper_embedding(batch, 2)
z_form = self.form_mlp(torch.cat([h_il, h_hl, h_chl, h_peg, batch["ratios"]], dim=-1))
z = self.film_gamma(batch["ctx"]) * z_form + self.film_beta(batch["ctx"])
h = self.trunk(torch.cat([z, g_il, d_il], dim=-1))
return {"y_hat": self.predictor(h).squeeze(-1), "z": h}
# ------------------------------------------------------------------
def _group_weights(self, study: torch.Tensor, per_sample: torch.Tensor):
losses = torch.zeros(self.n_studies, device=per_sample.device)
present = torch.zeros(self.n_studies, dtype=torch.bool, device=per_sample.device)
for d in torch.unique(study):
mask = study == d
losses[d] = per_sample[mask].mean()
present[d] = True
if self.training and self.use_gdro:
with torch.no_grad():
self.n_seen += present.float()
adj = self.c_adj / torch.sqrt(self.n_seen.clamp(min=1.0))
q = self.q.clone()
q[present] = q[present] * torch.exp(self.eta_q * (losses[present].detach() + adj[present]))
self.q.copy_(q / q.sum().clamp(min=1e-9))
weights = self.q[study] if self.use_gdro else torch.ones_like(per_sample)
return losses, present, weights
def compute_loss(self, batch, out, epoch=0, n_epochs=1):
per_sample = F.smooth_l1_loss(out["y_hat"], batch["y"], reduction="none")
study = batch["study_id"]
_, _, w = self._group_weights(study, per_sample)
reg = (per_sample * w / w.mean().clamp(min=1e-6)).mean()
same = study[:, None] == study[None, :]
diff = batch["y"][:, None] - batch["y"][None, :]
valid = same & (diff > 1e-4)
if bool(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)
total = reg + self.lam_rank * rank
return total, {"reg": float(reg.detach()), "rank": float(rank.detach())}
class SeqCausalLNP(NeuralModel):
name = "seqcausal"
def build(self, store: FeatureStore, cfg: TrainConfig) -> nn.Module:
return SeqCausalModule(
ctx_dim=store.ctx_dim, vocab_size=len(store.token_vocab),
n_studies=store.n_studies, desc_dim=store.il_desc.shape[1], **self.kwargs,
)
def need(self) -> Sequence[str]:
return ("y", "ctx", "ratios", "graph", "tokens", "helpers", "cpp", "study_id", "desc")