yangheng commited on
Commit
629f896
·
verified ·
1 Parent(s): 988f538

Upload 9 files

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