File size: 7,847 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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
"""Shared neural building blocks: GINE, D-MPNN, Bi-Mamba, PMA, GRL."""

from __future__ import annotations

import math
from typing import Optional

import torch
import torch.nn as nn
import torch.nn.functional as F


# ---------------------------------------------------------------------------
# Gradient reversal
# ---------------------------------------------------------------------------
class GradReverse(torch.autograd.Function):
    @staticmethod
    def forward(ctx, x, alpha):
        ctx.alpha = alpha
        return x.view_as(x)

    @staticmethod
    def backward(ctx, grad_output):
        return grad_output.neg() * ctx.alpha, None


def grad_reverse(x: torch.Tensor, alpha: float = 1.0) -> torch.Tensor:
    return GradReverse.apply(x, alpha)


# ---------------------------------------------------------------------------
# Graph encoders
# ---------------------------------------------------------------------------
class GINELayer(nn.Module):
    """Edge-featured GIN layer with pre-norm residual."""

    def __init__(self, dim: int, edge_dim: int, dropout: float = 0.0):
        super().__init__()
        self.eps = nn.Parameter(torch.zeros(1))
        self.edge_enc = nn.Linear(edge_dim, dim)
        self.mlp = nn.Sequential(nn.Linear(dim, 2 * dim), nn.SiLU(), nn.Dropout(dropout), nn.Linear(2 * dim, dim))
        self.norm = nn.LayerNorm(dim)
        self.dropout = nn.Dropout(dropout)

    def forward(self, x, edge_index, edge_attr):
        src, dst = edge_index
        msg = x[src] + self.edge_enc(edge_attr)
        agg = torch.zeros_like(x).index_add_(0, dst, msg)
        out = self.mlp((1.0 + self.eps) * x + agg)
        return self.norm(x + self.dropout(out))


def graph_pool(x: torch.Tensor, batch: torch.Tensor, n_graphs: int, mode: str = "mean") -> torch.Tensor:
    out = torch.zeros(n_graphs, x.shape[1], device=x.device, dtype=x.dtype).index_add_(0, batch, x)
    if mode == "mean":
        counts = torch.zeros(n_graphs, device=x.device, dtype=x.dtype).index_add_(
            0, batch, torch.ones_like(batch, dtype=x.dtype)
        )
        out = out / counts.clamp(min=1.0).unsqueeze(-1)
    return out


class GINEEncoder(nn.Module):
    def __init__(self, in_dim: int, edge_dim: int, hidden: int, n_layers: int = 3, dropout: float = 0.1):
        super().__init__()
        self.in_proj = nn.Linear(in_dim, hidden)
        self.layers = nn.ModuleList([GINELayer(hidden, edge_dim, dropout) for _ in range(n_layers)])

    def forward(self, g: dict) -> torch.Tensor:
        x = self.in_proj(g["x"])
        for layer in self.layers:
            x = layer(x, g["edge_index"], g["edge_attr"])
        return graph_pool(x, g["batch"], g["n_graphs"], mode="mean")


def _reverse_edge_index(edge_index: torch.Tensor) -> torch.Tensor:
    """Index of the reverse edge for each directed edge (edges stored in pairs)."""
    e = edge_index.shape[1]
    if e == 0:
        return torch.zeros(0, dtype=torch.long, device=edge_index.device)
    return torch.arange(e, device=edge_index.device) ^ 1


class DMPNNEncoder(nn.Module):
    """Directed message-passing neural network (chemprop-style), the LiON backbone."""

    def __init__(self, atom_dim: int, hidden: int = 300, depth: int = 3, dropout: float = 0.0):
        super().__init__()
        self.depth = depth
        self.W_i = nn.Linear(atom_dim, hidden, bias=False)
        self.W_o = nn.Linear(atom_dim + hidden, hidden)
        self.dropout = nn.Dropout(dropout)

    def forward(self, g: dict) -> torch.Tensor:
        x, edge_index, batch = g["x"], g["edge_index"], g["batch"]
        src, dst = edge_index
        h0 = self.W_i(x)
        rev = _reverse_edge_index(edge_index)
        m = h0[src]
        for _ in range(max(0, self.depth - 1)):
            agg = torch.zeros_like(h0).index_add_(0, dst, m)
            m = self.dropout(F.relu(h0[src] + agg[src] - m[rev]))
        agg = torch.zeros_like(h0).index_add_(0, dst, m)
        atom_h = F.relu(self.W_o(torch.cat([x, agg], dim=-1)))
        return graph_pool(atom_h, batch, g["n_graphs"], mode="mean")


# ---------------------------------------------------------------------------
# Selective state-space (Mamba) with a chunked parallel scan
# ---------------------------------------------------------------------------
class SelectiveSSM(nn.Module):
    """Minimal pure-PyTorch Mamba block with a chunked associative scan.

    The recurrence ``s_t = exp(dt_t A) s_{t-1} + dt_t B_t x_t`` is evaluated
    chunk-by-chunk so that no [B, L, D, N] tensor is ever materialised for the
    full sequence.  This keeps both memory and wall-clock cost low without
    requiring the CUDA kernels of ``mamba_ssm``.
    """

    def __init__(self, d_model: int, d_state: int = 8, chunk: int = 32):
        super().__init__()
        self.d_model = d_model
        self.d_state = d_state
        self.chunk = chunk
        self.in_proj = nn.Linear(d_model, 2 * d_model)
        self.conv1d = nn.Conv1d(d_model, d_model, kernel_size=3, padding=1, groups=d_model)
        self.x_proj = nn.Linear(d_model, 2 * d_state + 1)
        self.dt_proj = nn.Linear(1, d_model)
        A = torch.arange(1, d_state + 1, dtype=torch.float32).repeat(d_model, 1)
        self.A_log = nn.Parameter(torch.log(A))
        self.D = nn.Parameter(torch.ones(d_model))
        self.out_proj = nn.Linear(d_model, d_model)

    def forward(self, u: torch.Tensor, mask: Optional[torch.Tensor] = None) -> torch.Tensor:
        B, L, D = u.shape
        xz = self.in_proj(u)
        x, z = xz.chunk(2, dim=-1)
        x = F.silu(self.conv1d(x.transpose(1, 2)).transpose(1, 2))
        params = self.x_proj(x)
        b_t, c_t, dt_raw = torch.split(params, [self.d_state, self.d_state, 1], dim=-1)
        dt = F.softplus(self.dt_proj(dt_raw)) + 1e-4  # [B, L, D]
        A = -torch.exp(self.A_log)  # [D, N]

        state = torch.zeros(B, D, self.d_state, device=u.device, dtype=u.dtype)
        outs = []
        for start in range(0, L, self.chunk):
            end = min(start + self.chunk, L)
            dt_c = dt[:, start:end]
            x_c = x[:, start:end]
            bc = b_t[:, start:end]
            dA = torch.exp(dt_c.unsqueeze(-1) * A.view(1, 1, D, self.d_state))
            b = dt_c.unsqueeze(-1) * bc.unsqueeze(2) * x_c.unsqueeze(-1)
            if mask is not None:
                m = mask[:, start:end].unsqueeze(-1).unsqueeze(-1)
                dA = torch.where(m > 0, dA, torch.ones_like(dA))
                b = b * m
            lc = torch.cumsum(torch.log(dA.clamp(min=1e-12)), dim=1).clamp(min=-60.0)
            p_ = torch.exp(lc)
            scaled = b * torch.exp(-lc)
            o = p_ * state.unsqueeze(1) + p_ * torch.cumsum(scaled, dim=1)
            outs.append(o)
            state = o[:, -1]
        y = torch.cat(outs, dim=1)
        y = (y * c_t.unsqueeze(2)).sum(-1) + self.D * x
        return self.out_proj(y * F.silu(z))


class BiMambaEncoder(nn.Module):
    def __init__(self, vocab_size: int, d_model: int = 128, n_layers: int = 2, d_state: int = 8, chunk: int = 32):
        super().__init__()
        self.emb = nn.Embedding(vocab_size, d_model, padding_idx=0)
        self.fwd = nn.ModuleList([SelectiveSSM(d_model, d_state, chunk) for _ in range(n_layers)])
        self.bwd = nn.ModuleList([SelectiveSSM(d_model, d_state, chunk) for _ in range(n_layers)])
        self.norms = nn.ModuleList([nn.LayerNorm(d_model) for _ in range(n_layers)])

    def forward(self, tokens: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
        x = self.emb(tokens)
        for f, b, norm in zip(self.fwd, self.bwd, self.norms):
            yf = f(x, mask)
            yb = torch.flip(b(torch.flip(x, dims=[1]), torch.flip(mask, dims=[1])), dims=[1])
            x = norm(x + yf + yb)
        m = mask.unsqueeze(-1).float()
        return (x * m).sum(1) / m.sum(1).clamp(min=1.0)