File size: 15,211 Bytes
ca7299e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
from opt_einsum import contract as einsum
# from model.model_utils import init_lecun_normal

class FeedForwardLayer(nn.Module):
    def __init__(self, d_model, r_ff, p_drop=0.1):
        super(FeedForwardLayer, self).__init__()
        self.norm = nn.LayerNorm(d_model)
        self.linear1 = nn.Linear(d_model, d_model*r_ff)
        self.dropout = nn.Dropout(p_drop)
        self.linear2 = nn.Linear(d_model*r_ff, d_model)

        # self.reset_parameter()

    # def reset_parameter(self):
    #     # initialize linear layer right before ReLu: He initializer (kaiming normal)
    #     nn.init.kaiming_normal_(self.linear1.weight, nonlinearity='relu')
    #     nn.init.zeros_(self.linear1.bias)

    #     # initialize linear layer right before residual connection: zero initialize
    #     nn.init.zeros_(self.linear2.weight)
    #     nn.init.zeros_(self.linear2.bias)
    
    def forward(self, src):
        src = self.norm(src)
        src = self.linear2(self.dropout(F.relu_(self.linear1(src))))
        return src

class Attention(nn.Module):
    # calculate multi-head attention
    def __init__(self, d_query, d_key, n_head, d_hidden, d_out):
        super(Attention, self).__init__()
        self.h = n_head
        self.dim = d_hidden
        #
        self.to_q = nn.Linear(d_query, n_head*d_hidden, bias=False)
        self.to_k = nn.Linear(d_key, n_head*d_hidden, bias=False)
        self.to_v = nn.Linear(d_key, n_head*d_hidden, bias=False)
        #
        self.to_out = nn.Linear(n_head*d_hidden, d_out)
        self.scaling = 1/math.sqrt(d_hidden)
        #
        # initialize all parameters properly
        # self.reset_parameter()

    # def reset_parameter(self):
    #     # query/key/value projection: Glorot uniform / Xavier uniform
    #     nn.init.xavier_uniform_(self.to_q.weight)
    #     nn.init.xavier_uniform_(self.to_k.weight)
    #     nn.init.xavier_uniform_(self.to_v.weight)

    #     # to_out: right before residual connection: zero initialize -- to make it sure residual operation is same to the Identity at the begining
    #     nn.init.zeros_(self.to_out.weight)
    #     nn.init.zeros_(self.to_out.bias)

    def forward(self, query, key, value):
        B, Q = query.shape[:2]
        B, K = key.shape[:2]
        #
        query = self.to_q(query).reshape(B, Q, self.h, self.dim)
        key = self.to_k(key).reshape(B, K, self.h, self.dim)
        value = self.to_v(value).reshape(B, K, self.h, self.dim)
        #
        query = query * self.scaling
        attn = einsum('bqhd,bkhd->bhqk', query, key)
        attn = F.softmax(attn, dim=-1)
        #
        out = einsum('bhqk,bkhd->bqhd', attn, value)
        out = out.reshape(B, Q, self.h*self.dim)
        #
        out = self.to_out(out)

        return out

class AttentionWithBias(nn.Module):
    def __init__(self, d_in=256, d_bias=128, n_head=8, d_hidden=32):
        super(AttentionWithBias, self).__init__()
        self.norm_in = nn.LayerNorm(d_in)
        self.norm_bias = nn.LayerNorm(d_bias)
        #
        self.to_q = nn.Linear(d_in, n_head*d_hidden, bias=False)
        self.to_k = nn.Linear(d_in, n_head*d_hidden, bias=False)
        self.to_v = nn.Linear(d_in, n_head*d_hidden, bias=False)
        self.to_b = nn.Linear(d_bias, n_head, bias=False)
        self.to_g = nn.Linear(d_in, n_head*d_hidden)
        self.to_out = nn.Linear(n_head*d_hidden, d_in)

        self.scaling = 1/math.sqrt(d_hidden)
        self.h = n_head
        self.dim = d_hidden

    #     self.reset_parameter()

    # def reset_parameter(self):
    #     # query/key/value projection: Glorot uniform / Xavier uniform
    #     nn.init.xavier_uniform_(self.to_q.weight)
    #     nn.init.xavier_uniform_(self.to_k.weight)
    #     nn.init.xavier_uniform_(self.to_v.weight)
        
    #     # bias: normal distribution
    #     self.to_b = init_lecun_normal(self.to_b)

    #     # gating: zero weights, one biases (mostly open gate at the begining)
    #     nn.init.zeros_(self.to_g.weight)
    #     nn.init.ones_(self.to_g.bias)

    #     # to_out: right before residual connection: zero initialize -- to make it sure residual operation is same to the Identity at the begining
    #     nn.init.zeros_(self.to_out.weight)
    #     nn.init.zeros_(self.to_out.bias)

    def forward(self, x, bias):
        B, L = x.shape[:2]
        #
        x = self.norm_in(x)
        bias = self.norm_bias(bias)
        #
        query = self.to_q(x).reshape(B, L, self.h, self.dim)
        key = self.to_k(x).reshape(B, L, self.h, self.dim)
        value = self.to_v(x).reshape(B, L, self.h, self.dim)
        bias = self.to_b(bias) # (B, L, L, h)
        gate = torch.sigmoid(self.to_g(x))
        #
        key = key * self.scaling
        attn = einsum('bqhd,bkhd->bqkh', query, key)
        attn = attn + bias
        attn = F.softmax(attn, dim=-2)
        #
        out = einsum('bqkh,bkhd->bqhd', attn, value).reshape(B, L, -1)
        out = gate * out
        #
        out = self.to_out(out)
        return out

# MSA Attention (row/column) from AlphaFold architecture
# class SequenceWeight(nn.Module):
#     def __init__(self, d_msa, n_head, d_hidden, p_drop=0.1):
#         super(SequenceWeight, self).__init__()
#         self.h = n_head
#         self.dim = d_hidden
#         self.scale = 1.0 / math.sqrt(self.dim)

#         self.to_query = nn.Linear(d_msa, n_head*d_hidden)
#         self.to_key = nn.Linear(d_msa, n_head*d_hidden)
#         self.dropout = nn.Dropout(p_drop)

#     #     self.reset_parameter()
    
#     # def reset_parameter(self):
#     #     # query/key/value projection: Glorot uniform / Xavier uniform
#     #     nn.init.xavier_uniform_(self.to_query.weight)
#     #     nn.init.xavier_uniform_(self.to_key.weight)

#     def forward(self, msa):
#         B, N, L = msa.shape[:3]
       
#         tar_seq = msa[:,0]
        
#         q = self.to_query(tar_seq).view(B, 1, L, self.h, self.dim)
#         k = self.to_key(msa).view(B, N, L, self.h, self.dim)
        
#         q = q * self.scale
#         attn = einsum('bqihd,bkihd->bkihq', q, k)
#         attn = F.softmax(attn, dim=1)
#         return self.dropout(attn)

class RowAttentionWithBias(nn.Module):
    def __init__(self, d_msa=256, d_pair=128, n_head=8, d_hidden=32):
        super().__init__()
        self.norm_msa = nn.LayerNorm(d_msa)
        self.norm_pair = nn.LayerNorm(d_pair)
        #
        # self.seq_weight = SequenceWeight(d_msa, n_head, d_hidden, p_drop=0.1)
        self.to_q = nn.Linear(d_msa, n_head*d_hidden, bias=False)
        self.to_k = nn.Linear(d_msa, n_head*d_hidden, bias=False)
        self.to_v = nn.Linear(d_msa, n_head*d_hidden, bias=False)
        self.to_b = nn.Linear(d_pair, n_head, bias=False)
        self.to_g = nn.Linear(d_msa, n_head*d_hidden)
        self.to_out = nn.Linear(n_head*d_hidden, d_msa)

        self.scaling = 1/math.sqrt(d_hidden)
        self.h = n_head
        self.dim = d_hidden

    def forward(self, msa, pair, mask = None): # TODO: make this as tied-attention
        B, L = msa.shape[:2]
        #
        msa = self.norm_msa(msa)
        pair = self.norm_pair(pair)
        #
        # seq_weight = self.seq_weight(msa) # (B, N, L, h, 1)
        query = self.to_q(msa).reshape(B, L, self.h, self.dim)  # (B, L, h, dim)
        key = self.to_k(msa).reshape(B, L, self.h, self.dim)
        value = self.to_v(msa).reshape(B, L, self.h, self.dim)
        bias = self.to_b(pair) # (B, L, L, h)
        gate = torch.sigmoid(self.to_g(msa))
        #
        # query = query * seq_weight.expand(-1, -1, -1, -1, self.dim)
        key = key * self.scaling
        attn = einsum('bqhd,bkhd->bqkh', query, key)  # (B, L, L, h)
        attn = attn + bias

        if mask is not None:
            mask_re = torch.matmul(mask.unsqueeze(2).type(torch.float32), mask.unsqueeze(1).type(torch.float32))[...,None]
            attn = attn * mask_re - 1e9 * (1-mask_re)

        attn = F.softmax(attn, dim=-2)
        #
        out = einsum('bqkh,bkhd->bqhd', attn, value).reshape(B, L, -1)
        out = gate * out
        #
        out = self.to_out(out)
        return out

class ColAttention(nn.Module):
    def __init__(self, d_msa=256, n_head=8, d_hidden=32):
        super().__init__()
        self.norm_msa = nn.LayerNorm(d_msa)
        #
        self.to_q = nn.Linear(d_msa, n_head*d_hidden, bias=False)
        self.to_k = nn.Linear(d_msa, n_head*d_hidden, bias=False)
        self.to_v = nn.Linear(d_msa, n_head*d_hidden, bias=False)
        self.to_g = nn.Linear(d_msa, n_head*d_hidden)
        self.to_out = nn.Linear(n_head*d_hidden, d_msa)

        self.scaling = 1/math.sqrt(d_hidden)
        self.h = n_head
        self.dim = d_hidden
        
    #     self.reset_parameter()

    # def reset_parameter(self):
    #     # query/key/value projection: Glorot uniform / Xavier uniform
    #     nn.init.xavier_uniform_(self.to_q.weight)
    #     nn.init.xavier_uniform_(self.to_k.weight)
    #     nn.init.xavier_uniform_(self.to_v.weight)

    #     # gating: zero weights, one biases (mostly open gate at the begining)
    #     nn.init.zeros_(self.to_g.weight)
    #     nn.init.ones_(self.to_g.bias)

    #     # to_out: right before residual connection: zero initialize -- to make it sure residual operation is same to the Identity at the begining
    #     nn.init.zeros_(self.to_out.weight)
    #     nn.init.zeros_(self.to_out.bias)

    def forward(self, msa, mask = None):
        '''

        msa (B,L,d_node)

        '''
        B, L = msa.shape[:2]
        #
        msa = self.norm_msa(msa)
        #
        query = self.to_q(msa).reshape(B, L, self.h, self.dim)  # (B,L,H,D)
        key = self.to_k(msa).reshape(B, L, self.h, self.dim)
        value = self.to_v(msa).reshape(B, L, self.h, self.dim)
        gate = torch.sigmoid(self.to_g(msa))
        #
        query = query * self.scaling
        attn = einsum('bqhd,bkhd->bqkh', query, key)  # (B,L,L,H)

        if mask is not None:
            mask_re = torch.matmul(mask.unsqueeze(2).type(torch.float32), mask.unsqueeze(1).type(torch.float32))[...,None]
            attn = attn * mask_re - 1e9 * (1-mask_re)

        attn = F.softmax(attn, dim=-3)  # (B,L,L,H)
        #
        out = einsum('bkqh,bkhd->bqhd', attn, value).reshape(B, L, -1)  # (B,L,H*D)
        out = gate * out
        #
        out = self.to_out(out)
        return out

# class MSAColGlobalAttention(nn.Module):
#     def __init__(self, d_msa=64, n_head=8, d_hidden=8):
#         super(MSAColGlobalAttention, self).__init__()
#         self.norm_msa = nn.LayerNorm(d_msa)
#         #
#         self.to_q = nn.Linear(d_msa, n_head*d_hidden, bias=False)
#         self.to_k = nn.Linear(d_msa, d_hidden, bias=False)
#         self.to_v = nn.Linear(d_msa, d_hidden, bias=False)
#         self.to_g = nn.Linear(d_msa, n_head*d_hidden)
#         self.to_out = nn.Linear(n_head*d_hidden, d_msa)

#         self.scaling = 1/math.sqrt(d_hidden)
#         self.h = n_head
#         self.dim = d_hidden
        
#         self.reset_parameter()

#     def reset_parameter(self):
#         # query/key/value projection: Glorot uniform / Xavier uniform
#         nn.init.xavier_uniform_(self.to_q.weight)
#         nn.init.xavier_uniform_(self.to_k.weight)
#         nn.init.xavier_uniform_(self.to_v.weight)

#         # gating: zero weights, one biases (mostly open gate at the begining)
#         nn.init.zeros_(self.to_g.weight)
#         nn.init.ones_(self.to_g.bias)

#         # to_out: right before residual connection: zero initialize -- to make it sure residual operation is same to the Identity at the begining
#         nn.init.zeros_(self.to_out.weight)
#         nn.init.zeros_(self.to_out.bias)

#     def forward(self, msa):
#         B, N, L = msa.shape[:3]
#         #
#         msa = self.norm_msa(msa)
#         #
#         query = self.to_q(msa).reshape(B, N, L, self.h, self.dim)
#         query = query.mean(dim=1) # (B, L, h, dim)
#         key = self.to_k(msa) # (B, N, L, dim)
#         value = self.to_v(msa) # (B, N, L, dim)
#         gate = torch.sigmoid(self.to_g(msa)) # (B, N, L, h*dim)
#         #
#         query = query * self.scaling
#         attn = einsum('bihd,bkid->bihk', query, key) # (B, L, h, N)
#         attn = F.softmax(attn, dim=-1)
#         #
#         out = einsum('bihk,bkid->bihd', attn, value).reshape(B, 1, L, -1) # (B, 1, L, h*dim)
#         out = gate * out # (B, N, L, h*dim)
#         #
#         out = self.to_out(out)
#         return out

# Instead of triangle attention, use Tied axail attention with bias from coordinates..?
class BiasedAxialAttention(nn.Module):
    def __init__(self, d_pair, d_bias, n_head, d_hidden, p_drop=0.1, is_row=True):
        super().__init__()
        #
        self.is_row = is_row
        self.norm_pair = nn.LayerNorm(d_pair)
        self.norm_bias = nn.LayerNorm(d_bias)

        self.to_q = nn.Linear(d_pair, n_head*d_hidden, bias=False)
        self.to_k = nn.Linear(d_pair, n_head*d_hidden, bias=False)
        self.to_v = nn.Linear(d_pair, n_head*d_hidden, bias=False)
        self.to_b = nn.Linear(d_bias, n_head, bias=False) 
        self.to_g = nn.Linear(d_pair, n_head*d_hidden)
        self.to_out = nn.Linear(n_head*d_hidden, d_pair)
        
        self.scaling = 1/math.sqrt(d_hidden)
        self.h = n_head
        self.dim = d_hidden

    def forward(self, pair, bias, mask = None):
        '''

        pair: (B, L, L, d_pair)

        mask: (B, L)

        '''

        B, L = pair.shape[:2]

        if self.is_row:
            pair = pair.permute(0,2,1,3)
            bias = bias.permute(0,2,1,3)

        pair = self.norm_pair(pair)
        bias = self.norm_bias(bias)
        
        query = self.to_q(pair).reshape(B, L, L, self.h, self.dim)  # (B, L, L, h, dim)
        key = self.to_k(pair).reshape(B, L, L, self.h, self.dim)
        value = self.to_v(pair).reshape(B, L, L, self.h, self.dim)
        bias = self.to_b(bias) # (B, L, L, h)
        gate = torch.sigmoid(self.to_g(pair)) # (B, L, L, h*dim) 
        
        query = query * self.scaling
        key = key / math.sqrt(L) # normalize for tied attention
        attn = einsum('bnihk,bnjhk->bijh', query, key) # tied attention (B, L, L, h)
        attn = attn + bias # apply bias
        if mask is not None:
            mask_temp = 1e-9 * (mask.type(torch.float) - 1)  # (B,L)
            attn = attn + mask_temp.unsqueeze(1).unsqueeze(-1)
            
        attn = F.softmax(attn, dim=-2) # (B, L, L, h)
        
        out = einsum('bijh,bkjhd->bikhd', attn, value).reshape(B, L, L, -1)  # (B, L, L, h*dim)
        out = gate * out
        
        out = self.to_out(out)
        if self.is_row:
            out = out.permute(0,2,1,3)
        return out