ssyypp111 commited on
Commit
021062b
·
verified ·
1 Parent(s): 95ef3b5

Upload modeling_esm.py

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