Spaces:
Runtime error

plastic0105 commited on
Commit
26dd822
·
verified ·
1 Parent(s): ba38b9a

Upload mint_repo/mint/modules.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. mint_repo/mint/modules.py +450 -0
mint_repo/mint/modules.py ADDED
@@ -0,0 +1,450 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ import math
7
+ from typing import Optional
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ import torch.nn.functional as F
12
+
13
+ from .axial_attention import ColumnSelfAttention, RowSelfAttention
14
+ from .multihead_attention import MultiheadAttention # noqa
15
+
16
+
17
+ def gelu(x):
18
+ """Implementation of the gelu activation function.
19
+
20
+ For information: OpenAI GPT's gelu is slightly different
21
+ (and gives slightly different results):
22
+ 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3))))
23
+ """
24
+ return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0)))
25
+
26
+
27
+ def symmetrize(x):
28
+ "Make layer symmetric in final two dimensions, used for contact prediction."
29
+ return x + x.transpose(-1, -2)
30
+
31
+
32
+ def apc(x):
33
+ "Perform average product correct, used for contact prediction."
34
+ a1 = x.sum(-1, keepdims=True)
35
+ a2 = x.sum(-2, keepdims=True)
36
+ a12 = x.sum((-1, -2), keepdims=True)
37
+
38
+ avg = a1 * a2
39
+ avg.div_(a12) # in-place to reduce memory
40
+ normalized = x - avg
41
+ return normalized
42
+
43
+
44
+ class ESM1LayerNorm(nn.Module):
45
+ def __init__(self, hidden_size, eps=1e-12, affine=True):
46
+ """Construct a layernorm layer in the TF style (eps inside the sqrt)."""
47
+ super().__init__()
48
+ self.hidden_size = (hidden_size,) if isinstance(hidden_size, int) else tuple(hidden_size)
49
+ self.eps = eps
50
+ self.affine = bool(affine)
51
+ if self.affine:
52
+ self.weight = nn.Parameter(torch.ones(hidden_size))
53
+ self.bias = nn.Parameter(torch.zeros(hidden_size))
54
+ else:
55
+ self.weight, self.bias = None, None
56
+
57
+ def forward(self, x):
58
+ dims = tuple(-(i + 1) for i in range(len(self.hidden_size)))
59
+ means = x.mean(dims, keepdim=True)
60
+ x_zeromean = x - means
61
+ variances = x_zeromean.pow(2).mean(dims, keepdim=True)
62
+ x = x_zeromean / torch.sqrt(variances + self.eps)
63
+ if self.affine:
64
+ x = (self.weight * x) + self.bias
65
+ return x
66
+
67
+
68
+ try:
69
+ from apex.normalization import FusedLayerNorm as _FusedLayerNorm
70
+
71
+ class ESM1bLayerNorm(_FusedLayerNorm):
72
+ @torch.jit.unused
73
+ def forward(self, x):
74
+ if not x.is_cuda:
75
+ return super().forward(x)
76
+ else:
77
+ with torch.cuda.device(x.device):
78
+ return super().forward(x)
79
+
80
+
81
+ except ImportError:
82
+ from torch.nn import LayerNorm as ESM1bLayerNorm
83
+
84
+
85
+ class TransformerLayer(nn.Module):
86
+ """Transformer layer block."""
87
+
88
+ def __init__(
89
+ self,
90
+ embed_dim,
91
+ ffn_embed_dim,
92
+ attention_heads,
93
+ add_bias_kv=True,
94
+ use_esm1b_layer_norm=False,
95
+ use_rotary_embeddings: bool = False,
96
+ use_multimer=False,
97
+ ):
98
+ super().__init__()
99
+ self.embed_dim = embed_dim
100
+ self.ffn_embed_dim = ffn_embed_dim
101
+ self.attention_heads = attention_heads
102
+ self.use_rotary_embeddings = use_rotary_embeddings
103
+ self.use_multimer = use_multimer
104
+ self._init_submodules(add_bias_kv, use_esm1b_layer_norm)
105
+
106
+ def _init_submodules(self, add_bias_kv, use_esm1b_layer_norm):
107
+ BertLayerNorm = ESM1bLayerNorm if use_esm1b_layer_norm else ESM1LayerNorm
108
+
109
+ self.self_attn = MultiheadAttention(
110
+ self.embed_dim,
111
+ self.attention_heads,
112
+ add_bias_kv=add_bias_kv,
113
+ add_zero_attn=False,
114
+ use_rotary_embeddings=self.use_rotary_embeddings,
115
+ )
116
+
117
+ if self.use_multimer:
118
+ self.multimer_attn = MultiheadAttention(
119
+ self.embed_dim,
120
+ self.attention_heads,
121
+ add_bias_kv=add_bias_kv,
122
+ add_zero_attn=False,
123
+ use_rotary_embeddings=False,
124
+ no_proj=True,
125
+ )
126
+
127
+ self.self_attn_layer_norm = BertLayerNorm(self.embed_dim)
128
+
129
+ self.fc1 = nn.Linear(self.embed_dim, self.ffn_embed_dim)
130
+ self.fc2 = nn.Linear(self.ffn_embed_dim, self.embed_dim)
131
+
132
+ self.final_layer_norm = BertLayerNorm(self.embed_dim)
133
+
134
+ def forward(
135
+ self, x, self_attn_mask=None, self_attn_padding_mask=None, need_head_weights=False
136
+ ):
137
+ residual = x
138
+ x = self.self_attn_layer_norm(x)
139
+ if self.use_multimer:
140
+ self_attn, self_v = self.self_attn(
141
+ query=x,
142
+ key=x,
143
+ value=x,
144
+ key_padding_mask=self_attn_padding_mask,
145
+ before_softmax=True,
146
+ )
147
+ multimer_attn, multimer_v = self.multimer_attn(
148
+ query=x,
149
+ key=x,
150
+ value=x,
151
+ key_padding_mask=self_attn_padding_mask,
152
+ before_softmax=True,
153
+ )
154
+ attn_weights = torch.where(self_attn_mask.unsqueeze(1), multimer_attn, self_attn)
155
+ attn_probs = F.softmax(attn_weights, dim=-1, dtype=torch.float32).type_as(attn_weights)
156
+ attn_probs_dropout = F.dropout(
157
+ attn_probs, p=self.self_attn.dropout, training=self.training
158
+ )
159
+ self_attn_probs = attn_probs_dropout.masked_fill(self_attn_mask.unsqueeze(1), 0.0)
160
+ multimer_attn_probs = attn_probs_dropout.masked_fill(~self_attn_mask.unsqueeze(1), 0.0)
161
+ attn_out = torch.matmul(self_attn_probs, self_v) + torch.matmul(
162
+ multimer_attn_probs, multimer_v
163
+ )
164
+
165
+ attn_out = attn_out.transpose(1, 2).contiguous()
166
+ attn_out = attn_out.view(*attn_out.shape[:2], -1)
167
+ x = self.self_attn.out_proj(attn_out).transpose(0, 1).contiguous()
168
+ if need_head_weights:
169
+ attn = attn_probs.transpose(0, 1).contiguous()
170
+ else:
171
+ attn = attn_probs.mean(1)
172
+ else:
173
+ x, attn = self.self_attn(
174
+ query=x,
175
+ key=x,
176
+ value=x,
177
+ key_padding_mask=self_attn_padding_mask,
178
+ need_weights=True,
179
+ need_head_weights=need_head_weights,
180
+ attn_mask=self_attn_mask,
181
+ )
182
+ x = residual + x
183
+
184
+ residual = x
185
+ x = self.final_layer_norm(x)
186
+ x = gelu(self.fc1(x))
187
+ x = self.fc2(x)
188
+ x = residual + x
189
+ return x, attn
190
+
191
+
192
+ class AxialTransformerLayer(nn.Module):
193
+ """Implements an Axial MSA Transformer block."""
194
+
195
+ def __init__(
196
+ self,
197
+ embedding_dim: int = 768,
198
+ ffn_embedding_dim: int = 3072,
199
+ num_attention_heads: int = 8,
200
+ dropout: float = 0.1,
201
+ attention_dropout: float = 0.1,
202
+ activation_dropout: float = 0.1,
203
+ max_tokens_per_msa: int = 2 ** 14,
204
+ ) -> None:
205
+ super().__init__()
206
+
207
+ # Initialize parameters
208
+ self.embedding_dim = embedding_dim
209
+ self.dropout_prob = dropout
210
+
211
+ row_self_attention = RowSelfAttention(
212
+ embedding_dim,
213
+ num_attention_heads,
214
+ dropout=dropout,
215
+ max_tokens_per_msa=max_tokens_per_msa,
216
+ )
217
+
218
+ column_self_attention = ColumnSelfAttention(
219
+ embedding_dim,
220
+ num_attention_heads,
221
+ dropout=dropout,
222
+ max_tokens_per_msa=max_tokens_per_msa,
223
+ )
224
+
225
+ feed_forward_layer = FeedForwardNetwork(
226
+ embedding_dim,
227
+ ffn_embedding_dim,
228
+ activation_dropout=activation_dropout,
229
+ max_tokens_per_msa=max_tokens_per_msa,
230
+ )
231
+
232
+ self.row_self_attention = self.build_residual(row_self_attention)
233
+ self.column_self_attention = self.build_residual(column_self_attention)
234
+ self.feed_forward_layer = self.build_residual(feed_forward_layer)
235
+
236
+ def build_residual(self, layer: nn.Module):
237
+ return NormalizedResidualBlock(layer, self.embedding_dim, self.dropout_prob,)
238
+
239
+ def forward(
240
+ self,
241
+ x: torch.Tensor,
242
+ self_attn_mask: Optional[torch.Tensor] = None,
243
+ self_attn_padding_mask: Optional[torch.Tensor] = None,
244
+ need_head_weights: bool = False,
245
+ ):
246
+ """
247
+ LayerNorm is applied either before or after the self-attention/ffn
248
+ modules similar to the original Transformer implementation.
249
+ """
250
+ x, row_attn = self.row_self_attention(
251
+ x, self_attn_mask=self_attn_mask, self_attn_padding_mask=self_attn_padding_mask,
252
+ )
253
+ x, column_attn = self.column_self_attention(
254
+ x, self_attn_mask=self_attn_mask, self_attn_padding_mask=self_attn_padding_mask,
255
+ )
256
+ x = self.feed_forward_layer(x)
257
+ if need_head_weights:
258
+ return x, column_attn, row_attn
259
+ else:
260
+ return x
261
+
262
+
263
+ class LearnedPositionalEmbedding(nn.Embedding):
264
+ """
265
+ This module learns positional embeddings up to a fixed maximum size.
266
+ Padding ids are ignored by either offsetting based on padding_idx
267
+ or by setting padding_idx to None and ensuring that the appropriate
268
+ position ids are passed to the forward function.
269
+ """
270
+
271
+ def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int):
272
+ if padding_idx is not None:
273
+ num_embeddings_ = num_embeddings + padding_idx + 1
274
+ else:
275
+ num_embeddings_ = num_embeddings
276
+ super().__init__(num_embeddings_, embedding_dim, padding_idx)
277
+ self.max_positions = num_embeddings
278
+
279
+ def forward(self, input: torch.Tensor):
280
+ """Input is expected to be of size [bsz x seqlen]."""
281
+ if input.size(1) > self.max_positions:
282
+ raise ValueError(
283
+ f"Sequence length {input.size(1)} above maximum "
284
+ f" sequence length of {self.max_positions}"
285
+ )
286
+ mask = input.ne(self.padding_idx).int()
287
+ positions = (torch.cumsum(mask, dim=1).type_as(mask) * mask).long() + self.padding_idx
288
+ return F.embedding(
289
+ positions,
290
+ self.weight,
291
+ self.padding_idx,
292
+ self.max_norm,
293
+ self.norm_type,
294
+ self.scale_grad_by_freq,
295
+ self.sparse,
296
+ )
297
+
298
+
299
+ class SinusoidalPositionalEmbedding(nn.Module):
300
+ def __init__(self, embed_dim, padding_idx, learned=False):
301
+ super().__init__()
302
+ self.embed_dim = embed_dim
303
+ self.padding_idx = padding_idx
304
+ self.register_buffer("_float_tensor", torch.FloatTensor(1))
305
+ self.weights = None
306
+
307
+ def forward(self, x):
308
+ bsz, seq_len = x.shape
309
+ max_pos = self.padding_idx + 1 + seq_len
310
+ if self.weights is None or max_pos > self.weights.size(0):
311
+ self.weights = self.get_embedding(max_pos)
312
+ self.weights = self.weights.type_as(self._float_tensor)
313
+
314
+ positions = self.make_positions(x)
315
+ return self.weights.index_select(0, positions.view(-1)).view(bsz, seq_len, -1).detach()
316
+
317
+ def make_positions(self, x):
318
+ mask = x.ne(self.padding_idx)
319
+ range_buf = torch.arange(x.size(1), device=x.device).expand_as(x) + self.padding_idx + 1
320
+ positions = range_buf.expand_as(x)
321
+ return positions * mask.long() + self.padding_idx * (1 - mask.long())
322
+
323
+ def get_embedding(self, num_embeddings):
324
+ half_dim = self.embed_dim // 2
325
+ emb = math.log(10000) / (half_dim - 1)
326
+ emb = torch.exp(torch.arange(half_dim, dtype=torch.float) * -emb)
327
+ emb = torch.arange(num_embeddings, dtype=torch.float).unsqueeze(1) * emb.unsqueeze(0)
328
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1).view(num_embeddings, -1)
329
+ if self.embed_dim % 2 == 1:
330
+ # zero pad
331
+ emb = torch.cat([emb, torch.zeros(num_embeddings, 1)], dim=1)
332
+ if self.padding_idx is not None:
333
+ emb[self.padding_idx, :] = 0
334
+ return emb
335
+
336
+
337
+ class RobertaLMHead(nn.Module):
338
+ """Head for masked language modeling."""
339
+
340
+ def __init__(self, embed_dim, output_dim, weight):
341
+ super().__init__()
342
+ self.dense = nn.Linear(embed_dim, embed_dim)
343
+ self.layer_norm = ESM1bLayerNorm(embed_dim)
344
+ self.weight = weight
345
+ self.bias = nn.Parameter(torch.zeros(output_dim))
346
+
347
+ def forward(self, features):
348
+ x = self.dense(features)
349
+ x = gelu(x)
350
+ x = self.layer_norm(x)
351
+ # project back to size of vocabulary with bias
352
+ x = F.linear(x, self.weight) + self.bias
353
+ return x
354
+
355
+
356
+ class ContactPredictionHead(nn.Module):
357
+ """Performs symmetrization, apc, and computes a logistic regression on the output features"""
358
+
359
+ def __init__(
360
+ self,
361
+ in_features: int,
362
+ prepend_bos: bool,
363
+ append_eos: bool,
364
+ bias=True,
365
+ eos_idx: Optional[int] = None,
366
+ ):
367
+ super().__init__()
368
+ self.in_features = in_features
369
+ self.prepend_bos = prepend_bos
370
+ self.append_eos = append_eos
371
+ if append_eos and eos_idx is None:
372
+ raise ValueError("Using an alphabet with eos token, but no eos token was passed in.")
373
+ self.eos_idx = eos_idx
374
+ self.regression = nn.Linear(in_features, 1, bias)
375
+ self.activation = nn.Sigmoid()
376
+
377
+ def forward(self, tokens, attentions):
378
+ # remove eos token attentions
379
+ if self.append_eos:
380
+ eos_mask = tokens.ne(self.eos_idx).to(attentions)
381
+ eos_mask = eos_mask.unsqueeze(1) * eos_mask.unsqueeze(2)
382
+ attentions = attentions * eos_mask[:, None, None, :, :]
383
+ attentions = attentions[..., :-1, :-1]
384
+ # remove cls token attentions
385
+ if self.prepend_bos:
386
+ attentions = attentions[..., 1:, 1:]
387
+ batch_size, layers, heads, seqlen, _ = attentions.size()
388
+ attentions = attentions.view(batch_size, layers * heads, seqlen, seqlen)
389
+
390
+ # features: B x C x T x T
391
+ attentions = attentions.to(
392
+ self.regression.weight.device
393
+ ) # attentions always float32, may need to convert to float16
394
+ attentions = apc(symmetrize(attentions))
395
+ attentions = attentions.permute(0, 2, 3, 1)
396
+ return self.activation(self.regression(attentions).squeeze(3))
397
+
398
+
399
+ class NormalizedResidualBlock(nn.Module):
400
+ def __init__(
401
+ self, layer: nn.Module, embedding_dim: int, dropout: float = 0.1,
402
+ ):
403
+ super().__init__()
404
+ self.embedding_dim = embedding_dim
405
+
406
+ self.layer = layer
407
+ self.dropout_module = nn.Dropout(dropout,)
408
+ self.layer_norm = ESM1bLayerNorm(self.embedding_dim)
409
+
410
+ def forward(self, x, *args, **kwargs):
411
+ residual = x
412
+ x = self.layer_norm(x)
413
+ outputs = self.layer(x, *args, **kwargs)
414
+ if isinstance(outputs, tuple):
415
+ x, *out = outputs
416
+ else:
417
+ x = outputs
418
+ out = None
419
+
420
+ x = self.dropout_module(x)
421
+ x = residual + x
422
+
423
+ if out is not None:
424
+ return (x,) + tuple(out)
425
+ else:
426
+ return x
427
+
428
+
429
+ class FeedForwardNetwork(nn.Module):
430
+ def __init__(
431
+ self,
432
+ embedding_dim: int,
433
+ ffn_embedding_dim: int,
434
+ activation_dropout: float = 0.1,
435
+ max_tokens_per_msa: int = 2 ** 14,
436
+ ):
437
+ super().__init__()
438
+ self.embedding_dim = embedding_dim
439
+ self.ffn_embedding_dim = ffn_embedding_dim
440
+ self.max_tokens_per_msa = max_tokens_per_msa
441
+ self.activation_fn = nn.GELU()
442
+ self.activation_dropout_module = nn.Dropout(activation_dropout,)
443
+ self.fc1 = nn.Linear(embedding_dim, ffn_embedding_dim)
444
+ self.fc2 = nn.Linear(ffn_embedding_dim, embedding_dim)
445
+
446
+ def forward(self, x):
447
+ x = self.activation_fn(self.fc1(x))
448
+ x = self.activation_dropout_module(x)
449
+ x = self.fc2(x)
450
+ return x