Upload modeling_bioxmol.py
Browse files- modeling_bioxmol.py +140 -0
modeling_bioxmol.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Self-contained molecular encoder for BioXMol.
|
| 3 |
+
|
| 4 |
+
This is the molecule branch (a Gated Graph Neural Network) of the BioXMol
|
| 5 |
+
soft-contrastive model. It maps a molecular graph to a fixed-length embedding.
|
| 6 |
+
No part of the mocop training framework is required to run it.
|
| 7 |
+
|
| 8 |
+
Architecture (as trained): n_edge=1, in_dim=75, n_conv=6, fc_dims=[1024, 128].
|
| 9 |
+
Embedding layers exposed by `embed(...)`:
|
| 10 |
+
"GNN" -> 75-d (graph-level sum-pooled node features)
|
| 11 |
+
"first_fc" -> 1024-d (after fc_layers[0]: Linear -> Tanh)
|
| 12 |
+
"second_fc" -> 128-d (after fc_layers[1]: Linear; contrastive projection)
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
import math
|
| 16 |
+
from typing import Iterable, List
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
import torch.nn as nn
|
| 20 |
+
import torch.nn.functional as F
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class GraphConvolution(nn.Module):
|
| 24 |
+
def __init__(self, in_dim: int, out_dim: int, n_edge: int = 1, bias: bool = True):
|
| 25 |
+
super().__init__()
|
| 26 |
+
self.weight = nn.Parameter(torch.Tensor(n_edge, in_dim, out_dim))
|
| 27 |
+
if bias:
|
| 28 |
+
self.bias = nn.Parameter(torch.Tensor(n_edge, 1, out_dim))
|
| 29 |
+
else:
|
| 30 |
+
self.register_parameter("bias", None)
|
| 31 |
+
self.reset_parameters()
|
| 32 |
+
|
| 33 |
+
def reset_parameters(self):
|
| 34 |
+
nn.init.xavier_uniform_(self.weight)
|
| 35 |
+
if self.bias is not None:
|
| 36 |
+
nn.init.zeros_(self.bias)
|
| 37 |
+
|
| 38 |
+
def forward(self, adj: torch.Tensor, feat: torch.Tensor) -> torch.Tensor:
|
| 39 |
+
if len(adj.size()) == 3:
|
| 40 |
+
adj = adj.unsqueeze(1)
|
| 41 |
+
feat = feat.unsqueeze(1)
|
| 42 |
+
output = torch.matmul(adj, feat)
|
| 43 |
+
output = torch.matmul(output, self.weight)
|
| 44 |
+
if self.bias is not None:
|
| 45 |
+
output = output + self.bias
|
| 46 |
+
output = output.sum(dim=1)
|
| 47 |
+
return F.relu(output)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class GRU2D(nn.Module):
|
| 51 |
+
"""2D GRU cell used to gate information flow between conv layers."""
|
| 52 |
+
|
| 53 |
+
def __init__(self, in_dim: int, hidden_dim: int, bias: bool = True):
|
| 54 |
+
super().__init__()
|
| 55 |
+
self.x_to_intermediate = nn.Linear(in_dim, 3 * hidden_dim, bias=bias)
|
| 56 |
+
self.h_to_intermediate = nn.Linear(in_dim, 3 * hidden_dim, bias=bias)
|
| 57 |
+
self.reset_parameters()
|
| 58 |
+
|
| 59 |
+
def reset_parameters(self):
|
| 60 |
+
for k, v in self.state_dict().items():
|
| 61 |
+
if "weight" in k:
|
| 62 |
+
std = math.sqrt(6.0 / (v.size(1) + v.size(0) / 3))
|
| 63 |
+
nn.init.uniform_(v, a=-std, b=std)
|
| 64 |
+
elif "bias" in k:
|
| 65 |
+
nn.init.zeros_(v)
|
| 66 |
+
|
| 67 |
+
def forward(self, x: torch.Tensor, h_0: torch.Tensor) -> torch.Tensor:
|
| 68 |
+
ix = self.x_to_intermediate(x)
|
| 69 |
+
ih = self.h_to_intermediate(h_0)
|
| 70 |
+
x_r, x_z, x_n = ix.chunk(3, -1)
|
| 71 |
+
h_r, h_z, h_n = ih.chunk(3, -1)
|
| 72 |
+
r = torch.sigmoid(x_r + h_r)
|
| 73 |
+
z = torch.sigmoid(x_z + h_z)
|
| 74 |
+
n = torch.tanh(x_n + (r * h_n))
|
| 75 |
+
return (1 - z) * n + z * h_0
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class GatedGraphConvolution(nn.Module):
|
| 79 |
+
def __init__(self, in_dim: int, out_dim: int, n_edge: int = 1, bias: bool = True):
|
| 80 |
+
super().__init__()
|
| 81 |
+
if in_dim != out_dim:
|
| 82 |
+
raise ValueError(f"in_dim ({in_dim}) must equal out_dim ({out_dim}).")
|
| 83 |
+
self.gc = GraphConvolution(in_dim=in_dim, out_dim=out_dim, n_edge=n_edge, bias=bias)
|
| 84 |
+
self.gru = GRU2D(in_dim=out_dim, hidden_dim=out_dim, bias=bias)
|
| 85 |
+
|
| 86 |
+
def forward(self, adj: torch.Tensor, h_0: torch.Tensor) -> torch.Tensor:
|
| 87 |
+
h = self.gc(adj, h_0)
|
| 88 |
+
return self.gru(h, h_0)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
class GatedGraphNeuralNetwork(nn.Module):
|
| 92 |
+
def __init__(
|
| 93 |
+
self,
|
| 94 |
+
n_edge: int = 1,
|
| 95 |
+
in_dim: int = 75,
|
| 96 |
+
n_conv: int = 6,
|
| 97 |
+
fc_dims: Iterable[int] = (1024, 128),
|
| 98 |
+
p_dropout: float = 0.0,
|
| 99 |
+
):
|
| 100 |
+
super().__init__()
|
| 101 |
+
fc_dims = list(fc_dims)
|
| 102 |
+
self.conv_layers = nn.ModuleList(
|
| 103 |
+
[GatedGraphConvolution(in_dim=in_dim, out_dim=in_dim, n_edge=n_edge) for _ in range(n_conv)]
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
num_fc = len(fc_dims)
|
| 107 |
+
dims = [in_dim] + fc_dims
|
| 108 |
+
fc_layers = []
|
| 109 |
+
for i, (a, b) in enumerate(zip(dims[:-1], dims[1:])):
|
| 110 |
+
layer = nn.Linear(a, b)
|
| 111 |
+
if i < num_fc - 2:
|
| 112 |
+
layer = nn.Sequential(layer, nn.ReLU())
|
| 113 |
+
elif i == num_fc - 2:
|
| 114 |
+
layer = nn.Sequential(layer, nn.Tanh())
|
| 115 |
+
fc_layers.append(layer)
|
| 116 |
+
self.fc_layers = nn.ModuleList(fc_layers)
|
| 117 |
+
self.dropout = nn.Dropout(p=p_dropout)
|
| 118 |
+
|
| 119 |
+
def _pool(self, adj, node_feat, atom_vec):
|
| 120 |
+
for conv in self.conv_layers:
|
| 121 |
+
node_feat = conv(adj, node_feat)
|
| 122 |
+
node_feat = self.dropout(node_feat)
|
| 123 |
+
return (node_feat * atom_vec).sum(1) # graph-level, masks padded atoms
|
| 124 |
+
|
| 125 |
+
def embed(self, adj, node_feat, atom_vec, layer: str = "first_fc") -> torch.Tensor:
|
| 126 |
+
"""Return embeddings from a chosen layer. Call model.eval() first."""
|
| 127 |
+
h = self._pool(adj, node_feat, atom_vec)
|
| 128 |
+
if layer == "GNN":
|
| 129 |
+
return h
|
| 130 |
+
h = self.fc_layers[0](h)
|
| 131 |
+
if layer == "first_fc":
|
| 132 |
+
return h
|
| 133 |
+
h = self.dropout(h)
|
| 134 |
+
h = self.fc_layers[1](h)
|
| 135 |
+
if layer == "second_fc":
|
| 136 |
+
return h
|
| 137 |
+
raise ValueError(f"Unknown layer '{layer}'. Use 'GNN', 'first_fc', or 'second_fc'.")
|
| 138 |
+
|
| 139 |
+
def forward(self, adj, node_feat, atom_vec):
|
| 140 |
+
return self.embed(adj, node_feat, atom_vec, layer="second_fc")
|