yangheng commited on
Commit
286d17c
·
verified ·
1 Parent(s): 3b26205

Upload 2 files

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