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