yangheng commited on
Commit
27f2e6c
1 Parent(s): f2a9e29

Delete modeling_omnigenome.py

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