etrop commited on
Commit
4f8c857
1 Parent(s): f1c99d0

ESM Config and Model definition script

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