Spaces:
Runtime error

plastic0105 commited on
Commit
ba38b9a
·
verified ·
1 Parent(s): 50f12d1

Upload mint_repo/mint/model/esm2.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. mint_repo/mint/model/esm2.py +160 -0
mint_repo/mint/model/esm2.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from typing import Union
7
+
8
+ import torch
9
+ import torch.nn as nn
10
+
11
+ from ..data import Alphabet
12
+ from ..modules import ESM1bLayerNorm, RobertaLMHead, TransformerLayer
13
+
14
+
15
+ class ESM2(nn.Module):
16
+ def __init__(
17
+ self,
18
+ num_layers: int = 33,
19
+ embed_dim: int = 1280,
20
+ attention_heads: int = 20,
21
+ alphabet: Union[Alphabet, str] = "ESM-1b",
22
+ token_dropout: bool = True,
23
+ use_multimer: bool = False,
24
+ ):
25
+ super().__init__()
26
+ self.num_layers = num_layers
27
+ self.embed_dim = embed_dim
28
+ self.attention_heads = attention_heads
29
+ if not isinstance(alphabet, Alphabet):
30
+ alphabet = Alphabet.from_architecture(alphabet)
31
+ self.alphabet = alphabet
32
+ self.alphabet_size = len(alphabet)
33
+ self.padding_idx = alphabet.padding_idx
34
+ self.mask_idx = alphabet.mask_idx
35
+ self.cls_idx = alphabet.cls_idx
36
+ self.eos_idx = alphabet.eos_idx
37
+ self.prepend_bos = alphabet.prepend_bos
38
+ self.append_eos = alphabet.append_eos
39
+ self.token_dropout = token_dropout
40
+ self.use_multimer = use_multimer
41
+ self._init_submodules()
42
+
43
+ def _init_submodules(self):
44
+ self.embed_scale = 1
45
+ self.embed_tokens = nn.Embedding(
46
+ self.alphabet_size, self.embed_dim, padding_idx=self.padding_idx,
47
+ )
48
+
49
+ self.layers = nn.ModuleList(
50
+ [
51
+ TransformerLayer(
52
+ self.embed_dim,
53
+ 4 * self.embed_dim,
54
+ self.attention_heads,
55
+ add_bias_kv=False,
56
+ use_esm1b_layer_norm=True,
57
+ use_rotary_embeddings=True,
58
+ use_multimer=self.use_multimer,
59
+ )
60
+ for _ in range(self.num_layers)
61
+ ]
62
+ )
63
+
64
+ # self.contact_head = ContactPredictionHead(
65
+ # self.num_layers * self.attention_heads,
66
+ # self.prepend_bos,
67
+ # self.append_eos,
68
+ # eos_idx=self.eos_idx,
69
+ # )
70
+ self.emb_layer_norm_after = ESM1bLayerNorm(self.embed_dim)
71
+
72
+ self.lm_head = RobertaLMHead(
73
+ embed_dim=self.embed_dim,
74
+ output_dim=self.alphabet_size,
75
+ weight=self.embed_tokens.weight,
76
+ )
77
+
78
+ def forward(
79
+ self,
80
+ tokens,
81
+ chain_ids=None,
82
+ repr_layers=[],
83
+ need_head_weights=False,
84
+ return_contacts=False,
85
+ ):
86
+ if return_contacts:
87
+ need_head_weights = True
88
+
89
+ assert tokens.ndim == 2
90
+ padding_mask = tokens.eq(self.padding_idx) # B, T
91
+
92
+ if chain_ids is None:
93
+ chain_ids = torch.zeros_like(tokens)
94
+ self_attn_mask = ~torch.eq(chain_ids.unsqueeze(-1), chain_ids.unsqueeze(-2)) # B, T, T
95
+
96
+ x = self.embed_scale * self.embed_tokens(tokens)
97
+
98
+ if self.token_dropout:
99
+ x.masked_fill_((tokens == self.mask_idx).unsqueeze(-1), 0.0)
100
+ # x: B x T x C
101
+ mask_ratio_train = 0.15 * 0.8
102
+ src_lengths = (~padding_mask).sum(-1)
103
+ mask_ratio_observed = (tokens == self.mask_idx).sum(-1).to(x.dtype) / src_lengths
104
+ x = x * (1 - mask_ratio_train) / (1 - mask_ratio_observed)[:, None, None]
105
+
106
+ if padding_mask is not None:
107
+ x = x * (1 - padding_mask.unsqueeze(-1).type_as(x))
108
+
109
+ repr_layers = set(repr_layers)
110
+ hidden_representations = {}
111
+ if 0 in repr_layers:
112
+ hidden_representations[0] = x
113
+
114
+ if need_head_weights:
115
+ attn_weights = []
116
+
117
+ # (B, T, E) => (T, B, E)
118
+ x = x.transpose(0, 1)
119
+
120
+ if not padding_mask.any():
121
+ padding_mask = None
122
+
123
+ for layer_idx, layer in enumerate(self.layers):
124
+ x, attn = layer(
125
+ x,
126
+ self_attn_padding_mask=padding_mask,
127
+ need_head_weights=need_head_weights,
128
+ self_attn_mask=self_attn_mask,
129
+ )
130
+ if (layer_idx + 1) in repr_layers:
131
+ hidden_representations[layer_idx + 1] = x.transpose(0, 1)
132
+ if need_head_weights:
133
+ # (H, B, T, T) => (B, H, T, T)
134
+ attn_weights.append(attn.transpose(1, 0))
135
+
136
+ x = self.emb_layer_norm_after(x)
137
+ x = x.transpose(0, 1) # (T, B, E) => (B, T, E)
138
+
139
+ # last hidden representation should have layer norm applied
140
+ if (layer_idx + 1) in repr_layers:
141
+ hidden_representations[layer_idx + 1] = x
142
+ x = self.lm_head(x)
143
+
144
+ result = {"logits": x, "representations": hidden_representations}
145
+ if need_head_weights:
146
+ # attentions: B x L x H x T x T
147
+ attentions = torch.stack(attn_weights, 1)
148
+ if padding_mask is not None:
149
+ attention_mask = 1 - padding_mask.type_as(attentions)
150
+ attention_mask = attention_mask.unsqueeze(1) * attention_mask.unsqueeze(2)
151
+ attentions = attentions * attention_mask[:, None, None, :, :]
152
+ result["attentions"] = attentions
153
+ if return_contacts:
154
+ contacts = self.contact_head(tokens, attentions)
155
+ result["contacts"] = contacts
156
+
157
+ return result
158
+
159
+ def predict_contacts(self, tokens):
160
+ return self(tokens, return_contacts=True)["contacts"]