File size: 7,203 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 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 | """Method C - SeqCausal-LNP.
Dual-stream molecular encoder (GINE graph stream + bidirectional selective
state space / Mamba over SMILES tokens), gated fusion, FiLM condition
modulation, causal/environment disentanglement and GroupDRO across the source
studies.
"""
from __future__ import annotations
import math
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, grad_reverse
HELPER_SLOTS = ("HL", "CHL", "PEG")
class SeqCausalModule(nn.Module):
def __init__(
self,
ctx_dim: int,
vocab_size: int,
n_studies: int,
d_model: int = 160,
gnn_layers: int = 3,
mamba_layers: int = 2,
d_state: int = 8,
z_dim: int = 96,
dropout: float = 0.1,
lam_rank: float = 0.4,
lam_adv: float = 0.1,
lam_env: float = 0.1,
lam_ortho: float = 0.05,
rank_gamma: float = 2.0,
eta_q: float = 0.05,
c_adj: float = 1.0,
use_mamba: bool = True,
use_gdro: bool = True,
):
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.lipid_fuse = nn.Sequential(nn.Linear(d_model + 16, 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)
self.causal = nn.Sequential(nn.Linear(d_model, z_dim), nn.LayerNorm(z_dim), nn.SiLU())
self.env = nn.Sequential(nn.Linear(d_model, z_dim), nn.LayerNorm(z_dim), nn.SiLU())
self.predictor = nn.Sequential(nn.Linear(z_dim, 64), nn.SiLU(), nn.Dropout(dropout), nn.Linear(64, 1))
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))
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_mamba, self.use_gdro = use_mamba, use_gdro
self.eta_q, self.c_adj = eta_q, c_adj
self.n_studies = 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)))
return alpha * h_g + (1.0 - alpha) * h_s
return 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, grl_alpha: float = 1.0):
h_il = self._lipid_embedding(batch)
h_il = self.lipid_fuse(torch.cat([h_il, batch["cpp"]], 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"])
z_c = self.causal(z)
z_e = self.env(z)
y_hat = self.predictor(z_c).squeeze(-1)
d_c = self.dom_c(grad_reverse(z_c, grl_alpha))
d_e = self.dom_e(z_e)
return {"y_hat": y_hat, "z_c": z_c, "z_e": z_e, "d_c": d_c, "d_e": d_e, "z": z}
# ------------------------------------------------------------------
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):
p = min(1.0, epoch / max(1.0, 0.3 * n_epochs))
grl_alpha = 2.0 / (1.0 + math.exp(-10.0 * p)) - 1.0
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 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)
adv = F.cross_entropy(out["d_c"], study)
env = F.cross_entropy(out["d_e"], study)
zc = out["z_c"]
ze = 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 = reg + self.lam_rank * rank + self.lam_adv * adv + self.lam_env * env + self.lam_ortho * ortho
return total, {
"reg": float(reg.detach()), "rank": float(rank.detach()),
"adv": float(adv.detach()), "env": float(env.detach()), "ortho": float(ortho.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, **self.kwargs,
)
def need(self) -> Sequence[str]:
return ("y", "ctx", "ratios", "graph", "tokens", "helpers", "cpp", "study_id") |