sboshar commited on
Commit
bd00359
1 Parent(s): ea54d02

Upload 2 files

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