isoformer-anonymous commited on
Commit
0e799f0
1 Parent(s): c672a56

Add model files for esm and NT

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