Jiqing commited on
Commit
455513d
·
verified ·
1 Parent(s): c447b83

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +161 -191
README.md CHANGED
@@ -5,197 +5,167 @@ tags: []
5
 
6
  # Model Card for Model ID
7
 
8
- <!-- Provide a quick summary of what the model is/does. -->
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
 
11
 
12
- ## Model Details
13
-
14
- ### Model Description
15
-
16
- <!-- Provide a longer summary of what this model is. -->
17
-
18
- This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
-
20
- - **Developed by:** [More Information Needed]
21
- - **Funded by [optional]:** [More Information Needed]
22
- - **Shared by [optional]:** [More Information Needed]
23
- - **Model type:** [More Information Needed]
24
- - **Language(s) (NLP):** [More Information Needed]
25
- - **License:** [More Information Needed]
26
- - **Finetuned from model [optional]:** [More Information Needed]
27
-
28
- ### Model Sources [optional]
29
-
30
- <!-- Provide the basic links for the model. -->
31
-
32
- - **Repository:** [More Information Needed]
33
- - **Paper [optional]:** [More Information Needed]
34
- - **Demo [optional]:** [More Information Needed]
35
-
36
- ## Uses
37
-
38
- <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
-
40
- ### Direct Use
41
-
42
- <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
-
44
- [More Information Needed]
45
-
46
- ### Downstream Use [optional]
47
-
48
- <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
-
50
- [More Information Needed]
51
-
52
- ### Out-of-Scope Use
53
-
54
- <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
-
56
- [More Information Needed]
57
-
58
- ## Bias, Risks, and Limitations
59
-
60
- <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
-
62
- [More Information Needed]
63
-
64
- ### Recommendations
65
-
66
- <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
-
68
- Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
-
70
- ## How to Get Started with the Model
71
-
72
- Use the code below to get started with the model.
73
-
74
- [More Information Needed]
75
-
76
- ## Training Details
77
-
78
- ### Training Data
79
-
80
- <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
-
82
- [More Information Needed]
83
-
84
- ### Training Procedure
85
-
86
- <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
-
88
- #### Preprocessing [optional]
89
-
90
- [More Information Needed]
91
-
92
-
93
- #### Training Hyperparameters
94
-
95
- - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
-
97
- #### Speeds, Sizes, Times [optional]
98
-
99
- <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
-
101
- [More Information Needed]
102
-
103
- ## Evaluation
104
-
105
- <!-- This section describes the evaluation protocols and provides the results. -->
106
-
107
- ### Testing Data, Factors & Metrics
108
-
109
- #### Testing Data
110
-
111
- <!-- This should link to a Dataset Card if possible. -->
112
-
113
- [More Information Needed]
114
-
115
- #### Factors
116
-
117
- <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
-
119
- [More Information Needed]
120
-
121
- #### Metrics
122
-
123
- <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
-
125
- [More Information Needed]
126
-
127
- ### Results
128
-
129
- [More Information Needed]
130
-
131
- #### Summary
132
-
133
-
134
-
135
- ## Model Examination [optional]
136
-
137
- <!-- Relevant interpretability work for the model goes here -->
138
-
139
- [More Information Needed]
140
-
141
- ## Environmental Impact
142
-
143
- <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
-
145
- Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
-
147
- - **Hardware Type:** [More Information Needed]
148
- - **Hours used:** [More Information Needed]
149
- - **Cloud Provider:** [More Information Needed]
150
- - **Compute Region:** [More Information Needed]
151
- - **Carbon Emitted:** [More Information Needed]
152
-
153
- ## Technical Specifications [optional]
154
-
155
- ### Model Architecture and Objective
156
-
157
- [More Information Needed]
158
-
159
- ### Compute Infrastructure
160
-
161
- [More Information Needed]
162
-
163
- #### Hardware
164
-
165
- [More Information Needed]
166
-
167
- #### Software
168
-
169
- [More Information Needed]
170
-
171
- ## Citation [optional]
172
-
173
- <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
-
175
- **BibTeX:**
176
-
177
- [More Information Needed]
178
-
179
- **APA:**
180
-
181
- [More Information Needed]
182
-
183
- ## Glossary [optional]
184
-
185
- <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
-
187
- [More Information Needed]
188
-
189
- ## More Information [optional]
190
-
191
- [More Information Needed]
192
-
193
- ## Model Card Authors [optional]
194
-
195
- [More Information Needed]
196
-
197
- ## Model Card Contact
198
-
199
- [More Information Needed]
200
-
201
-
 
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 DataCollatorForLanguageModeling, DataCollatorForTokenClassification, 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 = {"acc": accuracy_score(labels, preds), "mcc": matthews_corrcoef(labels, preds)}
94
+
95
+ def preprocess_logits_for_metrics(logits, labels):
96
+ return torch.softmax(logits, dim=-1)
97
+
98
+
99
+ if __name__ == "__main__":
100
+ device = torch.device("cpu")
101
+ raw_dataset = load_dataset("Jiqing/ProtST-BinaryLocalization")
102
+ model = AutoModel.from_pretrained("Jiqing/protst-esm1b-for-sequential-classification", trust_remote_code=True, torch_dtype=torch.bfloat16).to(device)
103
+ tokenizer = AutoTokenizer.from_pretrained("facebook/esm1b_t33_650M_UR50S")
104
+
105
+ output_dir = "/home/jiqingfe/protst/protst_2/ProtST-HuggingFace/output_dir/ProtSTModel/default/ESM-1b_PubMedBERT-abs/240123_015856"
106
+ training_args = {'output_dir': output_dir, 'overwrite_output_dir': True, 'do_train': True, 'per_device_train_batch_size': 32, 'gradient_accumulation_steps': 1, \
107
+ 'learning_rate': 5e-05, 'weight_decay': 0, 'num_train_epochs': 100, 'max_steps': -1, 'lr_scheduler_type': 'constant', 'do_eval': True, \
108
+ 'evaluation_strategy': 'epoch', 'per_device_eval_batch_size': 32, 'logging_strategy': 'epoch', 'save_strategy': 'epoch', 'save_steps': 820, \
109
+ 'dataloader_num_workers': 0, 'run_name': 'downstream_esm1b_localization_fix', 'optim': 'adamw_torch', 'resume_from_checkpoint': False, \
110
+ 'label_names': ['labels'], 'load_best_model_at_end': True, 'metric_for_best_model': 'accuracy'}
111
+ training_args = HfArgumentParser(TrainingArguments).parse_dict(training_args, allow_extra_keys=False)[0]
112
+
113
+ def tokenize_protein(example, tokenizer=None):
114
+ protein_seq = example["prot_seq"]
115
+ protein_seq_str = tokenizer(protein_seq, add_special_tokens=True)
116
+ example["input_ids"] = protein_seq_str["input_ids"]
117
+ example["attention_mask"] = protein_seq_str["attention_mask"]
118
+ example["labels"] = example["localization"]
119
+
120
+ return example
121
+
122
+ func_tokenize_protein = functools.partial(tokenize_protein, tokenizer=tokenizer)
123
+
124
+ for split in ["train", "validation", "test"]:
125
+ raw_dataset[split] = raw_dataset[split].map(func_tokenize_protein, batched=False, remove_columns=["Unnamed: 0", "prot_seq", "localization"])
126
+
127
+ data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm_probability=0.0)
128
+ data_collator = DataCollatorForTokenClassification(tokenizer=tokenizer)
129
+ data_collator = DataCollatorWithPadding(tokenizer=tokenizer)
130
+
131
+ transformers.utils.logging.set_verbosity_info()
132
+ log_level = training_args.get_process_log_level()
133
+ logger.setLevel(log_level)
134
+
135
+ optimizer = create_optimizer(model)
136
+ scheduler = create_scheduler(training_args, optimizer)
137
+
138
+ # build trainer
139
+ trainer = Trainer(
140
+ model=model,
141
+ args=training_args,
142
+ train_dataset=raw_dataset["train"],
143
+ eval_dataset=raw_dataset["validation"],
144
+ data_collator=data_collator,
145
+ optimizers=(optimizer, scheduler),
146
+ compute_metrics=compute_metrics,
147
+ preprocess_logits_for_metrics=preprocess_logits_for_metrics,
148
+ )
149
+
150
+ train_result = trainer.train()
151
+
152
+ trainer.save_model()
153
+ # Saves the tokenizer too for easy upload
154
+ tokenizer.save_pretrained(training_args.output_dir)
155
+
156
+ metrics = train_result.metrics
157
+ metrics["train_samples"] = len(raw_dataset["train"])
158
+
159
+ trainer.log_metrics("train", metrics)
160
+ trainer.save_metrics("train", metrics)
161
+ trainer.save_state()
162
+
163
+ metric = trainer.evaluate(raw_dataset["test"], metric_key_prefix="test")
164
+ print("test metric: ", metric)
165
+
166
+ metric = trainer.evaluate(raw_dataset["validation"], metric_key_prefix="valid")
167
+ print("valid metric: ", metric)
168
+ ```
169
 
170
 
171