File size: 5,853 Bytes
d1988f5 dedf737 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 | """Shared hierarchical set encoder used by Methods A and B.
A formulation is represented as an unordered set of up to ten nodes:
0 head 1 linker 2-5 tail1..4 6 whole ionizable lipid
7 helper lipid 8 cholesterol 9 PEG lipid
Nodes carry (i) a Morgan fingerprint, (ii) a 16-dim physical descriptor and
(iii) the molar fraction, and are processed by permutation-equivariant set
attention whose logits receive a pairwise physical interaction bias.
"""
from __future__ import annotations
from typing import Sequence
import torch
import torch.nn as nn
import torch.nn.functional as F
from .attention import ConditionCrossAttention, PMA, PhysicallyBiasedSetAttention
N_NODES = 10
NODE_TYPES = ["head", "linker", "tail1", "tail2", "tail3", "tail4", "il", "hl", "chl", "peg"]
PHYS_DIM = 16
# indices inside the 16-dim physical descriptor
IDX_LOGP, IDX_CHARGE, IDX_HBD, IDX_HBA, IDX_CCPP, IDX_DCCPP = 0, 1, 2, 3, 4, 5
def assemble_nodes(batch: dict) -> dict:
"""Merge ionizable-lipid substructure nodes and the three helper-lipid nodes."""
node_fp = batch["node_fp"] # [B, 7, 2048]
node_phys = batch["node_phys"] # [B, 7, 16]
node_mask = batch["node_mask"] # [B, 7] True = pad
helper_fp = batch["helper_fp"] # [B, 3, 2048]
helper_phys = batch["helper_phys"] # [B, 3, 16]
helper_mask = batch["helper_mask"] # [B, 3] True = pad
fp = torch.cat([node_fp, helper_fp], dim=1)
phys = torch.cat([node_phys, helper_phys], dim=1)
mask = torch.cat([node_mask, helper_mask], dim=1)
ratios = batch["ratios"] # [B,5] -> w_il, w_hl, w_chl, w_peg, log_il_na/5
B = fp.shape[0]
node_ratio = torch.zeros(B, N_NODES, device=fp.device, dtype=fp.dtype)
node_ratio[:, :7] = ratios[:, 0:1]
node_ratio[:, 7] = ratios[:, 1]
node_ratio[:, 8] = ratios[:, 2]
node_ratio[:, 9] = ratios[:, 3]
is_il = torch.zeros(B, N_NODES, device=fp.device, dtype=fp.dtype)
is_il[:, :7] = 1.0
il_na = ratios[:, 4:5] * is_il
types = torch.arange(N_NODES, device=fp.device).unsqueeze(0).expand(B, -1)
return {
"fp": fp,
"phys": phys,
"mask": mask,
"ratio": node_ratio,
"il_na": il_na,
"type": types,
}
def pair_bias(phys: torch.Tensor, ratio: torch.Tensor) -> torch.Tensor:
"""5-dim pairwise physical interaction bias."""
logp = phys[..., IDX_LOGP]
q = phys[..., IDX_CHARGE]
hbd = phys[..., IDX_HBD]
hba = phys[..., IDX_HBA]
ccpp = phys[..., IDX_CCPP]
w = ratio.clamp(min=0.0)
return torch.stack(
[
-(logp[:, :, None] - logp[:, None, :]).abs(),
-(q[:, :, None] * q[:, None, :]),
hbd[:, :, None] * hba[:, None, :] + hba[:, :, None] * hbd[:, None, :],
-(ccpp[:, :, None] - ccpp[:, None, :]).abs(),
(w[:, :, None] * w[:, None, :]).clamp(min=0.0).sqrt(),
],
dim=-1,
)
def schema_edge_mask() -> torch.Tensor:
"""Typed adjacency of the formulation schema.
Nodes 0 head, 1 linker, 2-5 tail1..4, 6 whole ionisable lipid, 7 helper,
8 cholesterol, 9 PEG. Covalent bonds only exist inside the ionisable
lipid, and only through the linker; the helper lipids co-assemble with the
whole lipid and with each other, never with an isolated fragment. Every
node is connected to itself so that a node whose partners are missing in a
given formulation still has a well-defined update.
"""
E = torch.zeros(N_NODES, N_NODES, dtype=torch.bool)
E.fill_diagonal_(True)
E[0, 1] = E[1, 0] = True # head -- linker
for k in range(2, 6):
E[1, k] = E[k, 1] = True # linker -- tail k
for k in range(7):
E[6, k] = E[k, 6] = True # whole lipid -- its parts
for a in range(7, 10):
for b in range(7, 10):
E[a, b] = True # helper co-assembly
return E
class HierarchicalSetEncoder(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,
phys_dim: int = PHYS_DIM,
dual_state: bool = False,
):
super().__init__()
self.dual_state = dual_state
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.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)
self.cond = ConditionCrossAttention(d_model, ctx_dim, n_heads, dropout)
self.fuse = nn.LayerNorm(d_model)
self.d_model = d_model
def forward(self, batch, fp_override: torch.Tensor | None = None, use_physics: bool = True):
n = assemble_nodes(batch)
fp = fp_override if fp_override is not None else n["fp"]
x = (
self.fp_proj(fp)
+ self.phys_proj(n["phys"])
+ self.ratio_proj(torch.stack([n["ratio"], n["il_na"]], dim=-1))
+ self.type_emb(n["type"])
)
x = self.in_norm(x)
bias = pair_bias(n["phys"], n["ratio"]) if use_physics else None
for layer in self.layers:
x, _ = layer(x, bias, n["mask"])
z_lnp = self.pma(x, n["mask"])
z_cond = self.cond(batch["ctx"], x, n["mask"])
return self.fuse(z_lnp + z_cond), z_lnp, z_cond, n |