gravelcompbio commited on
Commit
0455452
1 Parent(s): 55e7c7d

Upload 3 files

Browse files
Files changed (3) hide show
  1. configuration_esm.py +370 -0
  2. modeling_esm.py +1595 -0
  3. tokenization_esm.py +142 -0
configuration_esm.py ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 Meta and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """ ESM model configuration"""
16
+
17
+ from dataclasses import asdict, dataclass
18
+ from typing import Optional
19
+
20
+ from transformers.configuration_utils import PretrainedConfig
21
+ from transformers.utils import logging
22
+
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+ # TODO Update this
27
+ ESM_PRETRAINED_CONFIG_ARCHIVE_MAP = {
28
+ "facebook/esm-1b": "https://huggingface.co/facebook/esm-1b/resolve/main/config.json",
29
+ # See all ESM models at https://huggingface.co/models?filter=esm
30
+ }
31
+
32
+
33
+ class EsmConfig(PretrainedConfig):
34
+ r"""
35
+ This is the configuration class to store the configuration of a [`ESMModel`]. It is used to instantiate a ESM model
36
+ according to the specified arguments, defining the model architecture. Instantiating a configuration with the
37
+ defaults will yield a similar configuration to that of the ESM
38
+ [facebook/esm-1b](https://huggingface.co/facebook/esm-1b) architecture.
39
+
40
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
41
+ documentation from [`PretrainedConfig`] for more information.
42
+
43
+
44
+ Args:
45
+ vocab_size (`int`, *optional*):
46
+ Vocabulary size of the ESM model. Defines the number of different tokens that can be represented by the
47
+ `inputs_ids` passed when calling [`ESMModel`].
48
+ mask_token_id (`int`, *optional*):
49
+ The index of the mask token in the vocabulary. This must be included in the config because of the
50
+ "mask-dropout" scaling trick, which will scale the inputs depending on the number of masked tokens.
51
+ pad_token_id (`int`, *optional*):
52
+ The index of the padding token in the vocabulary. This must be included in the config because certain parts
53
+ of the ESM code use this instead of the attention mask.
54
+ hidden_size (`int`, *optional*, defaults to 768):
55
+ Dimensionality of the encoder layers and the pooler layer.
56
+ num_hidden_layers (`int`, *optional*, defaults to 12):
57
+ Number of hidden layers in the Transformer encoder.
58
+ num_attention_heads (`int`, *optional*, defaults to 12):
59
+ Number of attention heads for each attention layer in the Transformer encoder.
60
+ intermediate_size (`int`, *optional*, defaults to 3072):
61
+ Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
62
+ hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
63
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
64
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
65
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
66
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
67
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
68
+ The dropout ratio for the attention probabilities.
69
+ max_position_embeddings (`int`, *optional*, defaults to 1026):
70
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
71
+ just in case (e.g., 512 or 1024 or 2048).
72
+ initializer_range (`float`, *optional*, defaults to 0.02):
73
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
74
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
75
+ The epsilon used by the layer normalization layers.
76
+ position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
77
+ Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query", "rotary"`.
78
+ For positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
79
+ [Self-Attention with Relative Position Representations (Shaw et al.)](https://arxiv.org/abs/1803.02155).
80
+ For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
81
+ with Better Relative Position Embeddings (Huang et al.)](https://arxiv.org/abs/2009.13658).
82
+ use_cache (`bool`, *optional*, defaults to `True`):
83
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
84
+ relevant if `config.is_decoder=True`.
85
+ classifier_dropout (`float`, *optional*):
86
+ The dropout ratio for the classification head.
87
+ emb_layer_norm_before (`bool`, *optional*):
88
+ Whether to apply layer normalization after embeddings but before the main stem of the network.
89
+ token_dropout (`bool`, defaults to `False`):
90
+ When this is enabled, masked tokens are treated as if they had been dropped out by input dropout.
91
+
92
+ Examples:
93
+
94
+ ```python
95
+ >>> from transformers import EsmModel, EsmConfig
96
+
97
+ >>> # Initializing a ESM facebook/esm-1b style configuration >>> configuration = EsmConfig()
98
+
99
+ >>> # Initializing a model from the configuration >>> model = ESMModel(configuration)
100
+
101
+ >>> # Accessing the model configuration >>> configuration = model.config
102
+ ```"""
103
+ model_type = "esm"
104
+
105
+ def __init__(
106
+ self,
107
+ vocab_size=None,
108
+ mask_token_id=None,
109
+ pad_token_id=None,
110
+ hidden_size=768,
111
+ num_hidden_layers=12,
112
+ num_attention_heads=12,
113
+ intermediate_size=3072,
114
+ hidden_act="gelu",
115
+ hidden_dropout_prob=0.1,
116
+ attention_probs_dropout_prob=0.1,
117
+ max_position_embeddings=1026,
118
+ initializer_range=0.02,
119
+ layer_norm_eps=1e-12,
120
+ position_embedding_type="absolute",
121
+ use_cache=True,
122
+ classifier_dropout=None,
123
+ emb_layer_norm_before=None,
124
+ token_dropout=False,
125
+ is_folding_model=False,
126
+ esmfold_config=None,
127
+ vocab_list=None,
128
+ **kwargs
129
+ ):
130
+ super().__init__(pad_token_id=pad_token_id, mask_token_id=mask_token_id, **kwargs)
131
+
132
+ self.vocab_size = vocab_size
133
+ self.hidden_size = hidden_size
134
+ self.num_hidden_layers = num_hidden_layers
135
+ self.num_attention_heads = num_attention_heads
136
+ self.hidden_act = hidden_act
137
+ self.intermediate_size = intermediate_size
138
+ self.hidden_dropout_prob = hidden_dropout_prob
139
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
140
+ self.max_position_embeddings = max_position_embeddings
141
+ self.initializer_range = initializer_range
142
+ self.layer_norm_eps = layer_norm_eps
143
+ self.position_embedding_type = position_embedding_type
144
+ self.use_cache = use_cache
145
+ self.classifier_dropout = classifier_dropout
146
+ self.emb_layer_norm_before = emb_layer_norm_before
147
+ self.token_dropout = token_dropout
148
+ self.is_folding_model = is_folding_model
149
+ if is_folding_model:
150
+ if esmfold_config is None:
151
+ logger.info("No esmfold_config supplied for folding model, using default values.")
152
+ esmfold_config = EsmFoldConfig()
153
+ elif isinstance(esmfold_config, dict):
154
+ esmfold_config = EsmFoldConfig(**esmfold_config)
155
+ self.esmfold_config = esmfold_config
156
+ if vocab_list is None:
157
+ logger.warning("No vocab_list supplied for folding model, assuming the ESM-2 vocabulary!")
158
+ self.vocab_list = get_default_vocab_list()
159
+ else:
160
+ self.vocab_list = vocab_list
161
+ else:
162
+ self.esmfold_config = None
163
+ self.vocab_list = None
164
+ if self.esmfold_config is not None and getattr(self.esmfold_config, "use_esm_attn_map", False):
165
+ raise ValueError("The HuggingFace port of ESMFold does not support use_esm_attn_map at this time!")
166
+
167
+ def to_dict(self):
168
+ """
169
+ Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].
170
+
171
+ Returns:
172
+ `Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
173
+ """
174
+ output = super().to_dict()
175
+ if isinstance(self.esmfold_config, EsmFoldConfig):
176
+ output["esmfold_config"] = self.esmfold_config.to_dict()
177
+ return output
178
+
179
+
180
+ @dataclass
181
+ class EsmFoldConfig:
182
+ esm_type: str = None
183
+ fp16_esm: bool = True
184
+ use_esm_attn_map: bool = False
185
+ esm_ablate_pairwise: bool = False
186
+ esm_ablate_sequence: bool = False
187
+ esm_input_dropout: float = 0
188
+
189
+ embed_aa: bool = True
190
+ bypass_lm: bool = False
191
+
192
+ lddt_head_hid_dim: int = 128
193
+ trunk: "TrunkConfig" = None
194
+
195
+ def __post_init__(self):
196
+ if self.trunk is None:
197
+ self.trunk = TrunkConfig()
198
+ elif isinstance(self.trunk, dict):
199
+ self.trunk = TrunkConfig(**self.trunk)
200
+
201
+ def to_dict(self):
202
+ """
203
+ Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].
204
+
205
+ Returns:
206
+ `Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
207
+ """
208
+ output = asdict(self)
209
+ output["trunk"] = self.trunk.to_dict()
210
+ return output
211
+
212
+
213
+ @dataclass
214
+ class TrunkConfig:
215
+ num_blocks: int = 48
216
+ sequence_state_dim: int = 1024
217
+ pairwise_state_dim: int = 128
218
+ sequence_head_width: int = 32
219
+ pairwise_head_width: int = 32
220
+ position_bins: int = 32
221
+ dropout: float = 0
222
+ layer_drop: float = 0
223
+ cpu_grad_checkpoint: bool = False
224
+ max_recycles: int = 4
225
+ chunk_size: Optional[int] = 128
226
+ structure_module: "StructureModuleConfig" = None
227
+
228
+ def __post_init__(self):
229
+ if self.structure_module is None:
230
+ self.structure_module = StructureModuleConfig()
231
+ elif isinstance(self.structure_module, dict):
232
+ self.structure_module = StructureModuleConfig(**self.structure_module)
233
+
234
+ if self.max_recycles <= 0:
235
+ raise ValueError(f"`max_recycles` should be positive, got {self.max_recycles}.")
236
+ if self.sequence_state_dim % self.sequence_state_dim != 0:
237
+ raise ValueError(
238
+ "`sequence_state_dim` should be a round multiple of `sequence_state_dim`, got"
239
+ f" {self.sequence_state_dim} and {self.sequence_state_dim}."
240
+ )
241
+ if self.pairwise_state_dim % self.pairwise_state_dim != 0:
242
+ raise ValueError(
243
+ "`pairwise_state_dim` should be a round multiple of `pairwise_state_dim`, got"
244
+ f" {self.pairwise_state_dim} and {self.pairwise_state_dim}."
245
+ )
246
+
247
+ sequence_num_heads = self.sequence_state_dim // self.sequence_head_width
248
+ pairwise_num_heads = self.pairwise_state_dim // self.pairwise_head_width
249
+
250
+ if self.sequence_state_dim != sequence_num_heads * self.sequence_head_width:
251
+ raise ValueError(
252
+ "`sequence_state_dim` should be equal to `sequence_num_heads * sequence_head_width, got"
253
+ f" {self.sequence_state_dim} != {sequence_num_heads} * {self.sequence_head_width}."
254
+ )
255
+ if self.pairwise_state_dim != pairwise_num_heads * self.pairwise_head_width:
256
+ raise ValueError(
257
+ "`pairwise_state_dim` should be equal to `pairwise_num_heads * pairwise_head_width, got"
258
+ f" {self.pairwise_state_dim} != {pairwise_num_heads} * {self.pairwise_head_width}."
259
+ )
260
+ if self.pairwise_state_dim % 2 != 0:
261
+ raise ValueError(f"`pairwise_state_dim` should be even, got {self.pairwise_state_dim}.")
262
+
263
+ if self.dropout >= 0.4:
264
+ raise ValueError(f"`dropout` should not be greater than 0.4, got {self.dropout}.")
265
+
266
+ def to_dict(self):
267
+ """
268
+ Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].
269
+
270
+ Returns:
271
+ `Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
272
+ """
273
+ output = asdict(self)
274
+ output["structure_module"] = self.structure_module.to_dict()
275
+ return output
276
+
277
+
278
+ @dataclass
279
+ class StructureModuleConfig:
280
+ """
281
+ Args:
282
+ sequence_dim:
283
+ Single representation channel dimension
284
+ pairwise_dim:
285
+ Pair representation channel dimension
286
+ ipa_dim:
287
+ IPA hidden channel dimension
288
+ resnet_dim:
289
+ Angle resnet (Alg. 23 lines 11-14) hidden channel dimension
290
+ num_heads_ipa:
291
+ Number of IPA heads
292
+ num_qk_points:
293
+ Number of query/key points to generate during IPA
294
+ num_v_points:
295
+ Number of value points to generate during IPA
296
+ dropout_rate:
297
+ Dropout rate used throughout the layer
298
+ num_blocks:
299
+ Number of structure module blocks
300
+ num_transition_layers:
301
+ Number of layers in the single representation transition (Alg. 23 lines 8-9)
302
+ num_resnet_blocks:
303
+ Number of blocks in the angle resnet
304
+ num_angles:
305
+ Number of angles to generate in the angle resnet
306
+ trans_scale_factor:
307
+ Scale of single representation transition hidden dimension
308
+ epsilon:
309
+ Small number used in angle resnet normalization
310
+ inf:
311
+ Large number used for attention masking
312
+ """
313
+
314
+ sequence_dim: int = 384
315
+ pairwise_dim: int = 128
316
+ ipa_dim: int = 16
317
+ resnet_dim: int = 128
318
+ num_heads_ipa: int = 12
319
+ num_qk_points: int = 4
320
+ num_v_points: int = 8
321
+ dropout_rate: float = 0.1
322
+ num_blocks: int = 8
323
+ num_transition_layers: int = 1
324
+ num_resnet_blocks: int = 2
325
+ num_angles: int = 7
326
+ trans_scale_factor: int = 10
327
+ epsilon: float = 1e-8
328
+ inf: float = 1e5
329
+
330
+ def to_dict(self):
331
+ return asdict(self)
332
+
333
+
334
+ def get_default_vocab_list():
335
+ return (
336
+ "<cls>",
337
+ "<pad>",
338
+ "<eos>",
339
+ "<unk>",
340
+ "L",
341
+ "A",
342
+ "G",
343
+ "V",
344
+ "S",
345
+ "E",
346
+ "R",
347
+ "T",
348
+ "I",
349
+ "D",
350
+ "P",
351
+ "K",
352
+ "Q",
353
+ "N",
354
+ "F",
355
+ "Y",
356
+ "M",
357
+ "H",
358
+ "W",
359
+ "C",
360
+ "X",
361
+ "B",
362
+ "U",
363
+ "Z",
364
+ "O",
365
+ ".",
366
+ "-",
367
+ "<null_1>",
368
+ "<mask>",
369
+ )
370
+
modeling_esm.py ADDED
@@ -0,0 +1,1595 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 Meta and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """ PyTorch ESM model."""
16
+
17
+ import math
18
+ from typing import List, Optional, Tuple, Union
19
+
20
+ import torch
21
+ import torch.utils.checkpoint
22
+ from torch import nn
23
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
24
+
25
+ from transformers.file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward
26
+ from transformers.modeling_outputs import (
27
+ BaseModelOutputWithPastAndCrossAttentions,
28
+ BaseModelOutputWithPoolingAndCrossAttentions,
29
+ MaskedLMOutput,
30
+ SequenceClassifierOutput,
31
+ TokenClassifierOutput,
32
+ )
33
+ from transformers.modeling_utils import PreTrainedModel, find_pruneable_heads_and_indices, prune_linear_layer
34
+ from transformers.utils import logging
35
+ from configuration_esm import EsmConfig
36
+
37
+
38
+
39
+
40
+ logger = logging.get_logger(__name__)
41
+
42
+ _CHECKPOINT_FOR_DOC = "facebook/esm2_t6_8M_UR50D"
43
+ _CONFIG_FOR_DOC = "EsmConfig"
44
+ _TOKENIZER_FOR_DOC = "EsmTokenizer"
45
+
46
+ ESM_PRETRAINED_MODEL_ARCHIVE_LIST = [
47
+ "facebook/esm2_t6_8M_UR50D",
48
+ "facebook/esm2_t12_35M_UR50D",
49
+ # This is not a complete list of all ESM models!
50
+ # See all ESM models at https://huggingface.co/models?filter=esm
51
+ ]
52
+
53
+
54
+ def rotate_half(x):
55
+ x1, x2 = x.chunk(2, dim=-1)
56
+ return torch.cat((-x2, x1), dim=-1)
57
+
58
+
59
+ def apply_rotary_pos_emb(x, cos, sin):
60
+ cos = cos[:, :, : x.shape[-2], :]
61
+ sin = sin[:, :, : x.shape[-2], :]
62
+
63
+ return (x * cos) + (rotate_half(x) * sin)
64
+
65
+
66
+ def gelu(x):
67
+ """
68
+ This is the gelu implementation from the original ESM repo. Using F.gelu yields subtly wrong results.
69
+ """
70
+ return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0)))
71
+
72
+
73
+ class RotaryEmbedding(torch.nn.Module):
74
+ """
75
+ Rotary position embeddings based on those in
76
+ [RoFormer](https://huggingface.co/docs/transformers/model_doc/roformer). Query and keys are transformed by rotation
77
+ matrices which depend on their relative positions.
78
+ """
79
+
80
+ def __init__(self, dim: int):
81
+ super().__init__()
82
+ # Generate and save the inverse frequency buffer (non trainable)
83
+ inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2).float() / dim))
84
+ inv_freq = inv_freq
85
+ self.register_buffer("inv_freq", inv_freq)
86
+
87
+ self._seq_len_cached = None
88
+ self._cos_cached = None
89
+ self._sin_cached = None
90
+
91
+ def _update_cos_sin_tables(self, x, seq_dimension=2):
92
+ seq_len = x.shape[seq_dimension]
93
+
94
+ # Reset the tables if the sequence length has changed,
95
+ # or if we're on a new device (possibly due to tracing for instance)
96
+ if seq_len != self._seq_len_cached or self._cos_cached.device != x.device:
97
+ self._seq_len_cached = seq_len
98
+ t = torch.arange(x.shape[seq_dimension], device=x.device).type_as(self.inv_freq)
99
+ freqs = torch.outer(t, self.inv_freq)
100
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
101
+
102
+ self._cos_cached = emb.cos()[None, None, :, :]
103
+ self._sin_cached = emb.sin()[None, None, :, :]
104
+
105
+ return self._cos_cached, self._sin_cached
106
+
107
+ def forward(self, q: torch.Tensor, k: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
108
+ self._cos_cached, self._sin_cached = self._update_cos_sin_tables(k, seq_dimension=-2)
109
+
110
+ return (
111
+ apply_rotary_pos_emb(q, self._cos_cached, self._sin_cached),
112
+ apply_rotary_pos_emb(k, self._cos_cached, self._sin_cached),
113
+ )
114
+
115
+
116
+ class EsmEmbeddings(nn.Module):
117
+ """
118
+ Same as BertEmbeddings with a tiny tweak for positional embeddings indexing.
119
+ """
120
+
121
+ def __init__(self, config):
122
+ super().__init__()
123
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
124
+
125
+ if config.emb_layer_norm_before:
126
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
127
+ else:
128
+ self.layer_norm = None
129
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
130
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
131
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
132
+ self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)))
133
+
134
+ self.padding_idx = config.pad_token_id
135
+ self.position_embeddings = nn.Embedding(
136
+ config.max_position_embeddings, config.hidden_size, padding_idx=self.padding_idx
137
+ )
138
+ self.token_dropout = config.token_dropout
139
+ self.mask_token_id = config.mask_token_id
140
+
141
+ def forward(
142
+ self, input_ids=None, attention_mask=None, position_ids=None, inputs_embeds=None, past_key_values_length=0
143
+ ):
144
+ if position_ids is None:
145
+ if input_ids is not None:
146
+ # Create the position ids from the input token ids. Any padded tokens remain padded.
147
+ position_ids = create_position_ids_from_input_ids(input_ids, self.padding_idx, past_key_values_length)
148
+ else:
149
+ position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds)
150
+
151
+ if inputs_embeds is None:
152
+ inputs_embeds = self.word_embeddings(input_ids)
153
+
154
+ # Note that if we want to support ESM-1 (not 1b!) in future then we need to support an
155
+ # embedding_scale factor here.
156
+ embeddings = inputs_embeds
157
+
158
+ # Matt: ESM has the option to handle masking in MLM in a slightly unusual way. If the token_dropout
159
+ # flag is False then it is handled in the same was as BERT/RoBERTa. If it is set to True, however,
160
+ # masked tokens are treated as if they were selected for input dropout and zeroed out.
161
+ # This "mask-dropout" is compensated for when masked tokens are not present, by scaling embeddings by
162
+ # a factor of (fraction of unmasked tokens during training) / (fraction of unmasked tokens in sample).
163
+ # This is analogous to the way that dropout layers scale down outputs during evaluation when not
164
+ # actually dropping out values (or, equivalently, scale up their un-dropped outputs in training).
165
+ if self.token_dropout:
166
+ embeddings.masked_fill_((input_ids == self.mask_token_id).unsqueeze(-1), 0.0)
167
+ mask_ratio_train = 0.15 * 0.8 # Hardcoded as the ratio used in all ESM model training runs
168
+ src_lengths = attention_mask.sum(-1)
169
+ mask_ratio_observed = (input_ids == self.mask_token_id).sum(-1).float() / src_lengths
170
+ embeddings = (embeddings * (1 - mask_ratio_train) / (1 - mask_ratio_observed)[:, None, None]).to(
171
+ embeddings.dtype
172
+ )
173
+
174
+ if self.position_embedding_type == "absolute":
175
+ position_embeddings = self.position_embeddings(position_ids)
176
+ embeddings += position_embeddings
177
+
178
+ if self.layer_norm is not None:
179
+ embeddings = self.layer_norm(embeddings)
180
+ if attention_mask is not None:
181
+ embeddings = (embeddings * attention_mask.unsqueeze(-1)).to(embeddings.dtype)
182
+ # Matt: I think this line was copied incorrectly from BERT, disabling it for now.
183
+ # embeddings = self.dropout(embeddings)
184
+ return embeddings
185
+
186
+ def create_position_ids_from_inputs_embeds(self, inputs_embeds):
187
+ """
188
+ We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
189
+
190
+ Args:
191
+ inputs_embeds: torch.Tensor
192
+
193
+ Returns: torch.Tensor
194
+ """
195
+ input_shape = inputs_embeds.size()[:-1]
196
+ sequence_length = input_shape[1]
197
+
198
+ position_ids = torch.arange(
199
+ self.padding_idx + 1, sequence_length + self.padding_idx + 1, dtype=torch.long, device=inputs_embeds.device
200
+ )
201
+ return position_ids.unsqueeze(0).expand(input_shape)
202
+
203
+
204
+ class EsmSelfAttention(nn.Module):
205
+ def __init__(self, config, position_embedding_type=None):
206
+ super().__init__()
207
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
208
+ raise ValueError(
209
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
210
+ f"heads ({config.num_attention_heads})"
211
+ )
212
+
213
+ self.num_attention_heads = config.num_attention_heads
214
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
215
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
216
+
217
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
218
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
219
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
220
+
221
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
222
+ self.position_embedding_type = position_embedding_type or getattr(
223
+ config, "position_embedding_type", "absolute"
224
+ )
225
+ self.rotary_embeddings = None
226
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
227
+ self.max_position_embeddings = config.max_position_embeddings
228
+ self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
229
+ elif self.position_embedding_type == "rotary":
230
+ self.rotary_embeddings = RotaryEmbedding(dim=self.attention_head_size)
231
+
232
+ self.is_decoder = config.is_decoder
233
+
234
+ def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
235
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
236
+ x = x.view(new_x_shape)
237
+ return x.permute(0, 2, 1, 3)
238
+
239
+ def forward(
240
+ self,
241
+ hidden_states: torch.Tensor,
242
+ attention_mask: Optional[torch.FloatTensor] = None,
243
+ head_mask: Optional[torch.FloatTensor] = None,
244
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
245
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
246
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
247
+ output_attentions: Optional[bool] = False,
248
+ ) -> Tuple[torch.Tensor]:
249
+
250
+ mixed_query_layer = self.query(hidden_states)
251
+
252
+ # If this is instantiated as a cross-attention module, the keys
253
+ # and values come from an encoder; the attention mask needs to be
254
+ # such that the encoder's padding tokens are not attended to.
255
+ is_cross_attention = encoder_hidden_states is not None
256
+
257
+ if is_cross_attention and past_key_value is not None:
258
+ # reuse k,v, cross_attentions
259
+ key_layer = past_key_value[0]
260
+ value_layer = past_key_value[1]
261
+ attention_mask = encoder_attention_mask
262
+ elif is_cross_attention:
263
+ key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
264
+ value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
265
+ attention_mask = encoder_attention_mask
266
+ elif past_key_value is not None:
267
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
268
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
269
+ key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
270
+ value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
271
+ else:
272
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
273
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
274
+
275
+ query_layer = self.transpose_for_scores(mixed_query_layer)
276
+
277
+ # Matt: Our BERT model (which this code was derived from) scales attention logits down by sqrt(head_dim).
278
+ # ESM scales the query down by the same factor instead. Modulo numerical stability these are equivalent,
279
+ # but not when rotary embeddings get involved. Therefore, we scale the query here to match the original
280
+ # ESM code and fix rotary embeddings.
281
+ query_layer = query_layer * self.attention_head_size**-0.5
282
+
283
+ if self.is_decoder:
284
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
285
+ # Further calls to cross_attention layer can then reuse all cross-attention
286
+ # key/value_states (first "if" case)
287
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
288
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
289
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
290
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
291
+ past_key_value = (key_layer, value_layer)
292
+
293
+ if self.position_embedding_type == "rotary":
294
+ query_layer, key_layer = self.rotary_embeddings(query_layer, key_layer)
295
+
296
+ # Take the dot product between "query" and "key" to get the raw attention scores.
297
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
298
+
299
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
300
+ seq_length = hidden_states.size()[1]
301
+ position_ids_l = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
302
+ position_ids_r = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
303
+ distance = position_ids_l - position_ids_r
304
+ positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
305
+ positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
306
+
307
+ if self.position_embedding_type == "relative_key":
308
+ relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
309
+ attention_scores = attention_scores + relative_position_scores
310
+ elif self.position_embedding_type == "relative_key_query":
311
+ relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
312
+ relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
313
+ attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
314
+
315
+ if attention_mask is not None:
316
+ # Apply the attention mask is (precomputed for all layers in EsmModel forward() function)
317
+ attention_scores = attention_scores + attention_mask
318
+
319
+ # Normalize the attention scores to probabilities.
320
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
321
+
322
+ # This is actually dropping out entire tokens to attend to, which might
323
+ # seem a bit unusual, but is taken from the original Transformer paper.
324
+ attention_probs = self.dropout(attention_probs)
325
+
326
+ # Mask heads if we want to
327
+ if head_mask is not None:
328
+ attention_probs = attention_probs * head_mask
329
+
330
+ context_layer = torch.matmul(attention_probs, value_layer)
331
+
332
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
333
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
334
+ context_layer = context_layer.view(new_context_layer_shape)
335
+
336
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
337
+
338
+ if self.is_decoder:
339
+ outputs = outputs + (past_key_value,)
340
+ return outputs
341
+
342
+
343
+ class EsmSelfOutput(nn.Module):
344
+ def __init__(self, config):
345
+ super().__init__()
346
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
347
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
348
+
349
+ def forward(self, hidden_states, input_tensor):
350
+ hidden_states = self.dense(hidden_states)
351
+ hidden_states = self.dropout(hidden_states)
352
+ hidden_states += input_tensor
353
+ return hidden_states
354
+
355
+
356
+ class EsmAttention(nn.Module):
357
+ def __init__(self, config):
358
+ super().__init__()
359
+ self.self = EsmSelfAttention(config)
360
+ self.output = EsmSelfOutput(config)
361
+ self.pruned_heads = set()
362
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
363
+
364
+ def prune_heads(self, heads):
365
+ if len(heads) == 0:
366
+ return
367
+ heads, index = find_pruneable_heads_and_indices(
368
+ heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
369
+ )
370
+
371
+ # Prune linear layers
372
+ self.self.query = prune_linear_layer(self.self.query, index)
373
+ self.self.key = prune_linear_layer(self.self.key, index)
374
+ self.self.value = prune_linear_layer(self.self.value, index)
375
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
376
+
377
+ # Update hyper params and store pruned heads
378
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
379
+ self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
380
+ self.pruned_heads = self.pruned_heads.union(heads)
381
+
382
+ def forward(
383
+ self,
384
+ hidden_states,
385
+ attention_mask=None,
386
+ head_mask=None,
387
+ encoder_hidden_states=None,
388
+ encoder_attention_mask=None,
389
+ past_key_value=None,
390
+ output_attentions=False,
391
+ ):
392
+ hidden_states_ln = self.LayerNorm(hidden_states)
393
+ self_outputs = self.self(
394
+ hidden_states_ln,
395
+ attention_mask,
396
+ head_mask,
397
+ encoder_hidden_states,
398
+ encoder_attention_mask,
399
+ past_key_value,
400
+ output_attentions,
401
+ )
402
+ attention_output = self.output(self_outputs[0], hidden_states)
403
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
404
+ return outputs
405
+
406
+
407
+ class EsmIntermediate(nn.Module):
408
+ def __init__(self, config):
409
+ super().__init__()
410
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
411
+
412
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
413
+ hidden_states = self.dense(hidden_states)
414
+ hidden_states = gelu(hidden_states)
415
+ return hidden_states
416
+
417
+
418
+ class EsmOutput(nn.Module):
419
+ def __init__(self, config):
420
+ super().__init__()
421
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
422
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
423
+
424
+ def forward(self, hidden_states, input_tensor):
425
+ hidden_states = self.dense(hidden_states)
426
+ hidden_states = self.dropout(hidden_states)
427
+ hidden_states += input_tensor
428
+ return hidden_states
429
+
430
+
431
+ class EsmLayer(nn.Module):
432
+ def __init__(self, config):
433
+ super().__init__()
434
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
435
+ self.seq_len_dim = 1
436
+ self.attention = EsmAttention(config)
437
+ self.is_decoder = config.is_decoder
438
+ self.add_cross_attention = config.add_cross_attention
439
+ if self.add_cross_attention:
440
+ if not self.is_decoder:
441
+ raise RuntimeError(f"{self} should be used as a decoder model if cross attention is added")
442
+ self.crossattention = EsmAttention(config)
443
+ self.intermediate = EsmIntermediate(config)
444
+ self.output = EsmOutput(config)
445
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
446
+
447
+ def forward(
448
+ self,
449
+ hidden_states,
450
+ attention_mask=None,
451
+ head_mask=None,
452
+ encoder_hidden_states=None,
453
+ encoder_attention_mask=None,
454
+ past_key_value=None,
455
+ output_attentions=False,
456
+ ):
457
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
458
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
459
+ self_attention_outputs = self.attention(
460
+ hidden_states,
461
+ attention_mask,
462
+ head_mask,
463
+ output_attentions=output_attentions,
464
+ past_key_value=self_attn_past_key_value,
465
+ )
466
+ attention_output = self_attention_outputs[0]
467
+
468
+ # if decoder, the last output is tuple of self-attn cache
469
+ if self.is_decoder:
470
+ outputs = self_attention_outputs[1:-1]
471
+ present_key_value = self_attention_outputs[-1]
472
+ else:
473
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
474
+
475
+ cross_attn_present_key_value = None
476
+ if self.is_decoder and encoder_hidden_states is not None:
477
+ if not hasattr(self, "crossattention"):
478
+ raise AttributeError(
479
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated"
480
+ " with cross-attention layers by setting `config.add_cross_attention=True`"
481
+ )
482
+
483
+ # cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple
484
+ cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
485
+ cross_attention_outputs = self.crossattention(
486
+ attention_output,
487
+ attention_mask,
488
+ head_mask,
489
+ encoder_hidden_states,
490
+ encoder_attention_mask,
491
+ cross_attn_past_key_value,
492
+ output_attentions,
493
+ )
494
+ attention_output = cross_attention_outputs[0]
495
+ outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
496
+
497
+ # add cross-attn cache to positions 3,4 of present_key_value tuple
498
+ cross_attn_present_key_value = cross_attention_outputs[-1]
499
+ present_key_value = present_key_value + cross_attn_present_key_value
500
+
501
+ layer_output = self.feed_forward_chunk(attention_output)
502
+
503
+ outputs = (layer_output,) + outputs
504
+
505
+ # if decoder, return the attn key/values as the last output
506
+ if self.is_decoder:
507
+ outputs = outputs + (present_key_value,)
508
+ return outputs
509
+
510
+ def feed_forward_chunk(self, attention_output):
511
+ attention_output_ln = self.LayerNorm(attention_output)
512
+ intermediate_output = self.intermediate(attention_output_ln)
513
+ layer_output = self.output(intermediate_output, attention_output)
514
+ return layer_output
515
+
516
+
517
+ class EsmEncoder(nn.Module):
518
+ def __init__(self, config):
519
+ super().__init__()
520
+ self.config = config
521
+ self.layer = nn.ModuleList([EsmLayer(config) for _ in range(config.num_hidden_layers)])
522
+ self.emb_layer_norm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
523
+ self.gradient_checkpointing = False
524
+
525
+ def forward(
526
+ self,
527
+ hidden_states,
528
+ attention_mask=None,
529
+ head_mask=None,
530
+ encoder_hidden_states=None,
531
+ encoder_attention_mask=None,
532
+ past_key_values=None,
533
+ use_cache=None,
534
+ output_attentions=False,
535
+ output_hidden_states=False,
536
+ return_dict=True,
537
+ ):
538
+ all_hidden_states = () if output_hidden_states else None
539
+ all_self_attentions = () if output_attentions else None
540
+ all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
541
+
542
+ next_decoder_cache = () if use_cache else None
543
+ for i, layer_module in enumerate(self.layer):
544
+ if output_hidden_states:
545
+ all_hidden_states = all_hidden_states + (hidden_states,)
546
+
547
+ layer_head_mask = head_mask[i] if head_mask is not None else None
548
+ past_key_value = past_key_values[i] if past_key_values is not None else None
549
+
550
+ if self.gradient_checkpointing and self.training:
551
+
552
+ if use_cache:
553
+ logger.warning(
554
+ "`use_cache=True` is incompatible with `config.gradient_checkpointing=True`. Setting "
555
+ "`use_cache=False`..."
556
+ )
557
+ use_cache = False
558
+
559
+ def create_custom_forward(module):
560
+ def custom_forward(*inputs):
561
+ return module(*inputs, past_key_value, output_attentions)
562
+
563
+ return custom_forward
564
+
565
+ layer_outputs = torch.utils.checkpoint.checkpoint(
566
+ create_custom_forward(layer_module),
567
+ hidden_states,
568
+ attention_mask,
569
+ layer_head_mask,
570
+ encoder_hidden_states,
571
+ encoder_attention_mask,
572
+ )
573
+ else:
574
+ layer_outputs = layer_module(
575
+ hidden_states,
576
+ attention_mask,
577
+ layer_head_mask,
578
+ encoder_hidden_states,
579
+ encoder_attention_mask,
580
+ past_key_value,
581
+ output_attentions,
582
+ )
583
+
584
+ hidden_states = layer_outputs[0]
585
+ if use_cache:
586
+ next_decoder_cache += (layer_outputs[-1],)
587
+ if output_attentions:
588
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
589
+ if self.config.add_cross_attention:
590
+ all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
591
+
592
+ if self.emb_layer_norm_after:
593
+ hidden_states = self.emb_layer_norm_after(hidden_states)
594
+
595
+ if output_hidden_states:
596
+ all_hidden_states = all_hidden_states + (hidden_states,)
597
+
598
+ if not return_dict:
599
+ return tuple(
600
+ v
601
+ for v in [
602
+ hidden_states,
603
+ next_decoder_cache,
604
+ all_hidden_states,
605
+ all_self_attentions,
606
+ all_cross_attentions,
607
+ ]
608
+ if v is not None
609
+ )
610
+ return BaseModelOutputWithPastAndCrossAttentions(
611
+ last_hidden_state=hidden_states,
612
+ past_key_values=next_decoder_cache,
613
+ hidden_states=all_hidden_states,
614
+ attentions=all_self_attentions,
615
+ cross_attentions=all_cross_attentions,
616
+ )
617
+
618
+
619
+ # Copied from transformers.models.bert.modeling_bert.BertPooler
620
+ class EsmPooler(nn.Module):
621
+ def __init__(self, config):
622
+ super().__init__()
623
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
624
+ self.activation = nn.Tanh()
625
+
626
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
627
+ # We "pool" the model by simply taking the hidden state corresponding
628
+ # to the first token.
629
+ first_token_tensor = hidden_states[:, 0]
630
+ pooled_output = self.dense(first_token_tensor)
631
+ pooled_output = self.activation(pooled_output)
632
+ return pooled_output
633
+
634
+
635
+ class EsmPreTrainedModel(PreTrainedModel):
636
+ """
637
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
638
+ models.
639
+ """
640
+
641
+ config_class = EsmConfig
642
+ base_model_prefix = "esm"
643
+ _no_split_modules = ["EsmLayer", "EsmFoldTriangularSelfAttentionBlock"]
644
+
645
+ # Copied from transformers.models.bert.modeling_bert.BertPreTrainedModel._init_weights
646
+ def _init_weights(self, module):
647
+ """Initialize the weights"""
648
+ if isinstance(module, nn.Linear):
649
+ # Slightly different from the TF version which uses truncated_normal for initialization
650
+ # cf https://github.com/pytorch/pytorch/pull/5617
651
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
652
+ if module.bias is not None:
653
+ module.bias.data.zero_()
654
+ elif isinstance(module, nn.Embedding):
655
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
656
+ if module.padding_idx is not None:
657
+ module.weight.data[module.padding_idx].zero_()
658
+ elif isinstance(module, nn.LayerNorm):
659
+ module.bias.data.zero_()
660
+ module.weight.data.fill_(1.0)
661
+
662
+
663
+ ESM_START_DOCSTRING = r"""
664
+
665
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
666
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
667
+ etc.)
668
+
669
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
670
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
671
+ and behavior.
672
+
673
+ Parameters:
674
+ config ([`EsmConfig`]): Model configuration class with all the parameters of the
675
+ model. Initializing with a config file does not load the weights associated with the model, only the
676
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
677
+ """
678
+
679
+ ESM_INPUTS_DOCSTRING = r"""
680
+ Args:
681
+ input_ids (`torch.LongTensor` of shape `({0})`):
682
+ Indices of input sequence tokens in the vocabulary.
683
+
684
+ Indices can be obtained using [`EsmTokenizer`]. See [`PreTrainedTokenizer.encode`] and
685
+ [`PreTrainedTokenizer.__call__`] for details.
686
+
687
+ [What are input IDs?](../glossary#input-ids)
688
+ attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
689
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
690
+
691
+ - 1 for tokens that are **not masked**,
692
+ - 0 for tokens that are **masked**.
693
+
694
+ [What are attention masks?](../glossary#attention-mask)
695
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
696
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
697
+ config.max_position_embeddings - 1]`.
698
+
699
+ [What are position IDs?](../glossary#position-ids)
700
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
701
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
702
+
703
+ - 1 indicates the head is **not masked**,
704
+ - 0 indicates the head is **masked**.
705
+
706
+ inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
707
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
708
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
709
+ model's internal embedding lookup matrix.
710
+ output_attentions (`bool`, *optional*):
711
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
712
+ tensors for more detail.
713
+ output_hidden_states (`bool`, *optional*):
714
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
715
+ more detail.
716
+ return_dict (`bool`, *optional*):
717
+ Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.
718
+ """
719
+
720
+
721
+ @add_start_docstrings(
722
+ "The bare ESM Model transformer outputting raw hidden-states without any specific head on top.",
723
+ ESM_START_DOCSTRING,
724
+ )
725
+ class EsmModel(EsmPreTrainedModel):
726
+ """
727
+
728
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
729
+ cross-attention is added between the self-attention layers, following the architecture described in [Attention is
730
+ all you need](https://arxiv.org/abs/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
731
+ Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
732
+
733
+ To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
734
+ to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
735
+ `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
736
+ """
737
+
738
+ _keys_to_ignore_on_load_missing = [r"position_ids"]
739
+ supports_gradient_checkpointing = False
740
+
741
+ # Copied from transformers.models.bert.modeling_bert.BertModel.__init__ with Bert->Esm
742
+ def __init__(self, config, add_pooling_layer=True):
743
+ super().__init__(config)
744
+ self.config = config
745
+
746
+ self.embeddings = EsmEmbeddings(config)
747
+ self.encoder = EsmEncoder(config)
748
+
749
+ self.pooler = EsmPooler(config) if add_pooling_layer else None
750
+
751
+ # Initialize weights and apply final processing
752
+ self.post_init()
753
+
754
+ def _set_gradient_checkpointing(self, module, value=False):
755
+ if isinstance(module, EsmEncoder):
756
+ module.gradient_checkpointing = value
757
+
758
+ def get_input_embeddings(self):
759
+ return self.embeddings.word_embeddings
760
+
761
+ def set_input_embeddings(self, value):
762
+ self.embeddings.word_embeddings = value
763
+
764
+ def _prune_heads(self, heads_to_prune):
765
+ """
766
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
767
+ class PreTrainedModel
768
+ """
769
+ for layer, heads in heads_to_prune.items():
770
+ self.encoder.layer[layer].attention.prune_heads(heads)
771
+
772
+ @add_start_docstrings_to_model_forward(ESM_INPUTS_DOCSTRING.format("(batch_size, sequence_length)"))
773
+ @add_code_sample_docstrings(
774
+ processor_class=_TOKENIZER_FOR_DOC,
775
+ checkpoint=_CHECKPOINT_FOR_DOC,
776
+ output_type=BaseModelOutputWithPoolingAndCrossAttentions,
777
+ config_class=_CONFIG_FOR_DOC,
778
+ )
779
+ def forward(
780
+ self,
781
+ input_ids: Optional[torch.Tensor] = None,
782
+ attention_mask: Optional[torch.Tensor] = None,
783
+ position_ids: Optional[torch.Tensor] = None,
784
+ head_mask: Optional[torch.Tensor] = None,
785
+ inputs_embeds: Optional[torch.Tensor] = None,
786
+ encoder_hidden_states: Optional[torch.Tensor] = None,
787
+ encoder_attention_mask: Optional[torch.Tensor] = None,
788
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
789
+ use_cache: Optional[bool] = None,
790
+ output_attentions: Optional[bool] = None,
791
+ output_hidden_states: Optional[bool] = None,
792
+ return_dict: Optional[bool] = None,
793
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
794
+ r"""
795
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
796
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
797
+ the model is configured as a decoder.
798
+ encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
799
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
800
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
801
+
802
+ - 1 for tokens that are **not masked**,
803
+ - 0 for tokens that are **masked**.
804
+ past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
805
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
806
+
807
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
808
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
809
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
810
+ use_cache (`bool`, *optional*):
811
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
812
+ `past_key_values`).
813
+ """
814
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
815
+ output_hidden_states = (
816
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
817
+ )
818
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
819
+
820
+ if self.config.is_decoder:
821
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
822
+ else:
823
+ use_cache = False
824
+
825
+ if input_ids is not None and inputs_embeds is not None:
826
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
827
+ elif input_ids is not None:
828
+ input_shape = input_ids.size()
829
+ elif inputs_embeds is not None:
830
+ input_shape = inputs_embeds.size()[:-1]
831
+ else:
832
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
833
+
834
+ batch_size, seq_length = input_shape
835
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
836
+
837
+ # past_key_values_length
838
+ past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
839
+
840
+ if attention_mask is None:
841
+ attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)
842
+
843
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
844
+ # ourselves in which case we just need to make it broadcastable to all heads.
845
+ extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
846
+
847
+ # If a 2D or 3D attention mask is provided for the cross-attention
848
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
849
+ if self.config.is_decoder and encoder_hidden_states is not None:
850
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
851
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
852
+ if encoder_attention_mask is None:
853
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
854
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
855
+ else:
856
+ encoder_extended_attention_mask = None
857
+
858
+ # Prepare head mask if needed
859
+ # 1.0 in head_mask indicate we keep the head
860
+ # attention_probs has shape bsz x n_heads x N x N
861
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
862
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
863
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
864
+
865
+ embedding_output = self.embeddings(
866
+ input_ids=input_ids,
867
+ position_ids=position_ids,
868
+ attention_mask=attention_mask,
869
+ inputs_embeds=inputs_embeds,
870
+ past_key_values_length=past_key_values_length,
871
+ )
872
+ encoder_outputs = self.encoder(
873
+ embedding_output,
874
+ attention_mask=extended_attention_mask,
875
+ head_mask=head_mask,
876
+ encoder_hidden_states=encoder_hidden_states,
877
+ encoder_attention_mask=encoder_extended_attention_mask,
878
+ past_key_values=past_key_values,
879
+ use_cache=use_cache,
880
+ output_attentions=output_attentions,
881
+ output_hidden_states=output_hidden_states,
882
+ return_dict=return_dict,
883
+ )
884
+ sequence_output = encoder_outputs[0]
885
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
886
+
887
+ if not return_dict:
888
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
889
+
890
+ return BaseModelOutputWithPoolingAndCrossAttentions(
891
+ last_hidden_state=sequence_output,
892
+ pooler_output=pooled_output,
893
+ past_key_values=encoder_outputs.past_key_values,
894
+ hidden_states=encoder_outputs.hidden_states,
895
+ attentions=encoder_outputs.attentions,
896
+ cross_attentions=encoder_outputs.cross_attentions,
897
+ )
898
+
899
+
900
+ @add_start_docstrings("""ESM Model with a `language modeling` head on top.""", ESM_START_DOCSTRING)
901
+ class EsmForMaskedLM(EsmPreTrainedModel):
902
+ _keys_to_ignore_on_load_missing = [r"position_ids", "lm_head.decoder.weight"]
903
+ _keys_to_ignore_on_load_unexpected = [r"pooler"]
904
+
905
+ def __init__(self, config):
906
+ super().__init__(config)
907
+
908
+ if config.is_decoder:
909
+ logger.warning(
910
+ "If you want to use `EsmForMaskedLM` make sure `config.is_decoder=False` for "
911
+ "bi-directional self-attention."
912
+ )
913
+
914
+ self.esm = EsmModel(config, add_pooling_layer=False)
915
+ self.lm_head = EsmLMHead(config)
916
+
917
+ self.init_weights()
918
+
919
+ def get_output_embeddings(self):
920
+ return self.lm_head.decoder
921
+
922
+ def set_output_embeddings(self, new_embeddings):
923
+ self.lm_head.decoder = new_embeddings
924
+
925
+ @add_start_docstrings_to_model_forward(ESM_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
926
+ @add_code_sample_docstrings(
927
+ processor_class=_TOKENIZER_FOR_DOC,
928
+ checkpoint=_CHECKPOINT_FOR_DOC,
929
+ output_type=MaskedLMOutput,
930
+ config_class=_CONFIG_FOR_DOC,
931
+ mask="<mask>",
932
+ )
933
+ def forward(
934
+ self,
935
+ input_ids: Optional[torch.LongTensor] = None,
936
+ attention_mask: Optional[torch.Tensor] = None,
937
+ position_ids: Optional[torch.LongTensor] = None,
938
+ head_mask: Optional[torch.Tensor] = None,
939
+ inputs_embeds: Optional[torch.FloatTensor] = None,
940
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
941
+ encoder_attention_mask: Optional[torch.Tensor] = None,
942
+ labels: Optional[torch.LongTensor] = None,
943
+ output_attentions: Optional[bool] = None,
944
+ output_hidden_states: Optional[bool] = None,
945
+ return_dict: Optional[bool] = None,
946
+ ) -> Union[Tuple, MaskedLMOutput]:
947
+ r"""
948
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
949
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
950
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
951
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
952
+ kwargs (`Dict[str, any]`, optional, defaults to *{}*):
953
+ Used to hide legacy arguments that have been deprecated.
954
+ """
955
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
956
+
957
+ outputs = self.esm(
958
+ input_ids,
959
+ attention_mask=attention_mask,
960
+ position_ids=position_ids,
961
+ head_mask=head_mask,
962
+ inputs_embeds=inputs_embeds,
963
+ encoder_hidden_states=encoder_hidden_states,
964
+ encoder_attention_mask=encoder_attention_mask,
965
+ output_attentions=output_attentions,
966
+ output_hidden_states=output_hidden_states,
967
+ return_dict=return_dict,
968
+ )
969
+ sequence_output = outputs[0]
970
+ prediction_scores = self.lm_head(sequence_output)
971
+
972
+ masked_lm_loss = None
973
+ if labels is not None:
974
+ loss_fct = CrossEntropyLoss()
975
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
976
+
977
+ if not return_dict:
978
+ output = (prediction_scores,) + outputs[2:]
979
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
980
+
981
+ return MaskedLMOutput(
982
+ loss=masked_lm_loss,
983
+ logits=prediction_scores,
984
+ hidden_states=outputs.hidden_states,
985
+ attentions=outputs.attentions,
986
+ )
987
+
988
+
989
+ class EsmLMHead(nn.Module):
990
+ """ESM Head for masked language modeling."""
991
+
992
+ def __init__(self, config):
993
+ super().__init__()
994
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
995
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
996
+
997
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
998
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
999
+
1000
+ def forward(self, features, **kwargs):
1001
+ x = self.dense(features)
1002
+ x = gelu(x)
1003
+ x = self.layer_norm(x)
1004
+
1005
+ # project back to size of vocabulary with bias
1006
+ x = self.decoder(x) + self.bias
1007
+ return x
1008
+
1009
+
1010
+ @add_start_docstrings(
1011
+ """
1012
+ ESM Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
1013
+ output) e.g. for GLUE tasks.
1014
+ """,
1015
+ ESM_START_DOCSTRING,
1016
+ )
1017
+ class EsmForSequenceClassification(EsmPreTrainedModel):
1018
+ _keys_to_ignore_on_load_missing = [r"position_ids"]
1019
+
1020
+ def __init__(self, config):
1021
+ super().__init__(config)
1022
+ self.num_labels = config.num_labels
1023
+ self.config = config
1024
+
1025
+ self.esm = EsmModel(config, add_pooling_layer=False)
1026
+ self.classifier = EsmClassificationHead(config)
1027
+
1028
+ self.init_weights()
1029
+
1030
+ @add_start_docstrings_to_model_forward(ESM_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1031
+ @add_code_sample_docstrings(
1032
+ processor_class=_TOKENIZER_FOR_DOC,
1033
+ checkpoint=_CHECKPOINT_FOR_DOC,
1034
+ output_type=SequenceClassifierOutput,
1035
+ config_class=_CONFIG_FOR_DOC,
1036
+ )
1037
+ def forward(
1038
+ self,
1039
+ input_ids: Optional[torch.LongTensor] = None,
1040
+ attention_mask: Optional[torch.Tensor] = None,
1041
+ position_ids: Optional[torch.LongTensor] = None,
1042
+ head_mask: Optional[torch.Tensor] = None,
1043
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1044
+ labels: Optional[torch.LongTensor] = None,
1045
+ output_attentions: Optional[bool] = None,
1046
+ output_hidden_states: Optional[bool] = None,
1047
+ return_dict: Optional[bool] = None,
1048
+ ) -> Union[Tuple, SequenceClassifierOutput]:
1049
+ r"""
1050
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1051
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1052
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1053
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1054
+ """
1055
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1056
+
1057
+ outputs = self.esm(
1058
+ input_ids,
1059
+ attention_mask=attention_mask,
1060
+ position_ids=position_ids,
1061
+ head_mask=head_mask,
1062
+ inputs_embeds=inputs_embeds,
1063
+ output_attentions=output_attentions,
1064
+ output_hidden_states=output_hidden_states,
1065
+ return_dict=return_dict,
1066
+ )
1067
+ sequence_output = outputs[0]
1068
+ logits = self.classifier(sequence_output)
1069
+
1070
+ loss = None
1071
+ if labels is not None:
1072
+ if self.config.problem_type is None:
1073
+ if self.num_labels == 1:
1074
+ self.config.problem_type = "regression"
1075
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1076
+ self.config.problem_type = "single_label_classification"
1077
+ else:
1078
+ self.config.problem_type = "multi_label_classification"
1079
+
1080
+ if self.config.problem_type == "regression":
1081
+ loss_fct = MSELoss()
1082
+ if self.num_labels == 1:
1083
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1084
+ else:
1085
+ loss = loss_fct(logits, labels)
1086
+ elif self.config.problem_type == "single_label_classification":
1087
+ loss_fct = CrossEntropyLoss()
1088
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1089
+ elif self.config.problem_type == "multi_label_classification":
1090
+ loss_fct = BCEWithLogitsLoss()
1091
+ loss = loss_fct(logits, labels)
1092
+
1093
+ if not return_dict:
1094
+ output = (logits,) + outputs[2:]
1095
+ return ((loss,) + output) if loss is not None else output
1096
+
1097
+ return SequenceClassifierOutput(
1098
+ loss=loss,
1099
+ logits=logits,
1100
+ hidden_states=outputs.hidden_states,
1101
+ attentions=outputs.attentions,
1102
+ )
1103
+
1104
+ @add_start_docstrings(
1105
+ """
1106
+ ESM Model transformer with a customized sequence classification/regression head on top (a linear layer on top of the pooled
1107
+ output) e.g. for GLUE tasks.
1108
+ """,
1109
+ ESM_START_DOCSTRING,
1110
+ )
1111
+ class EsmForSequenceClassificationCustom(EsmPreTrainedModel):
1112
+ _keys_to_ignore_on_load_missing = [r"position_ids"]
1113
+
1114
+ def __init__(self, config):
1115
+ super().__init__(config)
1116
+ self.num_labels = config.num_labels
1117
+ self.config = config
1118
+
1119
+ self.esm = EsmModel(config, add_pooling_layer=False)
1120
+ self.classifier = EsmClassificationHeadCustom(config)
1121
+
1122
+ self.init_weights()
1123
+
1124
+ @add_start_docstrings_to_model_forward(ESM_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1125
+ @add_code_sample_docstrings(
1126
+ processor_class=_TOKENIZER_FOR_DOC,
1127
+ checkpoint=_CHECKPOINT_FOR_DOC,
1128
+ output_type=SequenceClassifierOutput,
1129
+ config_class=_CONFIG_FOR_DOC,
1130
+ )
1131
+ def forward(
1132
+ self,
1133
+ input_ids: Optional[torch.LongTensor] = None,
1134
+ attention_mask: Optional[torch.Tensor] = None,
1135
+ position_ids: Optional[torch.LongTensor] = None,
1136
+ head_mask: Optional[torch.Tensor] = None,
1137
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1138
+ labels: Optional[torch.LongTensor] = None,
1139
+ output_attentions: Optional[bool] = None,
1140
+ output_hidden_states: Optional[bool] = None,
1141
+ return_dict: Optional[bool] = None,
1142
+ ) -> Union[Tuple, SequenceClassifierOutput]:
1143
+ r"""
1144
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1145
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1146
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1147
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1148
+ """
1149
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1150
+
1151
+ outputs = self.esm(
1152
+ input_ids,
1153
+ attention_mask=attention_mask,
1154
+ position_ids=position_ids,
1155
+ head_mask=head_mask,
1156
+ inputs_embeds=inputs_embeds,
1157
+ output_attentions=output_attentions,
1158
+ output_hidden_states=output_hidden_states,
1159
+ return_dict=return_dict,
1160
+ )
1161
+ sequence_output = outputs[0]
1162
+ logits = self.classifier(sequence_output)
1163
+
1164
+ loss = None
1165
+ if labels is not None:
1166
+ if self.config.problem_type is None:
1167
+ if self.num_labels == 1:
1168
+ self.config.problem_type = "regression"
1169
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1170
+ self.config.problem_type = "single_label_classification"
1171
+ else:
1172
+ self.config.problem_type = "multi_label_classification"
1173
+
1174
+ if self.config.problem_type == "regression":
1175
+ loss_fct = MSELoss()
1176
+ if self.num_labels == 1:
1177
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1178
+ else:
1179
+ loss = loss_fct(logits, labels)
1180
+ elif self.config.problem_type == "single_label_classification":
1181
+ loss_fct = CrossEntropyLoss()
1182
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1183
+ elif self.config.problem_type == "multi_label_classification":
1184
+ loss_fct = BCEWithLogitsLoss()
1185
+ loss = loss_fct(logits, labels)
1186
+
1187
+ if not return_dict:
1188
+ output = (logits,) + outputs[2:]
1189
+ return ((loss,) + output) if loss is not None else output
1190
+
1191
+ return SequenceClassifierOutput(
1192
+ loss=loss,
1193
+ logits=logits,
1194
+ hidden_states=outputs.hidden_states,
1195
+ attentions=outputs.attentions,
1196
+ )
1197
+
1198
+ #from model_outputs import SequenceClassifierOutputCustom
1199
+ @add_start_docstrings(
1200
+ """
1201
+ ESM Model transformer with a customized sequence classification/regression head on top (a linear layer on top of the pooled
1202
+ output) e.g. for GLUE tasks.
1203
+ """,
1204
+ ESM_START_DOCSTRING,
1205
+ )
1206
+ class EsmForSequenceClassificationMHACustom(EsmPreTrainedModel):
1207
+ _keys_to_ignore_on_load_missing = [r"position_ids"]
1208
+
1209
+ def __init__(self, config):
1210
+ super().__init__(config)
1211
+ self.num_labels = config.num_labels
1212
+ self.config = config
1213
+
1214
+ self.esm = EsmModel(config, add_pooling_layer=False)
1215
+ self.classifier = EsmClassificationHeadMHACustom(config)
1216
+
1217
+ self.init_weights()
1218
+
1219
+ @add_start_docstrings_to_model_forward(ESM_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1220
+ @add_code_sample_docstrings(
1221
+ processor_class=_TOKENIZER_FOR_DOC,
1222
+ checkpoint=_CHECKPOINT_FOR_DOC,
1223
+ output_type=SequenceClassifierOutput,
1224
+ config_class=_CONFIG_FOR_DOC,
1225
+ )
1226
+ def forward(
1227
+ self,
1228
+ input_ids: Optional[torch.LongTensor] = None,
1229
+ attention_mask: Optional[torch.Tensor] = None,
1230
+ position_ids: Optional[torch.LongTensor] = None,
1231
+ head_mask: Optional[torch.Tensor] = None,
1232
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1233
+ labels: Optional[torch.LongTensor] = None,
1234
+ output_attentions: Optional[bool] = None,
1235
+ output_hidden_states: Optional[bool] = None,
1236
+ return_dict: Optional[bool] = None,
1237
+ ) -> Union[Tuple, SequenceClassifierOutput]:
1238
+ r"""
1239
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1240
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1241
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1242
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1243
+ """
1244
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1245
+
1246
+ outputs = self.esm(
1247
+ input_ids,
1248
+ attention_mask=attention_mask,
1249
+ position_ids=position_ids,
1250
+ head_mask=head_mask,
1251
+ inputs_embeds=inputs_embeds,
1252
+ output_attentions=output_attentions,
1253
+ output_hidden_states=output_hidden_states,
1254
+ return_dict=return_dict,
1255
+ )
1256
+ sequence_output = outputs[0]
1257
+ logits, self.attn_outputs, self.attn_output_weights = self.classifier(sequence_output)
1258
+
1259
+ loss = None
1260
+ if labels is not None:
1261
+ if self.config.problem_type is None:
1262
+ if self.num_labels == 1:
1263
+ self.config.problem_type = "regression"
1264
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1265
+ self.config.problem_type = "single_label_classification"
1266
+ else:
1267
+ self.config.problem_type = "multi_label_classification"
1268
+
1269
+ if self.config.problem_type == "regression":
1270
+ loss_fct = MSELoss()
1271
+ if self.num_labels == 1:
1272
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1273
+ else:
1274
+ loss = loss_fct(logits, labels)
1275
+ elif self.config.problem_type == "single_label_classification":
1276
+ loss_fct = CrossEntropyLoss()
1277
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1278
+ elif self.config.problem_type == "multi_label_classification":
1279
+ loss_fct = BCEWithLogitsLoss()
1280
+ loss = loss_fct(logits, labels)
1281
+
1282
+ if not return_dict:
1283
+ output = (logits,) + outputs[2:]
1284
+ return ((loss,) + output) if loss is not None else output
1285
+
1286
+ return (SequenceClassifierOutput(
1287
+ loss=loss,
1288
+ logits=logits,
1289
+ hidden_states=outputs.hidden_states,
1290
+ attentions=outputs.attentions,
1291
+ ),
1292
+ self.attn_outputs, # classifier attn_outputs
1293
+ self.attn_output_weights, # classifier attn_output_weights
1294
+ )
1295
+
1296
+ @add_start_docstrings(
1297
+ """
1298
+ ESM Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1299
+ Named-Entity-Recognition (NER) tasks.
1300
+ """,
1301
+ ESM_START_DOCSTRING,
1302
+ )
1303
+ class EsmForTokenClassification(EsmPreTrainedModel):
1304
+ _keys_to_ignore_on_load_unexpected = [r"pooler"]
1305
+ _keys_to_ignore_on_load_missing = [r"position_ids"]
1306
+
1307
+ def __init__(self, config):
1308
+ super().__init__(config)
1309
+ self.num_labels = config.num_labels
1310
+
1311
+ self.esm = EsmModel(config, add_pooling_layer=False)
1312
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
1313
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1314
+
1315
+ self.init_weights()
1316
+
1317
+ @add_start_docstrings_to_model_forward(ESM_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1318
+ @add_code_sample_docstrings(
1319
+ processor_class=_TOKENIZER_FOR_DOC,
1320
+ checkpoint=_CHECKPOINT_FOR_DOC,
1321
+ output_type=TokenClassifierOutput,
1322
+ config_class=_CONFIG_FOR_DOC,
1323
+ )
1324
+ def forward(
1325
+ self,
1326
+ input_ids: Optional[torch.LongTensor] = None,
1327
+ attention_mask: Optional[torch.Tensor] = None,
1328
+ position_ids: Optional[torch.LongTensor] = None,
1329
+ head_mask: Optional[torch.Tensor] = None,
1330
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1331
+ labels: Optional[torch.LongTensor] = None,
1332
+ output_attentions: Optional[bool] = None,
1333
+ output_hidden_states: Optional[bool] = None,
1334
+ return_dict: Optional[bool] = None,
1335
+ ) -> Union[Tuple, TokenClassifierOutput]:
1336
+ r"""
1337
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1338
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1339
+ """
1340
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1341
+
1342
+ outputs = self.esm(
1343
+ input_ids,
1344
+ attention_mask=attention_mask,
1345
+ position_ids=position_ids,
1346
+ head_mask=head_mask,
1347
+ inputs_embeds=inputs_embeds,
1348
+ output_attentions=output_attentions,
1349
+ output_hidden_states=output_hidden_states,
1350
+ return_dict=return_dict,
1351
+ )
1352
+
1353
+ sequence_output = outputs[0]
1354
+
1355
+ sequence_output = self.dropout(sequence_output)
1356
+ logits = self.classifier(sequence_output)
1357
+
1358
+ loss = None
1359
+ if labels is not None:
1360
+ loss_fct = CrossEntropyLoss()
1361
+ # Only keep active parts of the loss
1362
+ if attention_mask is not None:
1363
+ active_loss = attention_mask.view(-1) == 1
1364
+ active_logits = logits.view(-1, self.num_labels)
1365
+ active_labels = torch.where(
1366
+ active_loss, labels.view(-1), torch.tensor(loss_fct.ignore_index).type_as(labels)
1367
+ )
1368
+ loss = loss_fct(active_logits, active_labels)
1369
+ else:
1370
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1371
+
1372
+ if not return_dict:
1373
+ output = (logits,) + outputs[2:]
1374
+ return ((loss,) + output) if loss is not None else output
1375
+
1376
+ return TokenClassifierOutput(
1377
+ loss=loss,
1378
+ logits=logits,
1379
+ hidden_states=outputs.hidden_states,
1380
+ attentions=outputs.attentions,
1381
+ )
1382
+
1383
+
1384
+ class EsmClassificationHead(nn.Module):
1385
+ """Head for sentence-level classification tasks."""
1386
+
1387
+ def __init__(self, config):
1388
+ super().__init__()
1389
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
1390
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
1391
+ self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
1392
+
1393
+ def forward(self, features, **kwargs):
1394
+ x = features[:, 0, :] # take <s> token (equiv. to [CLS])
1395
+ x = self.dropout(x)
1396
+ x = self.dense(x)
1397
+ x = torch.tanh(x)
1398
+ x = self.dropout(x)
1399
+ x = self.out_proj(x)
1400
+ return x
1401
+
1402
+
1403
+ class EsmClassificationHeadCustom(nn.Module):
1404
+ """Head for sentence-level classification tasks."""
1405
+
1406
+ def __init__(self, config):
1407
+ super().__init__()
1408
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
1409
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
1410
+ self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
1411
+
1412
+ def forward(self, features, **kwargs):
1413
+ x = features[:, 8, :] # take center substrate token
1414
+ x = self.dropout(x)
1415
+ x = self.dense(x)
1416
+ x = torch.tanh(x)
1417
+ x = self.dropout(x)
1418
+ x = self.out_proj(x)
1419
+ return x
1420
+
1421
+
1422
+ class EsmClassificationHeadMHACustom(nn.Module):
1423
+ """Head for sentence-level classification tasks."""
1424
+
1425
+ def __init__(self, config):
1426
+ super().__init__()
1427
+ self.multihead_attn = nn.MultiheadAttention(embed_dim = config.hidden_size, num_heads=8, batch_first=True)
1428
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
1429
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
1430
+ self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
1431
+
1432
+ def forward(self, features, **kwargs):
1433
+ x_substrate = features[:, :16, :]
1434
+ x_kinase = features[:, 16:, :]
1435
+ attn_output, attn_output_weights = self.multihead_attn(x_substrate, x_kinase, x_kinase)
1436
+ x = attn_output[:, 8, :] # take center substrate token
1437
+ x = self.dropout(x)
1438
+ x = self.dense(x)
1439
+ x = torch.tanh(x)
1440
+ x = self.dropout(x)
1441
+ x = self.out_proj(x)
1442
+ return x, attn_output, attn_output_weights
1443
+
1444
+ def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0):
1445
+ """
1446
+ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
1447
+ are ignored. This is modified from fairseq's `utils.make_positions`.
1448
+
1449
+ Args:
1450
+ x: torch.Tensor x:
1451
+
1452
+ Returns: torch.Tensor
1453
+ """
1454
+ # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
1455
+ mask = input_ids.ne(padding_idx).int()
1456
+ incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
1457
+ return incremental_indices.long() + padding_idx
1458
+
1459
+
1460
+
1461
+ class EsmClassificationHeadStructureCustom(nn.Module):
1462
+ """Head for sentence-level classification tasks."""
1463
+
1464
+ def __init__(self, config):
1465
+ super().__init__()
1466
+ self.dense = nn.Linear(config.input_size, config.hidden_size)
1467
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
1468
+ self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
1469
+
1470
+ def forward(self, features_sequence, features_structure, **kwargs):
1471
+ x = features_sequence[:, 8, :] # take center substrate token
1472
+ x = torch.cat([x, features_structure], 1)
1473
+ # print(x.shape)
1474
+ x = self.dropout(x)
1475
+ x = self.dense(x)
1476
+ x = torch.tanh(x)
1477
+ x = self.dropout(x)
1478
+ x = self.out_proj(x)
1479
+ return x
1480
+
1481
+
1482
+
1483
+
1484
+ # from kinasedb import KinaseDB_Uniport
1485
+ # # import torchdrug.datasets as tddatasets
1486
+ # from torchdrug import transforms as tdtransforms
1487
+ # # from torchdrug.data.protein import PackedProtein
1488
+
1489
+ # from torchdrug import layers as tdlayers
1490
+ # from torchdrug.layers import geometry as tdgeometry
1491
+ # from torchdrug.models import GearNet
1492
+ # from torchdrug import data as tddata
1493
+ # from torchdrug import utils as tdutils
1494
+
1495
+ # class EsmForSequenceClassificationStructureCustom(EsmPreTrainedModel):
1496
+ # _keys_to_ignore_on_load_missing = [r"position_ids"]
1497
+
1498
+ # def __init__(self, config):
1499
+ # super().__init__(config)
1500
+
1501
+ # self.num_labels = config.num_labels
1502
+ # self.config = config
1503
+ # self.config.input_size = self.config.hidden_size + 3072
1504
+ # self.esm = EsmModel(config, add_pooling_layer=False)
1505
+ # self.classifier = EsmClassificationHeadStructureCustom(config)
1506
+ # self.graph_construction_model = tdlayers.GraphConstruction(node_layers=[tdgeometry.AlphaCarbonNode()],
1507
+ # edge_layers=[tdgeometry.SpatialEdge(radius=10.0, min_distance=5),
1508
+ # tdgeometry.KNNEdge(k=10, min_distance=5),
1509
+ # tdgeometry.SequentialEdge(max_distance=2)],
1510
+ # edge_feature="gearnet")
1511
+ # truncuate_transform = tdtransforms.TruncateProtein(max_length=800, random=True)
1512
+ # protein_view_transform = tdtransforms.ProteinView(view='residue')
1513
+ # transform = tdtransforms.Compose([truncuate_transform, protein_view_transform])
1514
+
1515
+ # self.dataset_uniprot = KinaseDB_Uniport("../curated_dataset_waylandy/structure_dataset/", self.graph_construction_model, transform=transform, atom_feature=None, bond_feature=None)
1516
+ # self.gearnet_edge = GearNet(input_dim=21, hidden_dims=[512, 512, 512, 512, 512, 512],
1517
+ # num_relation=7, edge_input_dim=59, num_angle_bin=8,
1518
+ # batch_norm=True, concat_hidden=True, short_cut=True, readout="sum")
1519
+ # self.gearnet_edge.load_state_dict(torch.load("./mc_gearnet_edge.pth"), strict=False)
1520
+ # self.init_weights()
1521
+
1522
+ # def forward(
1523
+ # self,
1524
+ # input_ids: Optional[torch.LongTensor] = None,
1525
+ # kinase_id: Optional[torch.LongTensor] = None,
1526
+ # attention_mask: Optional[torch.Tensor] = None,
1527
+ # position_ids: Optional[torch.LongTensor] = None,
1528
+ # head_mask: Optional[torch.Tensor] = None,
1529
+ # inputs_embeds: Optional[torch.FloatTensor] = None,
1530
+ # labels: Optional[torch.LongTensor] = None,
1531
+ # output_attentions: Optional[bool] = None,
1532
+ # output_hidden_states: Optional[bool] = None,
1533
+ # return_dict: Optional[bool] = None,
1534
+ # ) -> Union[Tuple, SequenceClassifierOutput]:
1535
+ # r"""
1536
+ # labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1537
+ # Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1538
+ # config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1539
+ # `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1540
+ # """
1541
+ # return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1542
+
1543
+ # outputs = self.esm(
1544
+ # input_ids,
1545
+ # attention_mask=attention_mask,
1546
+ # position_ids=position_ids,
1547
+ # head_mask=head_mask,
1548
+ # inputs_embeds=inputs_embeds,
1549
+ # output_attentions=output_attentions,
1550
+ # output_hidden_states=output_hidden_states,
1551
+ # return_dict=return_dict,
1552
+ # )
1553
+ # sequence_output = outputs[0]
1554
+ # # print(kinase_id.tolist())
1555
+ # packedprotein = tddata.Protein.pack([self.dataset_uniprot.get_item(i)["graph"] for i in kinase_id.tolist()])
1556
+ # packedprotein = tdutils.cuda(packedprotein, device=self.device)
1557
+ # graph = self.graph_construction_model(packedprotein).cuda()
1558
+ # structure_output = self.gearnet_edge(graph, graph.node_feature.float())
1559
+
1560
+ # logits = self.classifier(sequence_output, structure_output["graph_feature"])
1561
+ # # print(logits.shape)
1562
+
1563
+ # loss = None
1564
+ # if labels is not None:
1565
+ # if self.config.problem_type is None:
1566
+ # if self.num_labels == 1:
1567
+ # self.config.problem_type = "regression"
1568
+ # elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1569
+ # self.config.problem_type = "single_label_classification"
1570
+ # else:
1571
+ # self.config.problem_type = "multi_label_classification"
1572
+
1573
+ # if self.config.problem_type == "regression":
1574
+ # loss_fct = MSELoss()
1575
+ # if self.num_labels == 1:
1576
+ # loss = loss_fct(logits.squeeze(), labels.squeeze())
1577
+ # else:
1578
+ # loss = loss_fct(logits, labels)
1579
+ # elif self.config.problem_type == "single_label_classification":
1580
+ # loss_fct = CrossEntropyLoss()
1581
+ # loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1582
+ # elif self.config.problem_type == "multi_label_classification":
1583
+ # loss_fct = BCEWithLogitsLoss()
1584
+ # loss = loss_fct(logits, labels)
1585
+
1586
+ # if not return_dict:
1587
+ # output = (logits,) + outputs[2:]
1588
+ # return ((loss,) + output) if loss is not None else output
1589
+
1590
+ # return SequenceClassifierOutput(
1591
+ # loss=loss,
1592
+ # logits=logits,
1593
+ # hidden_states=outputs.hidden_states,
1594
+ # attentions=outputs.attentions,
1595
+ # )
tokenization_esm.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 Meta and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Tokenization classes for ESM."""
16
+ import os
17
+ from typing import List, Optional, Union
18
+
19
+ from transformers.tokenization_utils import PreTrainedTokenizer
20
+ from transformers.tokenization_utils_base import AddedToken
21
+ from transformers.utils import logging
22
+
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt"}
27
+
28
+ PRETRAINED_VOCAB_FILES_MAP = {
29
+ "vocab_file": {
30
+ "facebook/esm2_t6_8M_UR50D": "https://huggingface.co/facebook/esm2_t6_8M_UR50D/resolve/main/vocab.txt",
31
+ "facebook/esm2_t12_35M_UR50D": "https://huggingface.co/facebook/esm2_t12_35M_UR50D/resolve/main/vocab.txt",
32
+ },
33
+ }
34
+
35
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
36
+ "facebook/esm2_t6_8M_UR50D": 1024,
37
+ "facebook/esm2_t12_35M_UR50D": 1024,
38
+ }
39
+
40
+
41
+ def load_vocab_file(vocab_file):
42
+ with open(vocab_file, "r") as f:
43
+ lines = f.read().splitlines()
44
+ return [l.strip() for l in lines]
45
+
46
+
47
+ class EsmTokenizer(PreTrainedTokenizer):
48
+ """
49
+ Constructs an ESM tokenizer.
50
+ """
51
+
52
+ vocab_files_names = VOCAB_FILES_NAMES
53
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
54
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
55
+ model_input_names = ["input_ids", "attention_mask"]
56
+
57
+ def __init__(self, vocab_file, **kwargs):
58
+ super().__init__(**kwargs)
59
+ self.all_tokens = load_vocab_file(vocab_file)
60
+ self._id_to_token = {ind: tok for ind, tok in enumerate(self.all_tokens)}
61
+ self._token_to_id = {tok: ind for ind, tok in enumerate(self.all_tokens)}
62
+ self.unk_token = "<unk>"
63
+ self.cls_token = "<cls>"
64
+ self.pad_token = "<pad>"
65
+ self.mask_token = "<mask>"
66
+ self.eos_token = "<eos>"
67
+ self.unique_no_split_tokens = self.all_tokens
68
+ self._create_trie(self.unique_no_split_tokens)
69
+
70
+ def _convert_id_to_token(self, index: int) -> str:
71
+ return self._id_to_token.get(index, self.unk_token)
72
+
73
+ def _convert_token_to_id(self, token: str) -> int:
74
+ return self._token_to_id.get(token, self._token_to_id.get(self.unk_token))
75
+
76
+ def _tokenize(self, text, **kwargs):
77
+ return text.split()
78
+
79
+ def get_vocab_size(self, with_added_tokens=False):
80
+ return len(self._id_to_token)
81
+
82
+ def get_vocab(self):
83
+ return {token: i for i, token in enumerate(self.all_tokens)}
84
+
85
+ def token_to_id(self, token: str) -> int:
86
+ return self._token_to_id.get(token, self._token_to_id.get(self.unk_token))
87
+
88
+ def id_to_token(self, index: int) -> str:
89
+ return self._id_to_token.get(index, self.unk_token)
90
+
91
+ def build_inputs_with_special_tokens(
92
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
93
+ ) -> List[int]:
94
+ if token_ids_1 is None:
95
+ return [self.cls_token_id] + token_ids_0 + [self.eos_token_id]
96
+ cls = [self.cls_token_id]
97
+ sep = [self.eos_token_id] # No sep token in ESM vocabulary
98
+ return cls + token_ids_0 + sep + token_ids_1 + sep
99
+
100
+ def get_special_tokens_mask(
101
+ self, token_ids_0: List, token_ids_1: Optional[List] = None, already_has_special_tokens: bool = False
102
+ ) -> List[int]:
103
+ """
104
+ Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
105
+ special tokens using the tokenizer `prepare_for_model` or `encode_plus` methods.
106
+
107
+ Args:
108
+ token_ids_0 (`List[int]`):
109
+ List of ids of the first sequence.
110
+ token_ids_1 (`List[int]`, *optional*):
111
+ List of ids of the second sequence.
112
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
113
+ Whether or not the token list is already formatted with special tokens for the model.
114
+
115
+ Returns:
116
+ A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
117
+ """
118
+ if already_has_special_tokens:
119
+ if token_ids_1 is not None:
120
+ raise ValueError(
121
+ "You should not supply a second sequence if the provided sequence of "
122
+ "ids is already formatted with special tokens for the model."
123
+ )
124
+
125
+ return [1 if token in self.all_special_ids else 0 for token in token_ids_0]
126
+ mask = [1] + ([0] * len(token_ids_0)) + [1]
127
+ if token_ids_1 is not None:
128
+ mask += [0] * len(token_ids_1) + [1]
129
+ return mask
130
+
131
+ def save_vocabulary(self, save_directory, filename_prefix):
132
+ vocab_file = os.path.join(save_directory, (filename_prefix + "-" if filename_prefix else "") + "vocab.txt")
133
+ with open(vocab_file, "w") as f:
134
+ f.write("\n".join(self.all_tokens))
135
+ return (vocab_file,)
136
+
137
+ @property
138
+ def vocab_size(self) -> int:
139
+ return self.get_vocab_size(with_added_tokens=False)
140
+
141
+ def _add_tokens(self, new_tokens: Union[List[str], List[AddedToken]], special_tokens: bool = False) -> int:
142
+ return super()._add_tokens(new_tokens, special_tokens=True)