File size: 5,926 Bytes
d1988f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a39e70
d1988f5
 
 
 
 
 
6a39e70
 
 
 
 
 
d1988f5
 
dedf737
 
 
 
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
"""Attention and sequence modules (PMA, physically biased set attention, Bi-Mamba)."""

from __future__ import annotations

import math

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

from .blocks import SelectiveSSM


class PhysicallyBiasedSetAttention(nn.Module):
    """Permutation-equivariant set attention with a pairwise physical bias."""

    def __init__(self, d_model: int, n_heads: int, phys_dim: int, dropout: float = 0.1, bias_hidden: int = 32):
        super().__init__()
        assert d_model % n_heads == 0
        self.d_model, self.n_heads = d_model, n_heads
        self.d_head = d_model // n_heads
        self.qkv = nn.Linear(d_model, 3 * d_model)
        self.out = nn.Linear(d_model, d_model)
        self.bias_mlp = nn.Sequential(nn.Linear(phys_dim, bias_hidden), nn.SiLU(), nn.Linear(bias_hidden, n_heads))
        self.norm1 = nn.LayerNorm(d_model)
        self.norm2 = nn.LayerNorm(d_model)
        self.ffn = nn.Sequential(
            nn.Linear(d_model, 4 * d_model), nn.GELU(), nn.Dropout(dropout),
            nn.Linear(4 * d_model, d_model), nn.Dropout(dropout),
        )
        self.dropout = nn.Dropout(dropout)

    def forward(self, x, phys_pair, pad_mask=None, edge_mask=None, extra_bias=None):
        B, N, _ = x.shape
        qkv = self.qkv(x).view(B, N, 3, self.n_heads, self.d_head).permute(2, 0, 3, 1, 4)
        q, k, v = qkv[0], qkv[1], qkv[2]
        scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.d_head)
        if phys_pair is not None:
            scores = scores + self.bias_mlp(phys_pair).permute(0, 3, 1, 2)
        if extra_bias is not None:
            # bias produced by the discrete relation-mode decoder
            # (physmode.PairRelationModes): [B, N, N] is shared by all heads,
            # [B, N, N, H] gives every head its own coupling profile
            scores = scores + (extra_bias.permute(0, 3, 1, 2)
                               if extra_bias.dim() == 4 else extra_bias.unsqueeze(1))
        if pad_mask is not None:
            scores = scores.masked_fill(pad_mask[:, None, None, :], float("-inf"))
        if edge_mask is not None:
            # typed adjacency: a node may only attend to the slots the schema
            # says it is bonded to or co-assembles with
            scores = scores.masked_fill(~edge_mask.view(1, 1, *edge_mask.shape), float("-inf"))
        attn = self.dropout(torch.softmax(scores, dim=-1))
        if edge_mask is not None:
            # a fully masked query row (all its schema partners absent) would
            # otherwise produce NaN; make it contribute nothing
            attn = torch.nan_to_num(attn, nan=0.0)
        out = torch.matmul(attn, v).transpose(1, 2).contiguous().view(B, N, self.d_model)
        x = self.norm1(x + self.out(out))
        x = self.norm2(x + self.ffn(x))
        return x, attn


class PMA(nn.Module):
    """Pooling by multi-head attention."""

    def __init__(self, d_model: int, n_heads: int, dropout: float = 0.1):
        super().__init__()
        self.seed = nn.Parameter(torch.randn(1, 1, d_model) * 0.02)
        self.attn = nn.MultiheadAttention(d_model, n_heads, batch_first=True, dropout=dropout)
        self.norm = nn.LayerNorm(d_model)

    def forward(self, x, pad_mask=None):
        B = x.shape[0]
        q = self.seed.expand(B, -1, -1)
        out, _ = self.attn(q, x, x, key_padding_mask=pad_mask, need_weights=False)
        return self.norm(out.squeeze(1))


class ConditionCrossAttention(nn.Module):
    """Experiment context as a query over lipid nodes."""

    def __init__(self, d_model: int, ctx_dim: int, n_heads: int, dropout: float = 0.1):
        super().__init__()
        self.enc = nn.Sequential(nn.Linear(ctx_dim, d_model), nn.SiLU(), nn.Linear(d_model, d_model))
        self.attn = nn.MultiheadAttention(d_model, n_heads, batch_first=True, dropout=dropout)
        self.norm = nn.LayerNorm(d_model)

    def forward(self, ctx, nodes, pad_mask=None):
        q = self.enc(ctx).unsqueeze(1)
        out, _ = self.attn(q, nodes, nodes, key_padding_mask=pad_mask, need_weights=False)
        return self.norm(out.squeeze(1))


class BiMambaEncoder(nn.Module):
    def __init__(self, vocab_size: int, d_model: int = 128, n_layers: int = 2, d_state: int = 8, chunk: int = 16):
        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)


def masked_pair_bias(feat: torch.Tensor) -> torch.Tensor:
    """Build the 5-dim pair interaction bias shared by Methods A/B.

    feat: [B, N, F] with channel layout
       0 logP, 1 protonated charge, 2 HBD, 3 HBA, 4 cCPP(prot), 5 dCCPP, 6 molar ratio
    """
    logp = feat[..., 0]
    q = feat[..., 1]
    hbd = feat[..., 2]
    hba = feat[..., 3]
    ccpp = feat[..., 4]
    dccpp = feat[..., 5]
    w = feat[..., 6].clamp(min=0.0)
    bias = 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,
    )
    return bias