GinnM commited on
Commit
b76e90d
·
verified ·
1 Parent(s): b199e08

Upload ProPrimeForPretraining

Browse files
Files changed (3) hide show
  1. config.json +1 -0
  2. model.safetensors +3 -0
  3. modeling_proprime.py +1345 -0
config.json CHANGED
@@ -6,6 +6,7 @@
6
  "attention_probs_dropout_prob": 0.0,
7
  "auto_map": {
8
  "AutoConfig": "configuration_proprime.ProPrimeConfig",
 
9
  "AutoModelForMaskedLM": "AI4Protein/ProPrime_650M--modeling_proprime.ProPrimeForMaskedLM"
10
  },
11
  "emb_layer_norm_before": false,
 
6
  "attention_probs_dropout_prob": 0.0,
7
  "auto_map": {
8
  "AutoConfig": "configuration_proprime.ProPrimeConfig",
9
+ "AutoModel": "modeling_proprime.ProPrimeForPretraining",
10
  "AutoModelForMaskedLM": "AI4Protein/ProPrime_650M--modeling_proprime.ProPrimeForMaskedLM"
11
  },
12
  "emb_layer_norm_before": false,
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:33c732ac89d871c8ec6ed53f710e03241c251865c52670f50ce7ae57d6293071
3
+ size 2676905476
modeling_proprime.py ADDED
@@ -0,0 +1,1345 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from typing import List, Optional, Tuple, Union
3
+ import torch.nn.functional as F
4
+ import torch
5
+ import torch.utils.checkpoint
6
+ from torch import nn
7
+ from torch.nn import CrossEntropyLoss
8
+ from dataclasses import dataclass
9
+ from transformers.modeling_outputs import (
10
+ BaseModelOutputWithPastAndCrossAttentions,
11
+ BaseModelOutputWithPoolingAndCrossAttentions,
12
+ MaskedLMOutput,
13
+ ModelOutput,
14
+ )
15
+ from transformers.modeling_utils import (
16
+ PreTrainedModel,
17
+ find_pruneable_heads_and_indices,
18
+ prune_linear_layer,
19
+ )
20
+ from transformers.utils import logging
21
+ from .configuration_proprime import ProPrimeConfig
22
+ from torch.nn.functional import scaled_dot_product_attention
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+
27
+ def consine_based_loss(x1, x2):
28
+ cos = nn.CosineSimilarity(dim=0, eps=1e-6)
29
+ x1 = x1 - x1.mean()
30
+ x2 = x2 - x2.mean()
31
+ return 1 - cos(x1, x2).mean()
32
+
33
+ PROPRIME_PRETRAINED_MODEL_ARCHIVE_LIST = [
34
+ "AI4protein/ProPrime_650M",
35
+ ]
36
+
37
+
38
+ def rotate_half(x):
39
+ return torch.cat((-x[..., x.shape[-1] // 2 :], x[..., : x.shape[-1] // 2]), dim=-1)
40
+
41
+
42
+ def apply_rotary_pos_emb(x, cos, sin):
43
+ cos = cos[:, :, : x.shape[-2], :]
44
+ sin = sin[:, :, : x.shape[-2], :]
45
+ return (x * cos) + (rotate_half(x) * sin)
46
+
47
+
48
+ def gelu(x):
49
+ return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0)))
50
+
51
+
52
+ class RotaryEmbedding(torch.nn.Module):
53
+ def __init__(self, dim: int):
54
+ super().__init__()
55
+ # Generate and save the inverse frequency buffer (non trainable)
56
+ inv_freq = 1.0 / (
57
+ 10000 ** (torch.arange(0, dim, 2, dtype=torch.int64).float() / dim)
58
+ )
59
+ inv_freq = inv_freq
60
+ self.register_buffer("inv_freq", inv_freq)
61
+
62
+ self._seq_len_cached = None
63
+ self._cos_cached = None
64
+ self._sin_cached = None
65
+
66
+ def _update_cos_sin_tables(self, x, seq_dimension=2):
67
+ seq_len = x.shape[seq_dimension]
68
+
69
+ # Reset the tables if the sequence length has changed,
70
+ # or if we're on a new device (possibly due to tracing for instance)
71
+ if seq_len != self._seq_len_cached or self._cos_cached.device != x.device:
72
+ self._seq_len_cached = seq_len
73
+ t = torch.arange(x.shape[seq_dimension], device=x.device).type_as(
74
+ self.inv_freq
75
+ )
76
+ freqs = torch.outer(t, self.inv_freq)
77
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
78
+
79
+ self._cos_cached = emb.cos()[None, None, :, :]
80
+ self._sin_cached = emb.sin()[None, None, :, :]
81
+
82
+ return self._cos_cached, self._sin_cached
83
+
84
+ def forward(
85
+ self, q: torch.Tensor, k: torch.Tensor
86
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
87
+ self._cos_cached, self._sin_cached = self._update_cos_sin_tables(
88
+ k, seq_dimension=-2
89
+ )
90
+
91
+ return (
92
+ apply_rotary_pos_emb(q, self._cos_cached, self._sin_cached),
93
+ apply_rotary_pos_emb(k, self._cos_cached, self._sin_cached),
94
+ )
95
+
96
+
97
+ class ProPrimeEmbeddings(nn.Module):
98
+
99
+ def __init__(self, config):
100
+ super().__init__()
101
+ self.word_embeddings = nn.Embedding(
102
+ config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id
103
+ )
104
+
105
+ if config.emb_layer_norm_before:
106
+ self.layer_norm = nn.LayerNorm(
107
+ config.hidden_size, eps=config.layer_norm_eps
108
+ )
109
+ else:
110
+ self.layer_norm = None
111
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
112
+ self.position_embedding_type = getattr(
113
+ config, "position_embedding_type", "absolute"
114
+ )
115
+ self.register_buffer(
116
+ "position_ids",
117
+ torch.arange(config.max_position_embeddings).expand((1, -1)),
118
+ persistent=False,
119
+ )
120
+
121
+ self.padding_idx = config.pad_token_id
122
+ if self.position_embedding_type == "absolute":
123
+ self.position_embeddings = nn.Embedding(
124
+ config.max_position_embeddings,
125
+ config.hidden_size,
126
+ padding_idx=self.padding_idx,
127
+ )
128
+ self.token_dropout = config.token_dropout
129
+ self.mask_token_id = config.mask_token_id
130
+
131
+ def forward(
132
+ self,
133
+ input_ids=None,
134
+ attention_mask=None,
135
+ position_ids=None,
136
+ inputs_embeds=None,
137
+ past_key_values_length=0,
138
+ ):
139
+ if position_ids is None:
140
+ if input_ids is not None:
141
+ position_ids = create_position_ids_from_input_ids(
142
+ input_ids, self.padding_idx, past_key_values_length
143
+ )
144
+ else:
145
+ position_ids = self.create_position_ids_from_inputs_embeds(
146
+ inputs_embeds
147
+ )
148
+
149
+ if inputs_embeds is None:
150
+ inputs_embeds = self.word_embeddings(input_ids)
151
+
152
+ embeddings = inputs_embeds
153
+
154
+ if self.token_dropout:
155
+ embeddings = embeddings.masked_fill(
156
+ (input_ids == self.mask_token_id).unsqueeze(-1), 0.0
157
+ )
158
+ mask_ratio_train = 0.15 * 0.8
159
+ src_lengths = attention_mask.sum(-1)
160
+ mask_ratio_observed = (input_ids == self.mask_token_id).sum(
161
+ -1
162
+ ).float() / src_lengths
163
+ embeddings = (
164
+ embeddings
165
+ * (1 - mask_ratio_train)
166
+ / (1 - mask_ratio_observed)[:, None, None]
167
+ ).to(embeddings.dtype)
168
+
169
+ if self.position_embedding_type == "absolute":
170
+ position_embeddings = self.position_embeddings(position_ids)
171
+ embeddings = embeddings + position_embeddings
172
+
173
+ if self.layer_norm is not None:
174
+ embeddings = self.layer_norm(embeddings)
175
+ if attention_mask is not None:
176
+ embeddings = (embeddings * attention_mask.unsqueeze(-1)).to(
177
+ embeddings.dtype
178
+ )
179
+ # Matt: I think this line was copied incorrectly from BERT, disabling it for now.
180
+ # embeddings = self.dropout(embeddings)
181
+ return embeddings
182
+
183
+ def create_position_ids_from_inputs_embeds(self, inputs_embeds):
184
+ input_shape = inputs_embeds.size()[:-1]
185
+ sequence_length = input_shape[1]
186
+
187
+ position_ids = torch.arange(
188
+ self.padding_idx + 1,
189
+ sequence_length + self.padding_idx + 1,
190
+ dtype=torch.long,
191
+ device=inputs_embeds.device,
192
+ )
193
+ return position_ids.unsqueeze(0).expand(input_shape)
194
+
195
+
196
+ class ProPrimeSelfAttention(nn.Module):
197
+ def __init__(self, config, position_embedding_type=None):
198
+ super().__init__()
199
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(
200
+ config, "embedding_size"
201
+ ):
202
+ raise ValueError(
203
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
204
+ f"heads ({config.num_attention_heads})"
205
+ )
206
+
207
+ self.num_attention_heads = config.num_attention_heads
208
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
209
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
210
+
211
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
212
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
213
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
214
+
215
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
216
+ self.position_embedding_type = position_embedding_type or getattr(
217
+ config, "position_embedding_type", "absolute"
218
+ )
219
+ self.rotary_embeddings = None
220
+ if (
221
+ self.position_embedding_type == "relative_key"
222
+ or self.position_embedding_type == "relative_key_query"
223
+ ):
224
+ self.max_position_embeddings = config.max_position_embeddings
225
+ self.distance_embedding = nn.Embedding(
226
+ 2 * config.max_position_embeddings - 1, self.attention_head_size
227
+ )
228
+ elif self.position_embedding_type == "rotary":
229
+ self.rotary_embeddings = RotaryEmbedding(dim=self.attention_head_size)
230
+ self.flash_attention = config.flash_attention
231
+ self.is_decoder = config.is_decoder
232
+ self.config = config
233
+
234
+ def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
235
+ new_x_shape = x.size()[:-1] + (
236
+ self.num_attention_heads,
237
+ self.attention_head_size,
238
+ )
239
+ x = x.view(new_x_shape)
240
+ return x.permute(0, 2, 1, 3)
241
+
242
+ def forward(
243
+ self,
244
+ hidden_states: torch.Tensor,
245
+ attention_mask: Optional[torch.FloatTensor] = None,
246
+ head_mask: Optional[torch.FloatTensor] = None,
247
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
248
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
249
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
250
+ output_attentions: Optional[bool] = False,
251
+ ) -> Tuple[torch.Tensor]:
252
+ mixed_query_layer = self.query(hidden_states)
253
+
254
+ # If this is instantiated as a cross-attention module, the keys
255
+ # and values come from an encoder; the attention mask needs to be
256
+ # such that the encoder's padding tokens are not attended to.
257
+ is_cross_attention = encoder_hidden_states is not None
258
+
259
+ if is_cross_attention and past_key_value is not None:
260
+ # reuse k,v, cross_attentions
261
+ key_layer = past_key_value[0]
262
+ value_layer = past_key_value[1]
263
+ attention_mask = encoder_attention_mask
264
+ elif is_cross_attention:
265
+ key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
266
+ value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
267
+ attention_mask = encoder_attention_mask
268
+ elif past_key_value is not None:
269
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
270
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
271
+ key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
272
+ value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
273
+ else:
274
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
275
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
276
+
277
+ query_layer = self.transpose_for_scores(mixed_query_layer)
278
+
279
+ query_layer = query_layer * self.attention_head_size**-0.5
280
+
281
+ if self.is_decoder:
282
+ past_key_value = (key_layer, value_layer)
283
+
284
+ if self.position_embedding_type == "rotary":
285
+ query_layer, key_layer = self.rotary_embeddings(query_layer, key_layer)
286
+
287
+ if not self.flash_attention:
288
+ # Take the dot product between "query" and "key" to get the raw attention scores.
289
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
290
+
291
+ if (
292
+ self.position_embedding_type == "relative_key"
293
+ or self.position_embedding_type == "relative_key_query"
294
+ ):
295
+ seq_length = hidden_states.size()[1]
296
+ position_ids_l = torch.arange(
297
+ seq_length, dtype=torch.long, device=hidden_states.device
298
+ ).view(-1, 1)
299
+ position_ids_r = torch.arange(
300
+ seq_length, dtype=torch.long, device=hidden_states.device
301
+ ).view(1, -1)
302
+ distance = position_ids_l - position_ids_r
303
+ positional_embedding = self.distance_embedding(
304
+ distance + self.max_position_embeddings - 1
305
+ )
306
+ positional_embedding = positional_embedding.to(
307
+ dtype=query_layer.dtype
308
+ ) # fp16 compatibility
309
+
310
+ if self.position_embedding_type == "relative_key":
311
+ relative_position_scores = torch.einsum(
312
+ "bhld,lrd->bhlr", query_layer, positional_embedding
313
+ )
314
+ attention_scores = attention_scores + relative_position_scores
315
+ elif self.position_embedding_type == "relative_key_query":
316
+ relative_position_scores_query = torch.einsum(
317
+ "bhld,lrd->bhlr", query_layer, positional_embedding
318
+ )
319
+ relative_position_scores_key = torch.einsum(
320
+ "bhrd,lrd->bhlr", key_layer, positional_embedding
321
+ )
322
+ attention_scores = (
323
+ attention_scores
324
+ + relative_position_scores_query
325
+ + relative_position_scores_key
326
+ )
327
+
328
+ if attention_mask is not None:
329
+ attention_scores = attention_scores + attention_mask
330
+
331
+ # Normalize the attention scores to probabilities.
332
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
333
+
334
+ # This is actually dropping out entire tokens to attend to, which might
335
+ # seem a bit unusual, but is taken from the original Transformer paper.
336
+ attention_probs = self.dropout(attention_probs)
337
+
338
+ # Mask heads if we want to
339
+ if head_mask is not None:
340
+ attention_probs = attention_probs * head_mask
341
+
342
+ context_layer = torch.matmul(attention_probs, value_layer)
343
+ else:
344
+ if self.training:
345
+ context_layer = scaled_dot_product_attention(
346
+ query_layer,
347
+ key_layer,
348
+ value_layer,
349
+ attn_mask=attention_mask,
350
+ dropout_p=self.config.attention_probs_dropout_prob,
351
+ scale=1, # we have query_layer = query_layer * self.attention_head_size**-0.5
352
+ )
353
+ else:
354
+ context_layer = scaled_dot_product_attention(
355
+ query_layer,
356
+ key_layer,
357
+ value_layer,
358
+ attn_mask=attention_mask,
359
+ scale=1, # we have query_layer = query_layer * self.attention_head_size**-0.5
360
+ )
361
+
362
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
363
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
364
+ context_layer = context_layer.view(new_context_layer_shape)
365
+
366
+ outputs = (
367
+ (context_layer, attention_probs) if output_attentions else (context_layer,)
368
+ )
369
+
370
+ if self.is_decoder:
371
+ outputs = outputs + (past_key_value,)
372
+ return outputs
373
+
374
+
375
+ class ProPrimeSelfOutput(nn.Module):
376
+ def __init__(self, config):
377
+ super().__init__()
378
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
379
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
380
+
381
+ def forward(self, hidden_states, input_tensor):
382
+ hidden_states = self.dense(hidden_states)
383
+ hidden_states = self.dropout(hidden_states)
384
+ hidden_states = hidden_states + input_tensor
385
+ return hidden_states
386
+
387
+
388
+ class ProPrimeAttention(nn.Module):
389
+ def __init__(self, config):
390
+ super().__init__()
391
+ self.self = ProPrimeSelfAttention(config)
392
+ self.output = ProPrimeSelfOutput(config)
393
+ self.pruned_heads = set()
394
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
395
+
396
+ def prune_heads(self, heads):
397
+ if len(heads) == 0:
398
+ return
399
+ heads, index = find_pruneable_heads_and_indices(
400
+ heads,
401
+ self.self.num_attention_heads,
402
+ self.self.attention_head_size,
403
+ self.pruned_heads,
404
+ )
405
+
406
+ # Prune linear layers
407
+ self.self.query = prune_linear_layer(self.self.query, index)
408
+ self.self.key = prune_linear_layer(self.self.key, index)
409
+ self.self.value = prune_linear_layer(self.self.value, index)
410
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
411
+
412
+ # Update hyper params and store pruned heads
413
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
414
+ self.self.all_head_size = (
415
+ self.self.attention_head_size * self.self.num_attention_heads
416
+ )
417
+ self.pruned_heads = self.pruned_heads.union(heads)
418
+
419
+ def forward(
420
+ self,
421
+ hidden_states,
422
+ attention_mask=None,
423
+ head_mask=None,
424
+ encoder_hidden_states=None,
425
+ encoder_attention_mask=None,
426
+ past_key_value=None,
427
+ output_attentions=False,
428
+ ):
429
+ hidden_states_ln = self.LayerNorm(hidden_states)
430
+ self_outputs = self.self(
431
+ hidden_states_ln,
432
+ attention_mask,
433
+ head_mask,
434
+ encoder_hidden_states,
435
+ encoder_attention_mask,
436
+ past_key_value,
437
+ output_attentions,
438
+ )
439
+ attention_output = self.output(self_outputs[0], hidden_states)
440
+ outputs = (attention_output,) + self_outputs[
441
+ 1:
442
+ ] # add attentions if we output them
443
+ return outputs
444
+
445
+
446
+ class ProPrimeIntermediate(nn.Module):
447
+ def __init__(self, config):
448
+ super().__init__()
449
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
450
+
451
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
452
+ hidden_states = self.dense(hidden_states)
453
+ hidden_states = gelu(hidden_states)
454
+ return hidden_states
455
+
456
+
457
+ class ProPrimeOutput(nn.Module):
458
+ def __init__(self, config):
459
+ super().__init__()
460
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
461
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
462
+
463
+ def forward(self, hidden_states, input_tensor):
464
+ hidden_states = self.dense(hidden_states)
465
+ hidden_states = self.dropout(hidden_states)
466
+ hidden_states = hidden_states + input_tensor
467
+ return hidden_states
468
+
469
+
470
+ class ProPrimeLayer(nn.Module):
471
+ def __init__(self, config):
472
+ super().__init__()
473
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
474
+ self.seq_len_dim = 1
475
+ self.attention = ProPrimeAttention(config)
476
+ self.is_decoder = config.is_decoder
477
+ self.add_cross_attention = config.add_cross_attention
478
+ if self.add_cross_attention:
479
+ if not self.is_decoder:
480
+ raise RuntimeError(
481
+ f"{self} should be used as a decoder model if cross attention is added"
482
+ )
483
+ self.crossattention = ProPrimeAttention(config)
484
+ self.intermediate = ProPrimeIntermediate(config)
485
+ self.output = ProPrimeOutput(config)
486
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
487
+
488
+ def forward(
489
+ self,
490
+ hidden_states,
491
+ attention_mask=None,
492
+ head_mask=None,
493
+ encoder_hidden_states=None,
494
+ encoder_attention_mask=None,
495
+ past_key_value=None,
496
+ output_attentions=False,
497
+ ):
498
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
499
+ self_attn_past_key_value = (
500
+ past_key_value[:2] if past_key_value is not None else None
501
+ )
502
+ self_attention_outputs = self.attention(
503
+ hidden_states,
504
+ attention_mask,
505
+ head_mask,
506
+ output_attentions=output_attentions,
507
+ past_key_value=self_attn_past_key_value,
508
+ )
509
+ attention_output = self_attention_outputs[0]
510
+
511
+ # if decoder, the last output is tuple of self-attn cache
512
+ if self.is_decoder:
513
+ outputs = self_attention_outputs[1:-1]
514
+ present_key_value = self_attention_outputs[-1]
515
+ else:
516
+ outputs = self_attention_outputs[
517
+ 1:
518
+ ] # add self attentions if we output attention weights
519
+
520
+ cross_attn_present_key_value = None
521
+ if self.is_decoder and encoder_hidden_states is not None:
522
+ if not hasattr(self, "crossattention"):
523
+ raise AttributeError(
524
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated"
525
+ " with cross-attention layers by setting `config.add_cross_attention=True`"
526
+ )
527
+
528
+ # cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple
529
+ cross_attn_past_key_value = (
530
+ past_key_value[-2:] if past_key_value is not None else None
531
+ )
532
+ cross_attention_outputs = self.crossattention(
533
+ attention_output,
534
+ attention_mask,
535
+ head_mask,
536
+ encoder_hidden_states,
537
+ encoder_attention_mask,
538
+ cross_attn_past_key_value,
539
+ output_attentions,
540
+ )
541
+ attention_output = cross_attention_outputs[0]
542
+ outputs = (
543
+ outputs + cross_attention_outputs[1:-1]
544
+ ) # add cross attentions if we output attention weights
545
+
546
+ # add cross-attn cache to positions 3,4 of present_key_value tuple
547
+ cross_attn_present_key_value = cross_attention_outputs[-1]
548
+ present_key_value = present_key_value + cross_attn_present_key_value
549
+
550
+ layer_output = self.feed_forward_chunk(attention_output)
551
+
552
+ outputs = (layer_output,) + outputs
553
+
554
+ # if decoder, return the attn key/values as the last output
555
+ if self.is_decoder:
556
+ outputs = outputs + (present_key_value,)
557
+ return outputs
558
+
559
+ def feed_forward_chunk(self, attention_output):
560
+ attention_output_ln = self.LayerNorm(attention_output)
561
+ intermediate_output = self.intermediate(attention_output_ln)
562
+ layer_output = self.output(intermediate_output, attention_output)
563
+ return layer_output
564
+
565
+
566
+ class ProPrimeEncoder(nn.Module):
567
+ def __init__(self, config):
568
+ super().__init__()
569
+ self.config = config
570
+ self.layer = nn.ModuleList(
571
+ [ProPrimeLayer(config) for _ in range(config.num_hidden_layers)]
572
+ )
573
+ self.emb_layer_norm_after = nn.LayerNorm(
574
+ config.hidden_size, eps=config.layer_norm_eps
575
+ )
576
+ self.gradient_checkpointing = False
577
+
578
+ def forward(
579
+ self,
580
+ hidden_states,
581
+ attention_mask=None,
582
+ head_mask=None,
583
+ encoder_hidden_states=None,
584
+ encoder_attention_mask=None,
585
+ past_key_values=None,
586
+ use_cache=None,
587
+ output_attentions=False,
588
+ output_hidden_states=False,
589
+ return_dict=True,
590
+ ):
591
+ if self.gradient_checkpointing and self.training:
592
+ if use_cache:
593
+ logger.warning_once(
594
+ "`use_cache=True` is incompatible with `config.gradient_checkpointing=True`. Setting "
595
+ "`use_cache=False`..."
596
+ )
597
+ use_cache = False
598
+ all_hidden_states = () if output_hidden_states else None
599
+ all_self_attentions = () if output_attentions else None
600
+ all_cross_attentions = (
601
+ () if output_attentions and self.config.add_cross_attention else None
602
+ )
603
+
604
+ next_decoder_cache = () if use_cache else None
605
+ for i, layer_module in enumerate(self.layer):
606
+ if output_hidden_states:
607
+ all_hidden_states = all_hidden_states + (hidden_states,)
608
+
609
+ layer_head_mask = head_mask[i] if head_mask is not None else None
610
+ past_key_value = past_key_values[i] if past_key_values is not None else None
611
+
612
+ if self.gradient_checkpointing and self.training:
613
+ layer_outputs = self._gradient_checkpointing_func(
614
+ layer_module.__call__,
615
+ hidden_states,
616
+ attention_mask,
617
+ layer_head_mask,
618
+ encoder_hidden_states,
619
+ encoder_attention_mask,
620
+ past_key_value,
621
+ output_attentions,
622
+ )
623
+ else:
624
+ layer_outputs = layer_module(
625
+ hidden_states,
626
+ attention_mask,
627
+ layer_head_mask,
628
+ encoder_hidden_states,
629
+ encoder_attention_mask,
630
+ past_key_value,
631
+ output_attentions,
632
+ )
633
+
634
+ hidden_states = layer_outputs[0]
635
+ if use_cache:
636
+ next_decoder_cache = next_decoder_cache + (layer_outputs[-1],)
637
+ if output_attentions:
638
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
639
+ if self.config.add_cross_attention:
640
+ all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
641
+
642
+ if self.emb_layer_norm_after:
643
+ hidden_states = self.emb_layer_norm_after(hidden_states)
644
+
645
+ if output_hidden_states:
646
+ all_hidden_states = all_hidden_states + (hidden_states,)
647
+
648
+ if not return_dict:
649
+ return tuple(
650
+ v
651
+ for v in [
652
+ hidden_states,
653
+ next_decoder_cache,
654
+ all_hidden_states,
655
+ all_self_attentions,
656
+ all_cross_attentions,
657
+ ]
658
+ if v is not None
659
+ )
660
+ return BaseModelOutputWithPastAndCrossAttentions(
661
+ last_hidden_state=hidden_states,
662
+ past_key_values=next_decoder_cache,
663
+ hidden_states=all_hidden_states,
664
+ attentions=all_self_attentions,
665
+ cross_attentions=all_cross_attentions,
666
+ )
667
+
668
+
669
+ class ProPrimePreTrainedModel(PreTrainedModel):
670
+ """
671
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
672
+ models.
673
+ """
674
+
675
+ config_class = ProPrimeConfig
676
+ base_model_prefix = "proprime"
677
+ supports_gradient_checkpointing = True
678
+ _no_split_modules = [
679
+ "ProPrimeLayer",
680
+ "ProPrimeEmbeddings",
681
+ ]
682
+
683
+ # Copied from transformers.models.bert.modeling_bert.BertPreTrainedModel._init_weights
684
+ def _init_weights(self, module):
685
+ """Initialize the weights"""
686
+ if isinstance(module, nn.Linear):
687
+ # Slightly different from the TF version which uses truncated_normal for initialization
688
+ # cf https://github.com/pytorch/pytorch/pull/5617
689
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
690
+ if module.bias is not None:
691
+ module.bias.data.zero_()
692
+ elif isinstance(module, nn.Embedding):
693
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
694
+ if module.padding_idx is not None:
695
+ module.weight.data[module.padding_idx].zero_()
696
+ elif isinstance(module, nn.LayerNorm):
697
+ module.bias.data.zero_()
698
+ module.weight.data.fill_(1.0)
699
+
700
+
701
+ class ProPrimeModel(ProPrimePreTrainedModel):
702
+ base_model_prefix = "proprime"
703
+
704
+ def __init__(self, config, add_pooling_layer=True):
705
+ super().__init__(config)
706
+ self.config = config
707
+ self.embeddings = ProPrimeEmbeddings(config)
708
+ self.encoder = ProPrimeEncoder(config)
709
+ self.post_init()
710
+
711
+ def get_input_embeddings(self):
712
+ return self.embeddings.word_embeddings
713
+
714
+ def set_input_embeddings(self, value):
715
+ self.embeddings.word_embeddings = value
716
+
717
+ def _prune_heads(self, heads_to_prune):
718
+ """
719
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
720
+ class PreTrainedModel
721
+ """
722
+ for layer, heads in heads_to_prune.items():
723
+ self.encoder.layer[layer].attention.prune_heads(heads)
724
+
725
+ def forward(
726
+ self,
727
+ input_ids: Optional[torch.Tensor] = None,
728
+ attention_mask: Optional[torch.Tensor] = None,
729
+ position_ids: Optional[torch.Tensor] = None,
730
+ head_mask: Optional[torch.Tensor] = None,
731
+ inputs_embeds: Optional[torch.Tensor] = None,
732
+ encoder_hidden_states: Optional[torch.Tensor] = None,
733
+ encoder_attention_mask: Optional[torch.Tensor] = None,
734
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
735
+ use_cache: Optional[bool] = None,
736
+ output_attentions: Optional[bool] = None,
737
+ output_hidden_states: Optional[bool] = None,
738
+ return_dict: Optional[bool] = None,
739
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
740
+ output_attentions = (
741
+ output_attentions
742
+ if output_attentions is not None
743
+ else self.config.output_attentions
744
+ )
745
+ output_hidden_states = (
746
+ output_hidden_states
747
+ if output_hidden_states is not None
748
+ else self.config.output_hidden_states
749
+ )
750
+ return_dict = (
751
+ return_dict if return_dict is not None else self.config.use_return_dict
752
+ )
753
+
754
+ if self.config.is_decoder:
755
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
756
+ else:
757
+ use_cache = False
758
+
759
+ if input_ids is not None and inputs_embeds is not None:
760
+ raise ValueError(
761
+ "You cannot specify both input_ids and inputs_embeds at the same time"
762
+ )
763
+ elif input_ids is not None:
764
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
765
+ input_shape = input_ids.size()
766
+ elif inputs_embeds is not None:
767
+ input_shape = inputs_embeds.size()[:-1]
768
+ else:
769
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
770
+
771
+ batch_size, seq_length = input_shape
772
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
773
+
774
+ # past_key_values_length
775
+ past_key_values_length = (
776
+ past_key_values[0][0].shape[2] if past_key_values is not None else 0
777
+ )
778
+
779
+ if attention_mask is None:
780
+ attention_mask = torch.ones(
781
+ ((batch_size, seq_length + past_key_values_length)), device=device
782
+ )
783
+
784
+ extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(
785
+ attention_mask, input_shape
786
+ )
787
+
788
+ if self.config.is_decoder and encoder_hidden_states is not None:
789
+ encoder_batch_size, encoder_sequence_length, _ = (
790
+ encoder_hidden_states.size()
791
+ )
792
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
793
+ if encoder_attention_mask is None:
794
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
795
+ encoder_extended_attention_mask = self.invert_attention_mask(
796
+ encoder_attention_mask
797
+ )
798
+ else:
799
+ encoder_extended_attention_mask = None
800
+
801
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
802
+
803
+ embedding_output = self.embeddings(
804
+ input_ids=input_ids,
805
+ position_ids=position_ids,
806
+ attention_mask=attention_mask,
807
+ inputs_embeds=inputs_embeds,
808
+ past_key_values_length=past_key_values_length,
809
+ )
810
+ encoder_outputs = self.encoder(
811
+ embedding_output,
812
+ attention_mask=extended_attention_mask,
813
+ head_mask=head_mask,
814
+ encoder_hidden_states=encoder_hidden_states,
815
+ encoder_attention_mask=encoder_extended_attention_mask,
816
+ past_key_values=past_key_values,
817
+ use_cache=use_cache,
818
+ output_attentions=output_attentions,
819
+ output_hidden_states=output_hidden_states,
820
+ return_dict=return_dict,
821
+ )
822
+ sequence_output = encoder_outputs[0]
823
+
824
+ return BaseModelOutputWithPoolingAndCrossAttentions(
825
+ last_hidden_state=sequence_output,
826
+ past_key_values=encoder_outputs.past_key_values,
827
+ hidden_states=encoder_outputs.hidden_states,
828
+ attentions=encoder_outputs.attentions,
829
+ cross_attentions=encoder_outputs.cross_attentions,
830
+ )
831
+
832
+
833
+ class ProPrimeForMaskedLM(ProPrimePreTrainedModel):
834
+ _tied_weights_keys = ["lm_head.decoder.weight"]
835
+
836
+ def __init__(self, config):
837
+ super().__init__(config)
838
+
839
+ if config.is_decoder:
840
+ logger.warning(
841
+ "If you want to use `ProPrimeForMaskedLM` make sure `config.is_decoder=False` for "
842
+ "bi-directional self-attention."
843
+ )
844
+
845
+ self.pro_prime = ProPrimeModel(config, add_pooling_layer=False)
846
+ self.lm_head = ProPrimeLMHead(config)
847
+ self.init_weights()
848
+
849
+ def get_input_embeddings(self):
850
+ return self.pro_prime.embeddings.word_embeddings
851
+
852
+ def get_output_embeddings(self):
853
+ return self.lm_head.decoder
854
+
855
+ def set_output_embeddings(self, new_embeddings):
856
+ self.lm_head.decoder = new_embeddings
857
+
858
+ def forward(
859
+ self,
860
+ input_ids: Optional[torch.LongTensor] = None,
861
+ attention_mask: Optional[torch.Tensor] = None,
862
+ position_ids: Optional[torch.LongTensor] = None,
863
+ head_mask: Optional[torch.Tensor] = None,
864
+ inputs_embeds: Optional[torch.FloatTensor] = None,
865
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
866
+ encoder_attention_mask: Optional[torch.Tensor] = None,
867
+ labels: Optional[torch.LongTensor] = None,
868
+ output_attentions: Optional[bool] = None,
869
+ output_hidden_states: Optional[bool] = None,
870
+ return_dict: Optional[bool] = None,
871
+ ) -> Union[Tuple, MaskedLMOutput]:
872
+ return_dict = (
873
+ return_dict if return_dict is not None else self.config.use_return_dict
874
+ )
875
+
876
+ outputs = self.pro_prime(
877
+ input_ids,
878
+ attention_mask=attention_mask,
879
+ position_ids=position_ids,
880
+ head_mask=head_mask,
881
+ inputs_embeds=inputs_embeds,
882
+ encoder_hidden_states=encoder_hidden_states,
883
+ encoder_attention_mask=encoder_attention_mask,
884
+ output_attentions=output_attentions,
885
+ output_hidden_states=output_hidden_states,
886
+ return_dict=return_dict,
887
+ )
888
+ sequence_output = outputs[0]
889
+ prediction_scores = self.lm_head(sequence_output)
890
+
891
+ masked_lm_loss = None
892
+ if labels is not None:
893
+ loss_fct = CrossEntropyLoss()
894
+
895
+ labels = labels.to(prediction_scores.device)
896
+ masked_lm_loss = loss_fct(
897
+ prediction_scores.view(-1, self.config.vocab_size), labels.view(-1)
898
+ )
899
+
900
+ if not return_dict:
901
+ output = (prediction_scores,) + outputs[2:]
902
+ return (
903
+ ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
904
+ )
905
+
906
+ return MaskedLMOutput(
907
+ loss=masked_lm_loss,
908
+ logits=prediction_scores,
909
+ hidden_states=outputs.hidden_states,
910
+ attentions=outputs.attentions,
911
+ )
912
+
913
+
914
+ class ProPrimeLMHead(nn.Module):
915
+
916
+ def __init__(self, config):
917
+ super().__init__()
918
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
919
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
920
+
921
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
922
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
923
+
924
+ def forward(self, features, **kwargs):
925
+ x = self.dense(features)
926
+ x = gelu(x)
927
+ x = self.layer_norm(x)
928
+
929
+ # project back to size of vocabulary with bias
930
+ x = self.decoder(x) + self.bias
931
+ return x
932
+
933
+
934
+ class ProPrimeStructureHead(nn.Module):
935
+
936
+ def __init__(self, config):
937
+ super().__init__()
938
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
939
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
940
+ self.decoder = nn.Linear(config.hidden_size, config.structure_vocab_size, bias=False)
941
+ self.bias = nn.Parameter(torch.zeros(config.structure_vocab_size))
942
+
943
+ def forward(self, features, **kwargs):
944
+ x = self.dense(features)
945
+ x = gelu(x)
946
+ x = self.layer_norm(x)
947
+
948
+ # project back to size of vocabulary with bias
949
+ x = self.decoder(x) + self.bias
950
+ return x
951
+
952
+
953
+ def create_position_ids_from_input_ids(
954
+ input_ids, padding_idx, past_key_values_length=0
955
+ ):
956
+ """
957
+ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
958
+ are ignored. This is modified from fairseq's `utils.make_positions`.
959
+
960
+ Args:
961
+ x: torch.Tensor x:
962
+
963
+ Returns: torch.Tensor
964
+ """
965
+ # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
966
+ mask = input_ids.ne(padding_idx).int()
967
+ incremental_indices = (
968
+ torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length
969
+ ) * mask
970
+ return incremental_indices.long() + padding_idx
971
+
972
+
973
+ # POOLING_HEAD
974
+ class MaskedConv1d(nn.Conv1d):
975
+ """A masked 1-dimensional convolution layer.
976
+
977
+ Takes the same arguments as torch.nn.Conv1D, except that the padding is set automatically.
978
+
979
+ Shape:
980
+ Input: (N, L, in_channels)
981
+ input_mask: (N, L, 1), optional
982
+ Output: (N, L, out_channels)
983
+ """
984
+
985
+ def __init__(
986
+ self,
987
+ in_channels: int,
988
+ out_channels: int,
989
+ kernel_size: int,
990
+ stride: int = 1,
991
+ dilation: int = 1,
992
+ groups: int = 1,
993
+ bias: bool = True,
994
+ ):
995
+ """
996
+ :param in_channels: input channels
997
+ :param out_channels: output channels
998
+ :param kernel_size: the kernel width
999
+ :param stride: filter shift
1000
+ :param dilation: dilation factor
1001
+ :param groups: perform depth-wise convolutions
1002
+ :param bias: adds learnable bias to output
1003
+ """
1004
+ padding = dilation * (kernel_size - 1) // 2
1005
+ super().__init__(
1006
+ in_channels,
1007
+ out_channels,
1008
+ kernel_size,
1009
+ stride=stride,
1010
+ dilation=dilation,
1011
+ groups=groups,
1012
+ bias=bias,
1013
+ padding=padding,
1014
+ )
1015
+
1016
+ def forward(self, x, input_mask=None):
1017
+ if input_mask is not None:
1018
+ x = x * input_mask
1019
+ return super().forward(x.transpose(1, 2)).transpose(1, 2)
1020
+
1021
+
1022
+ class Attention1d(nn.Module):
1023
+ def __init__(self, config):
1024
+ super().__init__()
1025
+ self.layer = MaskedConv1d(config.hidden_size, 1, 1)
1026
+ self.out = nn.Linear(config.hidden_size, config.hidden_size)
1027
+
1028
+ def forward(self, x, input_mask=None):
1029
+ batch_szie = x.shape[0]
1030
+ attn = self.layer(x)
1031
+ attn = attn.view(batch_szie, -1)
1032
+ if input_mask is not None:
1033
+ attn = attn.masked_fill_(
1034
+ ~input_mask.view(batch_szie, -1).bool(), float("-inf")
1035
+ )
1036
+ attn = F.softmax(attn, dim=-1).view(batch_szie, -1, 1)
1037
+ out = (attn * x).sum(dim=1)
1038
+ out = self.out(out)
1039
+ return out
1040
+
1041
+
1042
+ class FFN1d(nn.Module):
1043
+ def __init__(self, config):
1044
+ super().__init__()
1045
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
1046
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
1047
+ self.act = nn.GELU()
1048
+
1049
+ def forward(self, x):
1050
+ x = self.fc1(x)
1051
+ x = self.act(x)
1052
+ x = self.fc2(x)
1053
+ return x
1054
+
1055
+
1056
+ class Attention1dPooling(nn.Module):
1057
+ """Outputs of the model with the attention1d"""
1058
+
1059
+ def __init__(
1060
+ self, config
1061
+ ): # [batch x sequence(751) x embedding (1280)] --> [batch x embedding] --> [batch x 1]
1062
+ super(Attention1dPooling, self).__init__()
1063
+ self.attention1d = Attention1d(config)
1064
+ self.ffn = FFN1d(config)
1065
+ # self.norm1 = nn.BatchNorm1d(config.hidden_size)
1066
+ # self.norm2 = nn.BatchNorm1d(config.hidden_size)
1067
+ self.dropout1 = nn.Dropout(config.hidden_dropout_prob)
1068
+ self.dropout2 = nn.Dropout(config.hidden_dropout_prob)
1069
+
1070
+ def forward(self, x, input_mask):
1071
+ attn_out = self.attention1d(x, input_mask=input_mask.unsqueeze(-1))
1072
+ x = self.dropout1(attn_out)
1073
+ # x = self.norm1(x)
1074
+ ffn_out = self.ffn(x)
1075
+ x = x + self.dropout2(ffn_out)
1076
+ # x = self.norm2(x)
1077
+ return x
1078
+
1079
+
1080
+ @dataclass
1081
+ class MaskedLMOutput(ModelOutput):
1082
+ loss: Optional[torch.FloatTensor] = None
1083
+ mlm_loss: Optional[torch.FloatTensor] = None
1084
+ value_loss: Optional[torch.FloatTensor] = None
1085
+ predicted_values: Optional[torch.FloatTensor] = None
1086
+ logits: torch.FloatTensor = None
1087
+ sequence_hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
1088
+ hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
1089
+ attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
1090
+
1091
+
1092
+ class ProPrimeMV(ProPrimePreTrainedModel):
1093
+ _tied_weights_keys = ["lm_head.decoder.weight"]
1094
+
1095
+ def __init__(self, config):
1096
+ super().__init__(config)
1097
+ self.pro_prime = ProPrimeModel(config, add_pooling_layer=False)
1098
+ self.lm_head = ProPrimeLMHead(config)
1099
+ self.sequence_pooling = Attention1dPooling(config)
1100
+ self.value_projection = nn.Sequential(
1101
+ nn.Linear(config.hidden_size, config.hidden_size),
1102
+ nn.Tanh(),
1103
+ nn.Linear(config.hidden_size, 1),
1104
+ )
1105
+ self.init_weights()
1106
+
1107
+ def get_input_embeddings(self):
1108
+ return self.pro_prime.embeddings.word_embeddings
1109
+
1110
+ def get_output_embeddings(self):
1111
+ return self.lm_head.decoder
1112
+
1113
+ def set_output_embeddings(self, new_embeddings):
1114
+ self.lm_head.decoder = new_embeddings
1115
+
1116
+ def forward(
1117
+ self,
1118
+ input_ids: Optional[torch.LongTensor] = None,
1119
+ attention_mask: Optional[torch.Tensor] = None,
1120
+ position_ids: Optional[torch.LongTensor] = None,
1121
+ head_mask: Optional[torch.Tensor] = None,
1122
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1123
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
1124
+ encoder_attention_mask: Optional[torch.Tensor] = None,
1125
+ labels: Optional[torch.LongTensor] = None,
1126
+ values: Optional[torch.FloatTensor] = None,
1127
+ output_attentions: Optional[bool] = None,
1128
+ output_hidden_states: Optional[bool] = None,
1129
+ return_dict: Optional[bool] = None,
1130
+ ) -> Union[Tuple, MaskedLMOutput]:
1131
+ return_dict = (
1132
+ return_dict if return_dict is not None else self.config.use_return_dict
1133
+ )
1134
+
1135
+ outputs = self.pro_prime(
1136
+ input_ids,
1137
+ attention_mask=attention_mask,
1138
+ position_ids=position_ids,
1139
+ head_mask=head_mask,
1140
+ inputs_embeds=inputs_embeds,
1141
+ encoder_hidden_states=encoder_hidden_states,
1142
+ encoder_attention_mask=encoder_attention_mask,
1143
+ output_attentions=output_attentions,
1144
+ output_hidden_states=output_hidden_states,
1145
+ return_dict=return_dict,
1146
+ )
1147
+ sequence_output = outputs[0]
1148
+ prediction_scores = self.lm_head(sequence_output)
1149
+
1150
+ masked_lm_loss = None
1151
+ if labels is not None:
1152
+ loss_fct = CrossEntropyLoss()
1153
+
1154
+ labels = labels.to(prediction_scores.device)
1155
+ masked_lm_loss = loss_fct(
1156
+ prediction_scores.view(-1, self.config.vocab_size), labels.view(-1)
1157
+ )
1158
+
1159
+ if not return_dict:
1160
+ output = (prediction_scores,) + outputs[2:]
1161
+ return (
1162
+ ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
1163
+ )
1164
+
1165
+ if values is not None:
1166
+ sequence_states = self.sequence_pooling(sequence_output, attention_mask)
1167
+ predicted_values = self.value_projection(sequence_states)
1168
+ values = values.to(predicted_values.dtype)
1169
+ values = values.reshape(-1, 1)
1170
+ value_loss = nn.MSELoss()(predicted_values, values)
1171
+ loss = masked_lm_loss + 0.01 * value_loss
1172
+ else:
1173
+ sequence_states = self.sequence_pooling(sequence_output, attention_mask)
1174
+ predicted_values = self.value_projection(sequence_states)
1175
+ value_loss = None
1176
+ loss = masked_lm_loss
1177
+
1178
+ return MaskedLMOutput(
1179
+ loss=loss,
1180
+ mlm_loss=masked_lm_loss,
1181
+ value_loss=value_loss,
1182
+ logits=prediction_scores,
1183
+ predicted_values=predicted_values.reshape(-1),
1184
+ hidden_states=outputs.hidden_states,
1185
+ sequence_hidden_states=sequence_states,
1186
+ attentions=outputs.attentions,
1187
+ )
1188
+
1189
+
1190
+ @dataclass
1191
+ class PretrainedOutput(ModelOutput):
1192
+ loss: Optional[torch.FloatTensor] = None
1193
+ mlm_loss: Optional[torch.FloatTensor] = None
1194
+ structure_loss: Optional[torch.FloatTensor] = None
1195
+ corr_loss: Optional[torch.FloatTensor] = None
1196
+ value_loss: Optional[torch.FloatTensor] = None
1197
+ predicted_values: Optional[torch.FloatTensor] = None
1198
+ logits: torch.FloatTensor = None
1199
+ structure_logits: torch.FloatTensor = None
1200
+ sequence_hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
1201
+ hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
1202
+ attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
1203
+
1204
+
1205
+ class ProPrimeForPretraining(ProPrimePreTrainedModel):
1206
+ _tied_weights_keys = ["lm_head.decoder.weight"]
1207
+ base_model_prefix = "proprime"
1208
+
1209
+ def __init__(self, config):
1210
+ super().__init__(config)
1211
+ self.pro_prime = ProPrimeModel(config, add_pooling_layer=False)
1212
+ self.lm_head = ProPrimeLMHead(config)
1213
+ self.structure_head = ProPrimeStructureHead(config)
1214
+ self.sequence_pooling = Attention1dPooling(config)
1215
+ self.value_projection = nn.Sequential(
1216
+ nn.Linear(config.hidden_size, config.hidden_size),
1217
+ nn.Tanh(),
1218
+ nn.Linear(config.hidden_size, 1),
1219
+ )
1220
+ self.init_weights()
1221
+
1222
+ def get_input_embeddings(self):
1223
+ return self.pro_prime.embeddings.word_embeddings
1224
+
1225
+ def get_output_embeddings(self):
1226
+ return self.lm_head.decoder
1227
+
1228
+ def set_output_embeddings(self, new_embeddings):
1229
+ self.lm_head.decoder = new_embeddings
1230
+
1231
+ def forward(
1232
+ self,
1233
+ input_ids: Optional[torch.LongTensor] = None,
1234
+ attention_mask: Optional[torch.Tensor] = None,
1235
+ position_ids: Optional[torch.LongTensor] = None,
1236
+ head_mask: Optional[torch.Tensor] = None,
1237
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1238
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
1239
+ encoder_attention_mask: Optional[torch.Tensor] = None,
1240
+ labels: Optional[torch.LongTensor] = None,
1241
+ structure_labels: Optional[torch.LongTensor] = None,
1242
+ values: Optional[torch.FloatTensor] = None,
1243
+ mutant_input_ids: Optional[torch.LongTensor] = None, # Corr
1244
+ mutant_index: Optional[torch.LongTensor] = None, # Corr
1245
+ mutant_type: Optional[torch.LongTensor] = None, # Corr
1246
+ wild_type: Optional[torch.LongTensor] = None, # Corr
1247
+ output_attentions: Optional[bool] = None,
1248
+ output_hidden_states: Optional[bool] = None,
1249
+ return_dict: Optional[bool] = None,
1250
+ ) -> Union[Tuple, MaskedLMOutput]:
1251
+ return_dict = (
1252
+ return_dict if return_dict is not None else self.config.use_return_dict
1253
+ )
1254
+ outputs = self.pro_prime(
1255
+ input_ids,
1256
+ attention_mask=attention_mask,
1257
+ position_ids=position_ids,
1258
+ head_mask=head_mask,
1259
+ inputs_embeds=inputs_embeds,
1260
+ encoder_hidden_states=encoder_hidden_states,
1261
+ encoder_attention_mask=encoder_attention_mask,
1262
+ output_attentions=output_attentions,
1263
+ output_hidden_states=output_hidden_states,
1264
+ return_dict=return_dict,
1265
+ )
1266
+ sequence_output = outputs[0]
1267
+
1268
+ mlm_scores = self.lm_head(sequence_output)
1269
+ structure_scores = self.structure_head(sequence_output)
1270
+ sequence_states = self.sequence_pooling(sequence_output, attention_mask)
1271
+ predicted_values = self.value_projection(sequence_states)
1272
+
1273
+ loss = 0
1274
+ if mutant_input_ids is not None:
1275
+ with torch.no_grad():
1276
+ mutant_outputs = self.pro_prime(
1277
+ mutant_input_ids,
1278
+ attention_mask=attention_mask,
1279
+ position_ids=position_ids,
1280
+ head_mask=head_mask,
1281
+ inputs_embeds=inputs_embeds,
1282
+ encoder_hidden_states=encoder_hidden_states,
1283
+ encoder_attention_mask=encoder_attention_mask,
1284
+ output_attentions=output_attentions,
1285
+ output_hidden_states=output_hidden_states,
1286
+ return_dict=return_dict,
1287
+ )
1288
+ mutant_sequence_output = mutant_outputs[0]
1289
+ mutant_sequence_states = self.sequence_pooling(mutant_sequence_output, attention_mask)
1290
+ mutant_predicted_values = self.value_projection(mutant_sequence_states)
1291
+ values_diff = mutant_predicted_values - predicted_values
1292
+ logits = mlm_scores.log_softmax(dim=-1)
1293
+ mt_probs = logits[torch.arange(logits.size(0)), mutant_index, mutant_type]
1294
+ wt_probs = logits[torch.arange(logits.size(0)), mutant_index, wild_type]
1295
+ mutant_effects = mt_probs - wt_probs
1296
+ corr_loss = consine_based_loss(values_diff.squeeze(), mutant_effects.squeeze())
1297
+ loss += corr_loss
1298
+ else:
1299
+ corr_loss = None
1300
+
1301
+ if labels is not None:
1302
+ loss_fct = CrossEntropyLoss()
1303
+ labels = labels.to(mlm_scores.device)
1304
+ mlm_loss = loss_fct(
1305
+ mlm_scores.view(-1, self.config.vocab_size), labels.view(-1)
1306
+ )
1307
+ loss += mlm_loss
1308
+ else:
1309
+ mlm_loss = None
1310
+
1311
+ if structure_labels is not None:
1312
+ loss_fct = CrossEntropyLoss()
1313
+ structure_labels = structure_labels.to(structure_scores.device)
1314
+ structure_loss = loss_fct(
1315
+ structure_scores.view(-1, self.config.structure_vocab_size), structure_labels.view(-1)
1316
+ )
1317
+ loss += structure_loss
1318
+ else:
1319
+ structure_loss = None
1320
+
1321
+ if values is not None:
1322
+ loss_fct = nn.MSELoss()
1323
+ values = values.to(predicted_values.dtype)
1324
+ values = values.reshape(-1, 1)
1325
+ value_loss = nn.MSELoss()(predicted_values, values)
1326
+ loss += 0.01 * value_loss
1327
+ else:
1328
+ value_loss = None
1329
+
1330
+ return PretrainedOutput(
1331
+ loss=loss,
1332
+ mlm_loss=mlm_loss,
1333
+ structure_loss=structure_loss,
1334
+ value_loss=value_loss,
1335
+ corr_loss=corr_loss,
1336
+ logits=mlm_scores,
1337
+ structure_logits=structure_scores,
1338
+ predicted_values=predicted_values,
1339
+ hidden_states=outputs.hidden_states,
1340
+ sequence_hidden_states=sequence_states,
1341
+ attentions=outputs.attentions,
1342
+ )
1343
+
1344
+ ProPrimeForMaskedLM.register_for_auto_class("AutoModelForMaskedLM")
1345
+ ProPrimeForPretraining.register_for_auto_class("AutoModel")