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