isoformer-anonymous commited on
Commit
33742a2
1 Parent(s): 13a7e78

Upload modeling_esm.py

Browse files
Files changed (1) hide show
  1. modeling_esm.py +1620 -0
modeling_esm.py 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