gravelcompbio commited on
Commit
b32e81c
·
verified ·
1 Parent(s): 1c586cc

Upload modeling_esm.py

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