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