anonymous8 commited on
Commit
ad587b6
1 Parent(s): 3b12349

Upload 7 files

Browse files
config.json ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "OmniGenomefold_config": null,
3
+ "_name_or_path": "./",
4
+ "architectures": [
5
+ "OmniGenomeModel",
6
+ "OmniGenomeForTokenClassification",
7
+ "OmniGenomeForMaskedLM",
8
+ "OmniGenomeModelForSeq2SeqLM",
9
+ "OmniGenomeForTSequenceClassification",
10
+ "OmniGenomeForTokenClassification",
11
+ "OmniGenomeForSeq2SeqLM"
12
+ ],
13
+ "attention_probs_dropout_prob": 0.0,
14
+ "classifier_dropout": null,
15
+ "emb_layer_norm_before": false,
16
+ "hidden_act": "gelu",
17
+ "hidden_dropout_prob": 0,
18
+ "hidden_size": 480,
19
+ "id2label": {
20
+ "0": "(",
21
+ "1": ")",
22
+ "2": "."
23
+ },
24
+ "initializer_range": 0.02,
25
+ "intermediate_size": 2400,
26
+ "is_folding_model": false,
27
+ "label2id": {
28
+ "(": 0,
29
+ ")": 1,
30
+ ".": 2
31
+ },
32
+ "layer_norm_eps": 1e-05,
33
+ "mask_token_id": 23,
34
+ "max_position_embeddings": 1026,
35
+ "model_type": "omnigenome",
36
+ "num_attention_heads": 24,
37
+ "num_generation": 50,
38
+ "num_hidden_layers": 16,
39
+ "num_population": 100,
40
+ "pad_token_id": 1,
41
+ "position_embedding_type": "rotary",
42
+ "token_dropout": true,
43
+ "torch_dtype": "float32",
44
+ "transformers_version": "4.41.0.dev0",
45
+ "use_cache": true,
46
+ "verify_ss": true,
47
+ "vocab_list": null,
48
+ "vocab_size": 24
49
+ }
configuration_omnigenome.py ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 Meta and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """ OmniGenome model configuration"""
16
+
17
+ from dataclasses import asdict, dataclass
18
+ from typing import Optional
19
+
20
+ from transformers import PretrainedConfig
21
+
22
+ from transformers.utils import logging
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+ # TODO Update this
27
+ OmniGenome_PRETRAINED_CONFIG_ARCHIVE_MAP = {
28
+ "anonymous8/OmniGenome-52M": "https://huggingface.co/anonymous8/OmniGenome-52M/resolve/main/config.json",
29
+ "anonymous8/OmniGenome-186M": "https://huggingface.co/anonymous8/OmniGenome-186M/resolve/main/config.json",
30
+ # See all OmniGenome models at https://huggingface.co/models?filter=OmniGenome
31
+ }
32
+
33
+
34
+ class OmniGenomeConfig(PretrainedConfig):
35
+ r"""
36
+ This is the configuration class to store the configuration of a [`OmniGenomeModel`]. It is used to instantiate a OmniGenome model
37
+ according to the specified arguments, defining the model architecture. Instantiating a configuration with the
38
+ defaults will yield a similar configuration to that of the OmniGenome
39
+ [anonymous8/OmniGenome-52M](https://huggingface.co/anonymous8/OmniGenome-52M) architecture.
40
+
41
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
42
+ documentation from [`PretrainedConfig`] for more information.
43
+
44
+
45
+ Args:
46
+ vocab_size (`int`, *optional*):
47
+ Vocabulary size of the OmniGenome model. Defines the number of different tokens that can be represented by the
48
+ `inputs_ids` passed when calling [`OmniGenomeModel`].
49
+ mask_token_id (`int`, *optional*):
50
+ The index of the mask token in the vocabulary. This must be included in the config because of the
51
+ "mask-dropout" scaling trick, which will scale the inputs depending on the number of masked tokens.
52
+ pad_token_id (`int`, *optional*):
53
+ The index of the padding token in the vocabulary. This must be included in the config because certain parts
54
+ of the OmniGenome code use this instead of the attention mask.
55
+ hidden_size (`int`, *optional*, defaults to 768):
56
+ Dimensionality of the encoder layers and the pooler layer.
57
+ num_hidden_layers (`int`, *optional*, defaults to 12):
58
+ Number of hidden layers in the Transformer encoder.
59
+ num_attention_heads (`int`, *optional*, defaults to 12):
60
+ Number of attention heads for each attention layer in the Transformer encoder.
61
+ intermediate_size (`int`, *optional*, defaults to 3072):
62
+ Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
63
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
64
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
65
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
66
+ The dropout ratio for the attention probabilities.
67
+ max_position_embeddings (`int`, *optional*, defaults to 1026):
68
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
69
+ just in case (e.g., 512 or 1024 or 2048).
70
+ initializer_range (`float`, *optional*, defaults to 0.02):
71
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
72
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
73
+ The epsilon used by the layer normalization layers.
74
+ position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
75
+ Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query", "rotary"`.
76
+ For positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
77
+ [Self-Attention with Relative Position Representations (Shaw et al.)](https://arxiv.org/abs/1803.02155).
78
+ For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
79
+ with Better Relative Position Embeddings (Huang et al.)](https://arxiv.org/abs/2009.13658).
80
+ is_decoder (`bool`, *optional*, defaults to `False`):
81
+ Whether the model is used as a decoder or not. If `False`, the model is used as an encoder.
82
+ use_cache (`bool`, *optional*, defaults to `True`):
83
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
84
+ relevant if `config.is_decoder=True`.
85
+ emb_layer_norm_before (`bool`, *optional*):
86
+ Whether to apply layer normalization after embeddings but before the main stem of the network.
87
+ token_dropout (`bool`, defaults to `False`):
88
+ When this is enabled, masked tokens are treated as if they had been dropped out by input dropout.
89
+
90
+ Examples:
91
+
92
+ ```python
93
+ # >>> from transformers import OmniGenomeModel, OmniGenomeConfig
94
+ #
95
+ # >>> # Initializing a OmniGenome anonymous8/OmniGenome-52M style configuration >>> configuration = OmniGenomeConfig()
96
+ #
97
+ # >>> # Initializing a model from the configuration >>> model = OmniGenomeModel(configuration)
98
+ #
99
+ # >>> # Accessing the model configuration >>> configuration = model.config
100
+ ```"""
101
+
102
+ model_type = "mprna"
103
+
104
+ def __init__(
105
+ self,
106
+ vocab_size=None,
107
+ mask_token_id=None,
108
+ pad_token_id=None,
109
+ hidden_size=768,
110
+ num_hidden_layers=12,
111
+ num_attention_heads=12,
112
+ intermediate_size=3072,
113
+ hidden_dropout_prob=0.1,
114
+ attention_probs_dropout_prob=0.1,
115
+ max_position_embeddings=1026,
116
+ initializer_range=0.02,
117
+ layer_norm_eps=1e-12,
118
+ position_embedding_type="absolute",
119
+ use_cache=True,
120
+ emb_layer_norm_before=None,
121
+ token_dropout=False,
122
+ is_folding_model=False,
123
+ OmniGenomefold_config=None,
124
+ vocab_list=None,
125
+ **kwargs,
126
+ ):
127
+ super().__init__(
128
+ pad_token_id=pad_token_id, mask_token_id=mask_token_id, **kwargs
129
+ )
130
+
131
+ self.vocab_size = vocab_size
132
+ self.hidden_size = hidden_size
133
+ self.num_hidden_layers = num_hidden_layers
134
+ self.num_attention_heads = num_attention_heads
135
+ self.intermediate_size = intermediate_size
136
+ self.hidden_dropout_prob = hidden_dropout_prob
137
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
138
+ self.max_position_embeddings = max_position_embeddings
139
+ self.initializer_range = initializer_range
140
+ self.layer_norm_eps = layer_norm_eps
141
+ self.position_embedding_type = position_embedding_type
142
+ self.use_cache = use_cache
143
+ self.emb_layer_norm_before = emb_layer_norm_before
144
+ self.token_dropout = token_dropout
145
+ self.is_folding_model = is_folding_model
146
+ self.OmniGenomefold_config = None
147
+ self.vocab_list = None
148
+ if self.OmniGenomefold_config is not None and getattr(
149
+ self.OmniGenomefold_config, "use_OmniGenome_attn_map", False
150
+ ):
151
+ raise ValueError(
152
+ "The HuggingFace port of OmniGenomeFold does not support use_OmniGenome_attn_map at this time!"
153
+ )
154
+
155
+ def to_dict(self):
156
+ """
157
+ Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].
158
+
159
+ Returns:
160
+ `Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
161
+ """
162
+ output = super().to_dict()
163
+ return output
164
+
165
+
166
+ @dataclass
167
+ class TrunkConfig:
168
+ num_blocks: int = 48
169
+ sequence_state_dim: int = 1024
170
+ pairwise_state_dim: int = 128
171
+ sequence_head_width: int = 32
172
+ pairwise_head_width: int = 32
173
+ position_bins: int = 32
174
+ dropout: float = 0
175
+ layer_drop: float = 0
176
+ cpu_grad_checkpoint: bool = False
177
+ max_recycles: int = 4
178
+ chunk_size: Optional[int] = 128
179
+ structure_module: "StructureModuleConfig" = None
180
+
181
+ def __post_init__(self):
182
+ if self.structure_module is None:
183
+ self.structure_module = StructureModuleConfig()
184
+ elif isinstance(self.structure_module, dict):
185
+ self.structure_module = StructureModuleConfig(**self.structure_module)
186
+
187
+ if self.max_recycles <= 0:
188
+ raise ValueError(
189
+ f"`max_recycles` should be positive, got {self.max_recycles}."
190
+ )
191
+ if self.sequence_state_dim % self.sequence_state_dim != 0:
192
+ raise ValueError(
193
+ "`sequence_state_dim` should be a round multiple of `sequence_state_dim`, got"
194
+ f" {self.sequence_state_dim} and {self.sequence_state_dim}."
195
+ )
196
+ if self.pairwise_state_dim % self.pairwise_state_dim != 0:
197
+ raise ValueError(
198
+ "`pairwise_state_dim` should be a round multiple of `pairwise_state_dim`, got"
199
+ f" {self.pairwise_state_dim} and {self.pairwise_state_dim}."
200
+ )
201
+
202
+ sequence_num_heads = self.sequence_state_dim // self.sequence_head_width
203
+ pairwise_num_heads = self.pairwise_state_dim // self.pairwise_head_width
204
+
205
+ if self.sequence_state_dim != sequence_num_heads * self.sequence_head_width:
206
+ raise ValueError(
207
+ "`sequence_state_dim` should be equal to `sequence_num_heads * sequence_head_width, got"
208
+ f" {self.sequence_state_dim} != {sequence_num_heads} * {self.sequence_head_width}."
209
+ )
210
+ if self.pairwise_state_dim != pairwise_num_heads * self.pairwise_head_width:
211
+ raise ValueError(
212
+ "`pairwise_state_dim` should be equal to `pairwise_num_heads * pairwise_head_width, got"
213
+ f" {self.pairwise_state_dim} != {pairwise_num_heads} * {self.pairwise_head_width}."
214
+ )
215
+ if self.pairwise_state_dim % 2 != 0:
216
+ raise ValueError(
217
+ f"`pairwise_state_dim` should be even, got {self.pairwise_state_dim}."
218
+ )
219
+
220
+ if self.dropout >= 0.4:
221
+ raise ValueError(
222
+ f"`dropout` should not be greater than 0.4, got {self.dropout}."
223
+ )
224
+
225
+ def to_dict(self):
226
+ """
227
+ Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].
228
+
229
+ Returns:
230
+ `Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
231
+ """
232
+ output = asdict(self)
233
+ output["structure_module"] = self.structure_module.to_dict()
234
+ return output
235
+
236
+
237
+ @dataclass
238
+ class StructureModuleConfig:
239
+ """
240
+ Args:
241
+ sequence_dim:
242
+ Single representation channel dimension
243
+ pairwise_dim:
244
+ Pair representation channel dimension
245
+ ipa_dim:
246
+ IPA hidden channel dimension
247
+ resnet_dim:
248
+ Angle resnet (Alg. 23 lines 11-14) hidden channel dimension
249
+ num_heads_ipa:
250
+ Number of IPA heads
251
+ num_qk_points:
252
+ Number of query/key points to generate during IPA
253
+ num_v_points:
254
+ Number of value points to generate during IPA
255
+ dropout_rate:
256
+ Dropout rate used throughout the layer
257
+ num_blocks:
258
+ Number of structure module blocks
259
+ num_transition_layers:
260
+ Number of layers in the single representation transition (Alg. 23 lines 8-9)
261
+ num_resnet_blocks:
262
+ Number of blocks in the angle resnet
263
+ num_angles:
264
+ Number of angles to generate in the angle resnet
265
+ trans_scale_factor:
266
+ Scale of single representation transition hidden dimension
267
+ epsilon:
268
+ Small number used in angle resnet normalization
269
+ inf:
270
+ Large number used for attention masking
271
+ """
272
+
273
+ sequence_dim: int = 384
274
+ pairwise_dim: int = 128
275
+ ipa_dim: int = 16
276
+ resnet_dim: int = 128
277
+ num_heads_ipa: int = 12
278
+ num_qk_points: int = 4
279
+ num_v_points: int = 8
280
+ dropout_rate: float = 0.1
281
+ num_blocks: int = 8
282
+ num_transition_layers: int = 1
283
+ num_resnet_blocks: int = 2
284
+ num_angles: int = 7
285
+ trans_scale_factor: int = 10
286
+ epsilon: float = 1e-8
287
+ inf: float = 1e5
288
+
289
+ def to_dict(self):
290
+ return asdict(self)
291
+
292
+
293
+ def get_default_vocab_list():
294
+ return (
295
+ "<cls>",
296
+ "<pad>",
297
+ "<eos>",
298
+ "<unk>",
299
+ "A",
300
+ "C",
301
+ "G",
302
+ "T",
303
+ "U",
304
+ "N",
305
+ " ",
306
+ "<mask>",
307
+ )
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2300e9ae1743dac0e51fe56eec44718d64b408c349e5f0bc98c567d339fe7938
3
+ size 210828112
modeling_omnigenome.py ADDED
@@ -0,0 +1,1744 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 = "anonymous8/OmniGenome-52M"
53
+ _CONFIG_FOR_DOC = "OmniGenomeConfig"
54
+
55
+ OmniGenome_PRETRAINED_MODEL_ARCHIVE_LIST = [
56
+ "anonymous8/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.classifier = OmniGenomeClassificationHead(config)
1243
+ self.init_weights()
1244
+
1245
+ @add_start_docstrings_to_model_forward(
1246
+ OmniGenome_INPUTS_DOCSTRING.format("batch_size, sequence_length")
1247
+ )
1248
+ @add_code_sample_docstrings(
1249
+ checkpoint=_CHECKPOINT_FOR_DOC,
1250
+ output_type=SequenceClassifierOutput,
1251
+ config_class=_CONFIG_FOR_DOC,
1252
+ )
1253
+ def forward(
1254
+ self,
1255
+ input_ids: Optional[torch.LongTensor] = None,
1256
+ attention_mask: Optional[torch.Tensor] = None,
1257
+ position_ids: Optional[torch.LongTensor] = None,
1258
+ head_mask: Optional[torch.Tensor] = None,
1259
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1260
+ labels: Optional[torch.LongTensor] = None,
1261
+ output_attentions: Optional[bool] = None,
1262
+ output_hidden_states: Optional[bool] = None,
1263
+ return_dict: Optional[bool] = None,
1264
+ ) -> Union[Tuple, SequenceClassifierOutput]:
1265
+ r"""
1266
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1267
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1268
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1269
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1270
+ """
1271
+ return_dict = (
1272
+ return_dict if return_dict is not None else self.config.use_return_dict
1273
+ )
1274
+
1275
+ outputs = self.OmniGenome(
1276
+ input_ids,
1277
+ attention_mask=attention_mask,
1278
+ position_ids=position_ids,
1279
+ head_mask=head_mask,
1280
+ inputs_embeds=inputs_embeds,
1281
+ output_attentions=output_attentions,
1282
+ output_hidden_states=output_hidden_states,
1283
+ return_dict=return_dict,
1284
+ )
1285
+ last_hidden_state = outputs[0]
1286
+ logits = self.classifier(last_hidden_state)
1287
+
1288
+ loss = None
1289
+ if labels is not None:
1290
+ labels = labels.to(logits.device)
1291
+
1292
+ if self.config.problem_type is None:
1293
+ if self.num_labels == 1:
1294
+ self.config.problem_type = "regression"
1295
+ elif self.num_labels > 1 and (
1296
+ labels.dtype == torch.long or labels.dtype == torch.int
1297
+ ):
1298
+ self.config.problem_type = "single_label_classification"
1299
+ else:
1300
+ self.config.problem_type = "multi_label_classification"
1301
+
1302
+ if self.config.problem_type == "regression":
1303
+ loss_fct = MSELoss()
1304
+ if self.num_labels == 1:
1305
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1306
+ else:
1307
+ loss = loss_fct(logits, labels)
1308
+ elif self.config.problem_type == "single_label_classification":
1309
+ loss_fct = CrossEntropyLoss()
1310
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1311
+ elif self.config.problem_type == "multi_label_classification":
1312
+ loss_fct = BCEWithLogitsLoss()
1313
+ loss = loss_fct(logits, labels)
1314
+
1315
+ if not return_dict:
1316
+ output = (logits,) + outputs[2:]
1317
+ return ((loss,) + output) if loss is not None else output
1318
+
1319
+ return SequenceClassifierOutput(
1320
+ loss=loss,
1321
+ logits=logits,
1322
+ hidden_states=outputs.hidden_states,
1323
+ attentions=outputs.attentions,
1324
+ )
1325
+
1326
+
1327
+ @add_start_docstrings(
1328
+ """
1329
+ OmniGenome Model with a token classification head on top (a linear layer on top of the hidden-states output)
1330
+ Note that this model is pre-trained for RNA secondary structure prediction and can be used for zero-shot RNA
1331
+ secondary structure prediction. Please find more advanced usages at https://github.com/anonymous895/OmniGenome
1332
+ This model can be fine-tuned for other token classification tasks.
1333
+ """,
1334
+ OmniGenome_START_DOCSTRING,
1335
+ )
1336
+ # Copied from transformers.models.esm.modeling_esm.EsmForTokenClassification with Esm->OmniGenome
1337
+ class OmniGenomeForTokenClassification(OmniGenomePreTrainedModel):
1338
+ def __init__(self, config):
1339
+ super().__init__(config)
1340
+ self.num_labels = config.num_labels
1341
+ self.OmniGenome = OmniGenomeModel(config, add_pooling_layer=False)
1342
+ self.dense = torch.nn.Linear(config.hidden_size, config.hidden_size)
1343
+ self.classifier = torch.nn.Linear(self.config.hidden_size, self.num_labels)
1344
+ self.softmax = nn.Softmax(dim=-1)
1345
+ self.init_weights()
1346
+
1347
+ @add_start_docstrings_to_model_forward(
1348
+ OmniGenome_INPUTS_DOCSTRING.format("batch_size, sequence_length")
1349
+ )
1350
+ @add_code_sample_docstrings(
1351
+ checkpoint=_CHECKPOINT_FOR_DOC,
1352
+ output_type=TokenClassifierOutput,
1353
+ config_class=_CONFIG_FOR_DOC,
1354
+ )
1355
+ def forward(
1356
+ self,
1357
+ input_ids: Optional[torch.LongTensor] = None,
1358
+ attention_mask: Optional[torch.Tensor] = None,
1359
+ position_ids: Optional[torch.LongTensor] = None,
1360
+ head_mask: Optional[torch.Tensor] = None,
1361
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1362
+ labels: Optional[torch.LongTensor] = None,
1363
+ output_attentions: Optional[bool] = None,
1364
+ output_hidden_states: Optional[bool] = None,
1365
+ return_dict: Optional[bool] = None,
1366
+ ) -> Union[Tuple, TokenClassifierOutput]:
1367
+ r"""
1368
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1369
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1370
+ """
1371
+
1372
+ return_dict = (
1373
+ return_dict if return_dict is not None else self.config.use_return_dict
1374
+ )
1375
+
1376
+ outputs = self.OmniGenome(
1377
+ input_ids,
1378
+ attention_mask=attention_mask,
1379
+ position_ids=position_ids,
1380
+ head_mask=head_mask,
1381
+ inputs_embeds=inputs_embeds,
1382
+ output_attentions=output_attentions,
1383
+ output_hidden_states=output_hidden_states,
1384
+ return_dict=return_dict,
1385
+ )
1386
+
1387
+ last_hidden_state = outputs[0]
1388
+ last_hidden_state = self.dense(last_hidden_state)
1389
+ logits = self.classifier(last_hidden_state)
1390
+ logits = self.softmax(logits)
1391
+
1392
+ loss = None
1393
+ if labels is not None:
1394
+ loss_fct = CrossEntropyLoss()
1395
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1396
+
1397
+ if not return_dict:
1398
+ output = (logits,) + outputs[2:]
1399
+ return ((loss,) + output) if loss is not None else output
1400
+
1401
+ return TokenClassifierOutput(
1402
+ loss=loss,
1403
+ logits=logits,
1404
+ hidden_states=outputs.hidden_states,
1405
+ attentions=outputs.attentions,
1406
+ )
1407
+
1408
+ @staticmethod
1409
+ def verify_secondary_structure(structure):
1410
+ structure = list(structure)
1411
+ left_brackets = []
1412
+ right_brackets = []
1413
+ for i, char in enumerate(structure):
1414
+ if char == "(":
1415
+ left_brackets.append(i)
1416
+ elif char == ")":
1417
+ if left_brackets:
1418
+ left_brackets.pop()
1419
+ else:
1420
+ right_brackets.append(i)
1421
+
1422
+ for i in left_brackets:
1423
+ structure[i] = "."
1424
+ for i in right_brackets:
1425
+ structure[i] = "."
1426
+
1427
+ structure = "".join(structure)
1428
+
1429
+ return structure
1430
+
1431
+ def fold(
1432
+ self,
1433
+ sequence: str,
1434
+ **kwargs
1435
+ ) -> List[str]:
1436
+ r"""
1437
+ Load the pretrained OmniGenome Model to do zero-shot prediction of the secondary structure
1438
+ of a sequence given the sequence
1439
+ """
1440
+ if self.tokenizer is None:
1441
+ tokenizer = kwargs.get("tokenizer", None)
1442
+ if tokenizer is None:
1443
+ from transformers import AutoTokenizer
1444
+ self.tokenizer = AutoTokenizer.from_pretrained(self.config.name_or_path)
1445
+ else:
1446
+ self.tokenizer = tokenizer
1447
+
1448
+ inputs = self.tokenizer(sequence, return_tensors="pt", padding="max_length", truncation=True)
1449
+ input_ids = inputs["input_ids"]
1450
+ attention_mask = inputs["attention_mask"]
1451
+ outputs = self.forward(input_ids, attention_mask, **kwargs)
1452
+
1453
+ logits = torch.argmax(outputs.logits, dim=-1)
1454
+ lengths = torch.sum(torch.ne(torch.tensor(0), attention_mask), dim=-1)
1455
+ structures = []
1456
+ for i, length in enumerate(lengths):
1457
+ structure = logits[i, :length].cpu().numpy()
1458
+ structure = "".join(self.config.id2label[label] for label in structure)
1459
+ if self.config.verify_ss:
1460
+ structure = self.verify_secondary_structure(structure)
1461
+ structures.append(structure)
1462
+ return structures
1463
+
1464
+
1465
+ @add_start_docstrings(
1466
+ """
1467
+ This is not a standard Seq2Seq model. Instead, this model is designed for RNA design tasks.
1468
+ This is the OmniGenome Model with a simple genetic algorithm based RNA design head on top.
1469
+ """,
1470
+ OmniGenome_START_DOCSTRING,
1471
+ )
1472
+ class OmniGenomeModelForSeq2SeqLM(OmniGenomePreTrainedModel):
1473
+ def __init__(self, config):
1474
+ super().__init__(config)
1475
+ self.num_labels = config.num_labels
1476
+ self.OmniGenome = OmniGenomeModel(config, add_pooling_layer=False)
1477
+ self.lm_head = OmniGenomeLMHead(config)
1478
+ self.num_generation = config.num_generation
1479
+ self.num_population = config.num_population
1480
+ self.init_weights()
1481
+
1482
+ self.tokenizer = None
1483
+ self.predict_structure = None
1484
+
1485
+ warnings.warn(f"This model {self.__class__.__name__} is not a real Seq2Seq model. "
1486
+ f"Instead, this model is designed for RNA design tasks")
1487
+
1488
+ @add_start_docstrings_to_model_forward(
1489
+ OmniGenome_INPUTS_DOCSTRING.format("batch_size, sequence_length")
1490
+ )
1491
+ @add_code_sample_docstrings(
1492
+ checkpoint=_CHECKPOINT_FOR_DOC,
1493
+ output_type=TokenClassifierOutput,
1494
+ config_class=_CONFIG_FOR_DOC,
1495
+ )
1496
+ def forward(
1497
+ self,
1498
+ input_ids: Optional[torch.LongTensor] = None,
1499
+ attention_mask: Optional[torch.Tensor] = None,
1500
+ position_ids: Optional[torch.LongTensor] = None,
1501
+ head_mask: Optional[torch.Tensor] = None,
1502
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1503
+ labels: Optional[torch.LongTensor] = None,
1504
+ output_attentions: Optional[bool] = None,
1505
+ output_hidden_states: Optional[bool] = True,
1506
+ return_dict: Optional[bool] = None,
1507
+ ) -> Union[Tuple, TokenClassifierOutput]:
1508
+ r"""
1509
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1510
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1511
+ """
1512
+ raise NotImplementedError("This model is not designed for standard Seq2Seq tasks. "
1513
+ "Use model.design() for RNA sequences design instead.")
1514
+
1515
+ def design(
1516
+ self,
1517
+ structure: str,
1518
+ predict_structure_func=None,
1519
+ **kwargs
1520
+ ) -> List[str]:
1521
+ """
1522
+ Assemble the RNA sequence given the reference sequence structure
1523
+ """
1524
+ if self.tokenizer is None:
1525
+ tokenizer = kwargs.get("tokenizer", None)
1526
+ if tokenizer is None:
1527
+ from transformers import AutoTokenizer
1528
+ self.tokenizer = AutoTokenizer.from_pretrained(self.config.name_or_path)
1529
+ else:
1530
+ self.tokenizer = tokenizer
1531
+
1532
+ candidates = self.genetic_algorithm_for_rna_design(structure, predict_structure_func=None, **kwargs)
1533
+
1534
+ return candidates
1535
+
1536
+ def genetic_algorithm_for_rna_design(self, structure, predict_structure_func=None, **kwargs):
1537
+ if predict_structure_func is None:
1538
+ import ViennaRNA
1539
+
1540
+ def predict_structure(sequence):
1541
+ return ViennaRNA.fold(sequence)[0]
1542
+
1543
+ predict_structure_func = predict_structure
1544
+
1545
+ self.predict_structure = predict_structure_func
1546
+ mutation_ratio = kwargs.get("mutation_ratio", 0.5)
1547
+ num_population = kwargs.get("num_population", self.num_population)
1548
+ num_generation = kwargs.get("num_generation", self.num_generation)
1549
+ import tqdm
1550
+ population = self.init_population(structure, num_population)
1551
+ population = self.mlm_mutate(population, structure, mutation_ratio=mutation_ratio)
1552
+ for generation_id in tqdm.tqdm(range(num_generation), desc="Designing RNA Sequence"):
1553
+ population_fitness = self.sequence_fitness(population, structure)[:num_population]
1554
+ population = sorted(zip(population, population_fitness), key=lambda x: x[1])[:num_population]
1555
+ population = [x[0] for x in population]
1556
+ next_generation = population # Elitism
1557
+ next_generation += self.crossover(population, structure)
1558
+ next_generation += self.mlm_mutate(next_generation, structure, mutation_ratio)
1559
+ fitness_values = self.sequence_fitness(next_generation, structure)
1560
+ next_generation = sorted(zip(next_generation, fitness_values), key=lambda x: x[1])
1561
+
1562
+ candidate_sequences = []
1563
+ for sequence, fitness in next_generation:
1564
+ if fitness == 0:
1565
+ candidate_sequences.append(sequence)
1566
+ else:
1567
+ break
1568
+ if candidate_sequences:
1569
+ return candidate_sequences
1570
+ print(f"Generation {generation_id}: {next_generation[0][0]} with fitness {next_generation[0][1]}")
1571
+ population = [x[0] for x in next_generation[:num_population]]
1572
+
1573
+ return []
1574
+
1575
+ def init_population(self, structure, num_population):
1576
+ # Initialize lists to store population data and inputs for masked language model
1577
+ population = []
1578
+ mlm_inputs = []
1579
+ # Iterate over the number of individuals in the population
1580
+ for _ in range(num_population): # Changed from self.num_population to num_population
1581
+ # Create a sequence by randomly choosing nucleotides or a mask token for each position in the structure
1582
+ masked_sequence = [
1583
+ random.choice(["A", "G", "C", "T", "<mask>"])
1584
+ for _ in range(len(structure))
1585
+ ]
1586
+ masked_sequence_str = "".join(masked_sequence)
1587
+ mlm_inputs.append(f"{masked_sequence_str}<eos>{''.join(structure)}")
1588
+
1589
+ # Call a function to predict outputs using the masked language model
1590
+ outputs = self.mlm_predict(mlm_inputs, structure)
1591
+
1592
+ # Decode the mlm outputs and construct the initial population
1593
+ for i in range(len(outputs)):
1594
+ sequence = self.tokenizer.convert_ids_to_tokens(outputs[i].tolist())
1595
+ fixed_sequence = [
1596
+ x if x in "AGCT" else random.choice(["G", "C"])
1597
+ for x, y in zip(sequence, list(mlm_inputs[i].replace('<mask>', '$')))
1598
+ ]
1599
+ population.append("".join(fixed_sequence))
1600
+
1601
+ return population
1602
+
1603
+ def mlm_mutate(self, population, structure, mutation_ratio):
1604
+ def mutate(sequence, mutation_rate):
1605
+ sequence = np.array(list(sequence), dtype=np.str_)
1606
+ probability_matrix = np.full(sequence.shape, mutation_rate)
1607
+ masked_indices = np.random.rand(*sequence.shape) < probability_matrix
1608
+ sequence[masked_indices] = "$"
1609
+ mut_seq = "".join(sequence.tolist()).replace("$", "<mask>")
1610
+ return mut_seq
1611
+
1612
+ # Initialize lists to store population data and inputs for masked language model
1613
+ mlm_inputs = []
1614
+ masked_sequences = []
1615
+
1616
+ # Iterate over the number of individuals in the population
1617
+ for sequence in population:
1618
+ # Create a sequence by randomly choosing nucleotides or a mask token for each position in the structure
1619
+ masked_sequence = mutate(sequence, mutation_ratio)
1620
+ masked_sequences.append(masked_sequence)
1621
+ mlm_inputs.append(f"{masked_sequence}<eos>{''.join(structure)}")
1622
+
1623
+ # Call a function to predict outputs using the masked language model
1624
+ outputs = self.mlm_predict(mlm_inputs, structure)
1625
+
1626
+ mut_population = []
1627
+
1628
+ # Decode the mlm outputs and construct the initial population
1629
+ for i in range(len(outputs)):
1630
+ sequence = self.tokenizer.convert_ids_to_tokens(outputs[i].tolist())
1631
+ fixed_sequence = [
1632
+ x if x in "AGCT" else random.choice(["G", "C"])
1633
+ for x, y in zip(sequence, list(masked_sequences[i].replace('<mask>', '$')))
1634
+ ]
1635
+ mut_population.append("".join(fixed_sequence))
1636
+
1637
+ return mut_population
1638
+
1639
+ def crossover(self, population, structure):
1640
+ crossover_population = []
1641
+ batch_crossover_inputs = []
1642
+ for i in range(len(population)):
1643
+ parent1, parent2 = random.choices(population, k=2)
1644
+ pos = random.randint(1, len(parent1) - 1)
1645
+ child1 = parent1[:pos] + "<mask>" * len(parent2[pos:])
1646
+ child2 = "<mask>" * len(parent1[:pos]) + parent2[pos:]
1647
+ batch_crossover_inputs.append(f"{child1}<eos>{structure}")
1648
+ batch_crossover_inputs.append(f"{child2}<eos>{structure}")
1649
+
1650
+ outputs = self.mlm_predict(batch_crossover_inputs, structure)
1651
+
1652
+ for i in range(len(outputs)):
1653
+ sequence = self.tokenizer.convert_ids_to_tokens(outputs[i].tolist())
1654
+ fixed_sequence = [
1655
+ x if x in "AGCT" else random.choice(["G", "C"])
1656
+ for x, y in zip(sequence, list(batch_crossover_inputs[i].replace('<mask>', '$')))
1657
+ ]
1658
+ crossover_population.append("".join(fixed_sequence))
1659
+
1660
+ return crossover_population
1661
+
1662
+ def sequence_fitness(self, sequences, structure):
1663
+ fitness_values = []
1664
+ structures = [self.predict_structure(sequence) for sequence in sequences]
1665
+ for predicted_structure in structures:
1666
+ scores = []
1667
+ for i in range(len(predicted_structure)):
1668
+ if predicted_structure[i] == structure[i]:
1669
+ scores.append(1)
1670
+ elif (
1671
+ predicted_structure[i] == ")"
1672
+ and structure[i] == "("
1673
+ or predicted_structure[i] == "("
1674
+ and structure[i] == ")"
1675
+ ):
1676
+ scores.append(-3)
1677
+ else:
1678
+ scores.append(0)
1679
+ score = 1 - sum(scores) / len(structure)
1680
+ fitness_values.append(score)
1681
+ return fitness_values
1682
+
1683
+ def mlm_predict(self, mlm_inputs, structure):
1684
+ batch_size = 4
1685
+ all_outputs = []
1686
+ from transformers import set_seed
1687
+ set_seed(random.randint(0, 99999999), deterministic=False)
1688
+
1689
+ with torch.no_grad():
1690
+ for i in range(0, len(mlm_inputs), batch_size):
1691
+ batch_mlm_inputs = self.tokenizer(
1692
+ mlm_inputs[i:i + batch_size],
1693
+ padding=True,
1694
+ max_length=len(mlm_inputs[0]) // 2,
1695
+ truncation=True,
1696
+ return_tensors="pt",
1697
+ )
1698
+ batch_mlm_inputs = batch_mlm_inputs.to(self.device)
1699
+ outputs = self.OmniGenome(**batch_mlm_inputs)[0]
1700
+ outputs = self.lm_head(outputs)
1701
+ outputs = outputs.argmax(dim=-1)
1702
+ all_outputs.append(outputs)
1703
+ outputs = torch.cat(all_outputs, dim=0)
1704
+ return outputs[:, 1:1 + len(structure)]
1705
+
1706
+
1707
+ # Copied from transformers.models.esm.modeling_esm.EsmClassificationHead with Esm->OmniGenome
1708
+ class OmniGenomeClassificationHead(nn.Module):
1709
+ """Head for sentence-level classification tasks."""
1710
+
1711
+ def __init__(self, config):
1712
+ super().__init__()
1713
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
1714
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
1715
+ self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
1716
+
1717
+ def forward(self, features, **kwargs):
1718
+ x = features[:, 0, :] # take <s> token (equiv. to [CLS])
1719
+ x = self.dropout(x)
1720
+ x = self.dense(x)
1721
+ x = torch.tanh(x)
1722
+ x = self.dropout(x)
1723
+ x = self.out_proj(x)
1724
+ return x
1725
+
1726
+
1727
+ def create_position_ids_from_input_ids(
1728
+ input_ids, padding_idx, past_key_values_length=0
1729
+ ):
1730
+ """
1731
+ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
1732
+ are ignored. This is modified from fairseq's `utils.make_positions`.
1733
+
1734
+ Args:
1735
+ x: torch.Tensor x:
1736
+
1737
+ Returns: torch.Tensor
1738
+ """
1739
+ # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
1740
+ mask = input_ids.ne(padding_idx).int()
1741
+ incremental_indices = (
1742
+ torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length
1743
+ ) * mask
1744
+ return incremental_indices.long() + padding_idx
special_tokens_map.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": {
3
+ "content": "<cls>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<eos>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "mask_token": {
17
+ "content": "<mask>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "pad_token": {
24
+ "content": "<pad>",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ },
30
+ "unk_token": {
31
+ "content": "<unk>",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false
36
+ }
37
+ }
tokenizer_config.json ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "<cls>",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "1": {
12
+ "content": "<pad>",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "2": {
20
+ "content": "<eos>",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "3": {
28
+ "content": "<unk>",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "23": {
36
+ "content": "<mask>",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ }
43
+ },
44
+ "clean_up_tokenization_spaces": true,
45
+ "cls_token": "<cls>",
46
+ "eos_token": "<eos>",
47
+ "mask_token": "<mask>",
48
+ "model_max_length": 1000000000000000019884624838656,
49
+ "pad_token": "<pad>",
50
+ "tokenizer_class": "EsmTokenizer",
51
+ "unk_token": "<unk>"
52
+ }
vocab.txt ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <cls>
2
+ <pad>
3
+ <eos>
4
+ <unk>
5
+ A
6
+ C
7
+ G
8
+ T
9
+ N
10
+ U
11
+ a
12
+ c
13
+ g
14
+ t
15
+ n
16
+ u
17
+ (
18
+ )
19
+ .
20
+ *
21
+ 1
22
+ 2
23
+ 3
24
+ <mask>