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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
library_name: transformers
|
| 3 |
+
tags: []
|
| 4 |
---
|
| 5 |
+
|
| 6 |
+
# Model Card for Model ID
|
| 7 |
+
|
| 8 |
+
ProtST for binary localization
|
| 9 |
+
|
| 10 |
+
## Running script
|
| 11 |
+
```python
|
| 12 |
+
from transformers import AutoModel, AutoTokenizer, HfArgumentParser, TrainingArguments, Trainer
|
| 13 |
+
from transformers.data.data_collator import DataCollatorWithPadding
|
| 14 |
+
from transformers.trainer_pt_utils import get_parameter_names
|
| 15 |
+
from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
|
| 16 |
+
from datasets import load_dataset
|
| 17 |
+
import functools
|
| 18 |
+
import numpy as np
|
| 19 |
+
from sklearn.metrics import accuracy_score, matthews_corrcoef
|
| 20 |
+
import sys
|
| 21 |
+
import torch
|
| 22 |
+
import logging
|
| 23 |
+
import datasets
|
| 24 |
+
import transformers
|
| 25 |
+
|
| 26 |
+
logging.basicConfig(level=logging.INFO)
|
| 27 |
+
logger = logging.getLogger(__name__)
|
| 28 |
+
|
| 29 |
+
def create_optimizer(opt_model, lr_ratio=0.1):
|
| 30 |
+
head_names = []
|
| 31 |
+
for n, p in opt_model.named_parameters():
|
| 32 |
+
if "classifier" in n:
|
| 33 |
+
head_names.append(n)
|
| 34 |
+
else:
|
| 35 |
+
p.requires_grad = False
|
| 36 |
+
# turn a list of tuple to 2 lists
|
| 37 |
+
for n, p in opt_model.named_parameters():
|
| 38 |
+
if n in head_names:
|
| 39 |
+
assert p.requires_grad
|
| 40 |
+
backbone_names = []
|
| 41 |
+
for n, p in opt_model.named_parameters():
|
| 42 |
+
if n not in head_names and p.requires_grad:
|
| 43 |
+
backbone_names.append(n)
|
| 44 |
+
# for weight_decay policy, see
|
| 45 |
+
# https://github.com/huggingface/transformers/blob/50573c648ae953dcc1b94d663651f07fb02268f4/src/transformers/trainer.py#L947
|
| 46 |
+
decay_parameters = get_parameter_names(opt_model, ALL_LAYERNORM_LAYERS) # forbidden layer norm
|
| 47 |
+
decay_parameters = [name for name in decay_parameters if "bias" not in name]
|
| 48 |
+
# training_args.learning_rate
|
| 49 |
+
head_decay_parameters = [name for name in head_names if name in decay_parameters]
|
| 50 |
+
head_not_decay_parameters = [name for name in head_names if name not in decay_parameters]
|
| 51 |
+
# training_args.learning_rate * model_config.lr_ratio
|
| 52 |
+
backbone_decay_parameters = [name for name in backbone_names if name in decay_parameters]
|
| 53 |
+
backbone_not_decay_parameters = [name for name in backbone_names if name not in decay_parameters]
|
| 54 |
+
optimizer_grouped_parameters = [
|
| 55 |
+
{
|
| 56 |
+
"params": [p for n, p in opt_model.named_parameters() if (n in head_decay_parameters and p.requires_grad)],
|
| 57 |
+
"weight_decay": training_args.weight_decay,
|
| 58 |
+
"lr": training_args.learning_rate
|
| 59 |
+
},
|
| 60 |
+
{
|
| 61 |
+
"params": [p for n, p in opt_model.named_parameters() if (n in backbone_decay_parameters and p.requires_grad)],
|
| 62 |
+
"weight_decay": training_args.weight_decay,
|
| 63 |
+
"lr": training_args.learning_rate * lr_ratio
|
| 64 |
+
},
|
| 65 |
+
{
|
| 66 |
+
"params": [p for n, p in opt_model.named_parameters() if (n in head_not_decay_parameters and p.requires_grad)],
|
| 67 |
+
"weight_decay": 0.0,
|
| 68 |
+
"lr": training_args.learning_rate
|
| 69 |
+
},
|
| 70 |
+
{
|
| 71 |
+
"params": [p for n, p in opt_model.named_parameters() if (n in backbone_not_decay_parameters and p.requires_grad)],
|
| 72 |
+
"weight_decay": 0.0,
|
| 73 |
+
"lr": training_args.learning_rate * lr_ratio
|
| 74 |
+
},
|
| 75 |
+
]
|
| 76 |
+
optimizer_cls, optimizer_kwargs = Trainer.get_optimizer_cls_and_kwargs(training_args)
|
| 77 |
+
optimizer = optimizer_cls(optimizer_grouped_parameters, **optimizer_kwargs)
|
| 78 |
+
|
| 79 |
+
return optimizer
|
| 80 |
+
|
| 81 |
+
def create_scheduler(training_args, optimizer):
|
| 82 |
+
from transformers.optimization import get_scheduler
|
| 83 |
+
return get_scheduler(
|
| 84 |
+
training_args.lr_scheduler_type,
|
| 85 |
+
optimizer=optimizer if optimizer is None else optimizer,
|
| 86 |
+
num_warmup_steps=training_args.get_warmup_steps(training_args.max_steps),
|
| 87 |
+
num_training_steps=training_args.max_steps,
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
def compute_metrics(eval_preds):
|
| 91 |
+
probs, labels = eval_preds
|
| 92 |
+
preds = np.argmax(probs, axis=-1)
|
| 93 |
+
result = {"accuracy": accuracy_score(labels, preds), "mcc": matthews_corrcoef(labels, preds)}
|
| 94 |
+
return result
|
| 95 |
+
|
| 96 |
+
def preprocess_logits_for_metrics(logits, labels):
|
| 97 |
+
return torch.softmax(logits, dim=-1)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
if __name__ == "__main__":
|
| 101 |
+
device = torch.device("cpu")
|
| 102 |
+
raw_dataset = load_dataset("Jiqing/ProtST-BinaryLocalization")
|
| 103 |
+
model = AutoModel.from_pretrained("Jiqing/protst-esm1b-for-sequential-classification", trust_remote_code=True, torch_dtype=torch.bfloat16).to(device)
|
| 104 |
+
tokenizer = AutoTokenizer.from_pretrained("facebook/esm1b_t33_650M_UR50S")
|
| 105 |
+
|
| 106 |
+
output_dir = "/home/jiqingfe/protst/protst_2/ProtST-HuggingFace/output_dir/ProtSTModel/default/ESM-1b_PubMedBERT-abs/240123_015856"
|
| 107 |
+
training_args = {'output_dir': output_dir, 'overwrite_output_dir': True, 'do_train': True, 'per_device_train_batch_size': 32, 'gradient_accumulation_steps': 1, \
|
| 108 |
+
'learning_rate': 5e-05, 'weight_decay': 0, 'num_train_epochs': 100, 'max_steps': -1, 'lr_scheduler_type': 'constant', 'do_eval': True, \
|
| 109 |
+
'evaluation_strategy': 'epoch', 'per_device_eval_batch_size': 32, 'logging_strategy': 'epoch', 'save_strategy': 'epoch', 'save_steps': 820, \
|
| 110 |
+
'dataloader_num_workers': 0, 'run_name': 'downstream_esm1b_localization_fix', 'optim': 'adamw_torch', 'resume_from_checkpoint': False, \
|
| 111 |
+
'label_names': ['labels'], 'load_best_model_at_end': True, 'metric_for_best_model': 'accuracy', 'bf16': True, "save_total_limit": 3}
|
| 112 |
+
training_args = HfArgumentParser(TrainingArguments).parse_dict(training_args, allow_extra_keys=False)[0]
|
| 113 |
+
|
| 114 |
+
def tokenize_protein(example, tokenizer=None):
|
| 115 |
+
protein_seq = example["prot_seq"]
|
| 116 |
+
protein_seq_str = tokenizer(protein_seq, add_special_tokens=True)
|
| 117 |
+
example["input_ids"] = protein_seq_str["input_ids"]
|
| 118 |
+
example["attention_mask"] = protein_seq_str["attention_mask"]
|
| 119 |
+
example["labels"] = example["localization"]
|
| 120 |
+
|
| 121 |
+
return example
|
| 122 |
+
|
| 123 |
+
func_tokenize_protein = functools.partial(tokenize_protein, tokenizer=tokenizer)
|
| 124 |
+
|
| 125 |
+
for split in ["train", "validation", "test"]:
|
| 126 |
+
raw_dataset[split] = raw_dataset[split].map(func_tokenize_protein, batched=False, remove_columns=["Unnamed: 0", "prot_seq", "localization"])
|
| 127 |
+
|
| 128 |
+
data_collator = DataCollatorWithPadding(tokenizer=tokenizer)
|
| 129 |
+
|
| 130 |
+
transformers.utils.logging.set_verbosity_info()
|
| 131 |
+
log_level = training_args.get_process_log_level()
|
| 132 |
+
logger.setLevel(log_level)
|
| 133 |
+
|
| 134 |
+
optimizer = create_optimizer(model)
|
| 135 |
+
scheduler = create_scheduler(training_args, optimizer)
|
| 136 |
+
|
| 137 |
+
# build trainer
|
| 138 |
+
trainer = Trainer(
|
| 139 |
+
model=model,
|
| 140 |
+
args=training_args,
|
| 141 |
+
train_dataset=raw_dataset["train"],
|
| 142 |
+
eval_dataset=raw_dataset["validation"],
|
| 143 |
+
data_collator=data_collator,
|
| 144 |
+
optimizers=(optimizer, scheduler),
|
| 145 |
+
compute_metrics=compute_metrics,
|
| 146 |
+
preprocess_logits_for_metrics=preprocess_logits_for_metrics,
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
train_result = trainer.train()
|
| 150 |
+
|
| 151 |
+
trainer.save_model()
|
| 152 |
+
# Saves the tokenizer too for easy upload
|
| 153 |
+
tokenizer.save_pretrained(training_args.output_dir)
|
| 154 |
+
|
| 155 |
+
metrics = train_result.metrics
|
| 156 |
+
metrics["train_samples"] = len(raw_dataset["train"])
|
| 157 |
+
|
| 158 |
+
trainer.log_metrics("train", metrics)
|
| 159 |
+
trainer.save_metrics("train", metrics)
|
| 160 |
+
trainer.save_state()
|
| 161 |
+
|
| 162 |
+
metric = trainer.evaluate(raw_dataset["test"], metric_key_prefix="test")
|
| 163 |
+
print("test metric: ", metric)
|
| 164 |
+
|
| 165 |
+
metric = trainer.evaluate(raw_dataset["validation"], metric_key_prefix="valid")
|
| 166 |
+
print("valid metric: ", metric)
|
| 167 |
+
```
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
|
config.json
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_name_or_path": "Jiqing/protst-esm1b-for-sequential-classification",
|
| 3 |
+
"architectures": [
|
| 4 |
+
"ProtSTForProteinPropertyPrediction"
|
| 5 |
+
],
|
| 6 |
+
"auto_map": {
|
| 7 |
+
"AutoConfig": "Jiqing/protst-esm1b-for-sequential-classification--configuration_protst.ProtSTConfig",
|
| 8 |
+
"AutoModel": "Jiqing/protst-esm1b-for-sequential-classification--modeling_protst.ProtSTForProteinPropertyPrediction"
|
| 9 |
+
},
|
| 10 |
+
"model_type": "protst",
|
| 11 |
+
"protein_config": {
|
| 12 |
+
"_name_or_path": "/tmp/facebook/esm1b_t33_650M_UR50S",
|
| 13 |
+
"architectures": [
|
| 14 |
+
"EsmForMaskedLM"
|
| 15 |
+
],
|
| 16 |
+
"attention_probs_dropout_prob": 0.0,
|
| 17 |
+
"classifier_dropout": null,
|
| 18 |
+
"cls_token_id": 0,
|
| 19 |
+
"emb_layer_norm_before": true,
|
| 20 |
+
"eos_token_id": 2,
|
| 21 |
+
"hidden_act": "gelu",
|
| 22 |
+
"hidden_dropout_prob": 0.0,
|
| 23 |
+
"hidden_size": 1280,
|
| 24 |
+
"intermediate_size": 5120,
|
| 25 |
+
"layer_norm_eps": 1e-05,
|
| 26 |
+
"mask_token_id": 32,
|
| 27 |
+
"model_type": "esm",
|
| 28 |
+
"num_attention_heads": 20,
|
| 29 |
+
"num_hidden_layers": 33,
|
| 30 |
+
"pad_token_id": 1,
|
| 31 |
+
"token_dropout": true,
|
| 32 |
+
"torch_dtype": "float32",
|
| 33 |
+
"vocab_size": 33
|
| 34 |
+
},
|
| 35 |
+
"torch_dtype": "float32",
|
| 36 |
+
"transformers_version": "4.38.0.dev0"
|
| 37 |
+
}
|
configuration_protst.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import PretrainedConfig
|
| 2 |
+
from transformers.utils import logging
|
| 3 |
+
from transformers.models.esm import EsmConfig
|
| 4 |
+
|
| 5 |
+
logger = logging.get_logger(__name__)
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class ProtSTConfig(PretrainedConfig):
|
| 9 |
+
r"""
|
| 10 |
+
This is the configuration class to store the configuration of a [`ProtSTModel`].
|
| 11 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 12 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 13 |
+
Args:
|
| 14 |
+
protein_config (`dict`, *optional*):
|
| 15 |
+
Dictionary of configuration options used to initialize [`EsmForProteinRepresentation`].
|
| 16 |
+
```"""
|
| 17 |
+
|
| 18 |
+
model_type = "protst"
|
| 19 |
+
|
| 20 |
+
def __init__(
|
| 21 |
+
self,
|
| 22 |
+
protein_config=None,
|
| 23 |
+
**kwargs,
|
| 24 |
+
):
|
| 25 |
+
super().__init__(**kwargs)
|
| 26 |
+
|
| 27 |
+
if protein_config is None:
|
| 28 |
+
protein_config = {}
|
| 29 |
+
logger.info("`protein_config` is `None`. Initializing the `ProtSTProteinConfig` with default values.")
|
| 30 |
+
|
| 31 |
+
self.protein_config = EsmConfig(**protein_config)
|
| 32 |
+
|
| 33 |
+
@classmethod
|
| 34 |
+
def from_protein_text_configs(
|
| 35 |
+
cls, protein_config: EsmConfig, **kwargs
|
| 36 |
+
):
|
| 37 |
+
r"""
|
| 38 |
+
Instantiate a [`ProtSTConfig`] (or a derived class) from ProtST text model configuration. Returns:
|
| 39 |
+
[`ProtSTConfig`]: An instance of a configuration object
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
return cls(protein_config=protein_config.to_dict(), **kwargs)
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2cc85989acd0d89c5dd68001eac09168fdb4e36b9ae6056ff278f6728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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
from typing import Optional, Tuple, Union
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
from transformers import PreTrainedModel
|
| 7 |
+
from transformers.modeling_outputs import ModelOutput
|
| 8 |
+
from transformers.models.esm import EsmPreTrainedModel, EsmModel
|
| 9 |
+
from transformers.models.bert import BertPreTrainedModel, BertModel
|
| 10 |
+
from .configuration_protst import ProtSTConfig
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@dataclass
|
| 14 |
+
class EsmProteinRepresentationOutput(ModelOutput):
|
| 15 |
+
|
| 16 |
+
protein_feature: torch.FloatTensor = None
|
| 17 |
+
residue_feature: torch.FloatTensor = None
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@dataclass
|
| 21 |
+
class BertTextRepresentationOutput(ModelOutput):
|
| 22 |
+
|
| 23 |
+
text_feature: torch.FloatTensor = None
|
| 24 |
+
word_feature: torch.FloatTensor = None
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@dataclass
|
| 28 |
+
class ProtSTClassificationOutput(ModelOutput):
|
| 29 |
+
|
| 30 |
+
loss: Optional[torch.FloatTensor] = None
|
| 31 |
+
logits: torch.FloatTensor = None
|
| 32 |
+
|
| 33 |
+
class ProtSTHead(nn.Module):
|
| 34 |
+
def __init__(self, config, out_dim=512):
|
| 35 |
+
super().__init__()
|
| 36 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 37 |
+
self.out_proj = nn.Linear(config.hidden_size, out_dim)
|
| 38 |
+
|
| 39 |
+
def forward(self, x):
|
| 40 |
+
x = self.dense(x)
|
| 41 |
+
x = nn.functional.relu(x)
|
| 42 |
+
x = self.out_proj(x)
|
| 43 |
+
return x
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class BertForPubMed(BertPreTrainedModel):
|
| 47 |
+
def __init__(self, config):
|
| 48 |
+
super().__init__(config)
|
| 49 |
+
|
| 50 |
+
self.pad_token_id = config.pad_token_id
|
| 51 |
+
self.cls_token_id = config.cls_token_id
|
| 52 |
+
self.sep_token_id = config.sep_token_id
|
| 53 |
+
|
| 54 |
+
self.bert = BertModel(config, add_pooling_layer=False)
|
| 55 |
+
self.text_mlp = ProtSTHead(config)
|
| 56 |
+
self.word_mlp = ProtSTHead(config)
|
| 57 |
+
|
| 58 |
+
self.post_init() # NOTE
|
| 59 |
+
|
| 60 |
+
def forward(
|
| 61 |
+
self,
|
| 62 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 63 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 64 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 65 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 66 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 67 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 68 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 69 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
| 70 |
+
output_attentions: Optional[bool] = None,
|
| 71 |
+
output_hidden_states: Optional[bool] = None,
|
| 72 |
+
return_dict: Optional[bool] = None,
|
| 73 |
+
) -> Union[Tuple[torch.Tensor], ModelOutput]:
|
| 74 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 75 |
+
|
| 76 |
+
outputs = self.bert(
|
| 77 |
+
input_ids,
|
| 78 |
+
attention_mask=attention_mask,
|
| 79 |
+
token_type_ids=token_type_ids,
|
| 80 |
+
position_ids=position_ids,
|
| 81 |
+
head_mask=head_mask,
|
| 82 |
+
inputs_embeds=inputs_embeds,
|
| 83 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 84 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 85 |
+
output_attentions=output_attentions,
|
| 86 |
+
output_hidden_states=output_hidden_states,
|
| 87 |
+
return_dict=return_dict,
|
| 88 |
+
)
|
| 89 |
+
word_feature = outputs.last_hidden_state
|
| 90 |
+
is_special = (input_ids == self.cls_token_id) | (input_ids == self.sep_token_id) | (input_ids == self.pad_token_id)
|
| 91 |
+
special_mask = (~is_special).to(torch.int64).unsqueeze(-1)
|
| 92 |
+
pooled_feature = ((word_feature * special_mask).sum(1) / (special_mask.sum(1) + 1.0e-6)).to(word_feature.dtype)
|
| 93 |
+
pooled_feature = self.text_mlp(pooled_feature)
|
| 94 |
+
word_feature = self.word_mlp(word_feature)
|
| 95 |
+
|
| 96 |
+
if not return_dict:
|
| 97 |
+
return (pooled_feature, word_feature)
|
| 98 |
+
|
| 99 |
+
return BertTextRepresentationOutput(text_feature=pooled_feature, word_feature=word_feature)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class EsmForProteinRepresentation(EsmPreTrainedModel):
|
| 105 |
+
def __init__(self, config):
|
| 106 |
+
super().__init__(config)
|
| 107 |
+
|
| 108 |
+
self.cls_token_id = config.cls_token_id
|
| 109 |
+
self.pad_token_id = config.pad_token_id
|
| 110 |
+
self.eos_token_id = config.eos_token_id
|
| 111 |
+
|
| 112 |
+
self.esm = EsmModel(config, add_pooling_layer=False)
|
| 113 |
+
|
| 114 |
+
self.post_init() # NOTE
|
| 115 |
+
|
| 116 |
+
def forward(
|
| 117 |
+
self,
|
| 118 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 119 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 120 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 121 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 122 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 123 |
+
output_attentions: Optional[bool] = None,
|
| 124 |
+
output_hidden_states: Optional[bool] = None,
|
| 125 |
+
return_dict: Optional[bool] = None,
|
| 126 |
+
) -> Union[Tuple, EsmProteinRepresentationOutput]:
|
| 127 |
+
|
| 128 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 129 |
+
|
| 130 |
+
outputs = self.esm(
|
| 131 |
+
input_ids,
|
| 132 |
+
attention_mask=attention_mask,
|
| 133 |
+
position_ids=position_ids,
|
| 134 |
+
head_mask=head_mask,
|
| 135 |
+
inputs_embeds=inputs_embeds,
|
| 136 |
+
output_attentions=output_attentions,
|
| 137 |
+
output_hidden_states=output_hidden_states,
|
| 138 |
+
return_dict=return_dict,
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
residue_feature = outputs.last_hidden_state # [batch_size, seq_len, hidden_dim]
|
| 142 |
+
|
| 143 |
+
# mean readout
|
| 144 |
+
is_special = (
|
| 145 |
+
(input_ids == self.cls_token_id) | (input_ids == self.eos_token_id) | (input_ids == self.pad_token_id)
|
| 146 |
+
)
|
| 147 |
+
special_mask = (~is_special).to(torch.int64).unsqueeze(-1)
|
| 148 |
+
protein_feature = ((residue_feature * special_mask).sum(1) / (special_mask.sum(1) + 1.0e-6)).to(residue_feature.dtype)
|
| 149 |
+
|
| 150 |
+
return EsmProteinRepresentationOutput(
|
| 151 |
+
protein_feature=protein_feature, residue_feature=residue_feature
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
class ProtSTPreTrainedModel(PreTrainedModel):
|
| 156 |
+
config_class = ProtSTConfig
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
class ProtSTForProteinPropertyPrediction(ProtSTPreTrainedModel):
|
| 160 |
+
def __init__(self, config):
|
| 161 |
+
super().__init__(config)
|
| 162 |
+
|
| 163 |
+
self.config = config
|
| 164 |
+
self.protein_model = EsmForProteinRepresentation(config.protein_config)
|
| 165 |
+
self.classifier = ProtSTHead(config.protein_config, out_dim=config.num_labels)
|
| 166 |
+
|
| 167 |
+
self.post_init() # NOTE
|
| 168 |
+
|
| 169 |
+
def forward(
|
| 170 |
+
self,
|
| 171 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 172 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 173 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 174 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 175 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 176 |
+
labels: Optional[torch.LongTensor] = None,
|
| 177 |
+
output_attentions: Optional[bool] = None,
|
| 178 |
+
output_hidden_states: Optional[bool] = None,
|
| 179 |
+
return_dict: Optional[bool] = None,
|
| 180 |
+
) -> Union[Tuple, ProtSTClassificationOutput]:
|
| 181 |
+
r"""
|
| 182 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 183 |
+
Labels for computing the protein classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
|
| 184 |
+
Returns:
|
| 185 |
+
Examples:
|
| 186 |
+
"""
|
| 187 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 188 |
+
|
| 189 |
+
outputs = self.protein_model(
|
| 190 |
+
input_ids,
|
| 191 |
+
attention_mask=attention_mask,
|
| 192 |
+
position_ids=position_ids,
|
| 193 |
+
head_mask=head_mask,
|
| 194 |
+
inputs_embeds=inputs_embeds,
|
| 195 |
+
output_attentions=output_attentions,
|
| 196 |
+
output_hidden_states=output_hidden_states,
|
| 197 |
+
return_dict=return_dict,
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
logits = self.classifier(outputs.protein_feature) # [bsz, xxx] -> [bsz, num_labels]
|
| 201 |
+
|
| 202 |
+
loss = None
|
| 203 |
+
if labels is not None:
|
| 204 |
+
loss_fct = nn.CrossEntropyLoss()
|
| 205 |
+
|
| 206 |
+
labels = labels.to(logits.device)
|
| 207 |
+
loss = loss_fct(logits.view(-1, logits.shape[-1]), labels.view(-1))
|
| 208 |
+
|
| 209 |
+
if not return_dict:
|
| 210 |
+
output = (logits,)
|
| 211 |
+
return ((loss,) + output) if loss is not None else output
|
| 212 |
+
|
| 213 |
+
return ProtSTClassificationOutput(loss=loss, logits=logits)
|