-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlora_binding_sites_newest_v3.py
275 lines (228 loc) · 9.96 KB
/
lora_binding_sites_newest_v3.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
import wandb
import xml.etree.ElementTree as ET
import numpy as np
from sklearn.model_selection import train_test_split
from transformers import (
AutoModelForTokenClassification,
AutoTokenizer,
DataCollatorForTokenClassification,
TrainingArguments,
Trainer,
)
from peft import get_peft_config, PeftModel, PeftConfig, get_peft_model, LoraConfig, TaskType
from datasets import Dataset
from sklearn.metrics import accuracy_score
from datetime import datetime
# Constants
MODEL_CHECKPOINT = "facebook/esm2_t6_8M_UR50D"
MAX_SEQUENCE_LENGTH = 1024
ID2LABEL = {
0: "No binding site",
1: "Binding site"
}
LABEL2ID = {v: k for k, v in ID2LABEL.items()}
# Utility functions
def convert_binding_string_to_labels(binding_string):
return [1 if char == '+' else 0 for char in binding_string]
def truncate_labels(labels, max_length):
return [label[:max_length] for label in labels]
def compute_metrics(p):
predictions, labels = p
predictions = np.argmax(predictions, axis=2)
true_predictions = [
p for prediction, label in zip(predictions, labels) for (p, l) in zip(prediction, label) if l != -100
]
true_labels = [
l for prediction, label in zip(predictions, labels) for (p, l) in zip(prediction, label) if l != -100
]
return {"accuracy": accuracy_score(true_labels, true_predictions)}
def run_training():
# Initialize wandb
run = wandb.init()
# Retrieve hyperparameters from wandb
lr = run.config.learning_rate
batch_size = run.config.batch_size
num_epochs = run.config.num_epochs
weight_decay = run.config.weight_decay
# Parse the XML file
tree = ET.parse('binding_sites.xml')
root = tree.getroot()
# Extract all sequences and labels
all_sequences = [partner.find(".//proSeq").text for partner in root.findall(".//BindPartner")]
all_labels = [convert_binding_string_to_labels(partner.find(".//proBnd").text) for partner in root.findall(".//BindPartner")]
# Split the dataset into train and test sets
train_sequences, test_sequences, train_labels, test_labels = train_test_split(all_sequences, all_labels, test_size=0.25, shuffle=True)
# Tokenize the sequences
tokenizer = AutoTokenizer.from_pretrained(MODEL_CHECKPOINT)
train_tokenized = tokenizer(train_sequences, padding=True, truncation=True, max_length=MAX_SEQUENCE_LENGTH, return_tensors="pt", is_split_into_words=False)
test_tokenized = tokenizer(test_sequences, padding=True, truncation=True, max_length=MAX_SEQUENCE_LENGTH, return_tensors="pt", is_split_into_words=False)
train_labels = truncate_labels(train_labels, MAX_SEQUENCE_LENGTH)
test_labels = truncate_labels(test_labels, MAX_SEQUENCE_LENGTH)
# Convert the tokenized data into datasets
train_dataset = Dataset.from_dict({k: v for k, v in train_tokenized.items()}).add_column("labels", train_labels)
test_dataset = Dataset.from_dict({k: v for k, v in test_tokenized.items()}).add_column("labels", test_labels)
# Initialize model and token classification head
model = AutoModelForTokenClassification.from_pretrained(
MODEL_CHECKPOINT, num_labels=len(ID2LABEL), id2label=ID2LABEL, label2id=LABEL2ID
)
# Define the LoraConfig
peft_config = LoraConfig(
task_type=TaskType.TOKEN_CLS,
inference_mode=False,
r=16,
lora_alpha=16,
target_modules=["query", "key", "value"],
lora_dropout=0.1,
bias="all"
)
# Convert the model into a PeftModel
model = get_peft_model(model, peft_config)
# Training setup
training_args = TrainingArguments(
output_dir=wandb.run.dir, # Save within the wandb directory; makes it easier to sync
learning_rate=lr,
per_device_train_batch_size=batch_size,
per_device_eval_batch_size=batch_size,
num_train_epochs=num_epochs,
weight_decay=weight_decay,
evaluation_strategy="epoch",
save_strategy="epoch",
load_best_model_at_end=True,
report_to="wandb", # Enable logging to wandb
)
# Trainer setup
trainer = Trainer(
model=model,
args=training_args,
train_dataset=train_dataset,
eval_dataset=test_dataset,
tokenizer=tokenizer,
data_collator=DataCollatorForTokenClassification(tokenizer=tokenizer),
compute_metrics=compute_metrics,
)
# Training
trainer.train()
print(f"Best model saved at: {training_args.output_dir}")
best_model_dir = os.path.join(training_args.output_dir, sorted(os.listdir(training_args.output_dir))[-1])
print(f"Best model directory: {best_model_dir}")
def train_with_best_hyperparameters(best_hyperparameters):
"""
Train the model with the best hyperparameters obtained from the sweep
"""
# Retrieve hyperparameters from the best run
lr = best_hyperparameters['learning_rate']
batch_size = best_hyperparameters['batch_size']
num_epochs = best_hyperparameters['num_epochs']
weight_decay = best_hyperparameters['weight_decay']
# Parse the XML file
tree = ET.parse('binding_sites.xml')
root = tree.getroot()
# Extract all sequences and labels
all_sequences = [partner.find(".//proSeq").text for partner in root.findall(".//BindPartner")]
all_labels = [convert_binding_string_to_labels(partner.find(".//proBnd").text) for partner in root.findall(".//BindPartner")]
# Split the dataset into train and test sets
train_sequences, test_sequences, train_labels, test_labels = train_test_split(all_sequences, all_labels, test_size=0.25, shuffle=True)
# Tokenize the sequences
tokenizer = AutoTokenizer.from_pretrained(MODEL_CHECKPOINT)
train_tokenized = tokenizer(train_sequences, padding=True, truncation=True, max_length=MAX_SEQUENCE_LENGTH, return_tensors="pt", is_split_into_words=False)
test_tokenized = tokenizer(test_sequences, padding=True, truncation=True, max_length=MAX_SEQUENCE_LENGTH, return_tensors="pt", is_split_into_words=False)
train_labels = truncate_labels(train_labels, MAX_SEQUENCE_LENGTH)
test_labels = truncate_labels(test_labels, MAX_SEQUENCE_LENGTH)
# Convert the tokenized data into datasets
train_dataset = Dataset.from_dict({k: v for k, v in train_tokenized.items()}).add_column("labels", train_labels)
test_dataset = Dataset.from_dict({k: v for k, v in test_tokenized.items()}).add_column("labels", test_labels)
# Initialize model and token classification head
model = AutoModelForTokenClassification.from_pretrained(
MODEL_CHECKPOINT, num_labels=len(ID2LABEL), id2label=ID2LABEL, label2id=LABEL2ID
)
# Define the LoraConfig
peft_config = LoraConfig(
task_type=TaskType.TOKEN_CLS,
inference_mode=False,
r=16,
lora_alpha=16,
target_modules=["query", "key", "value"],
lora_dropout=0.1,
bias="all"
)
# Convert the model into a PeftModel
model = get_peft_model(model, peft_config)
# Training setup
training_args = TrainingArguments(
output_dir="best_model_dir", # Change this as necessary
learning_rate=lr,
per_device_train_batch_size=batch_size,
per_device_eval_batch_size=batch_size,
num_train_epochs=num_epochs,
weight_decay=weight_decay,
evaluation_strategy="epoch",
save_strategy="epoch",
load_best_model_at_end=True,
report_to="wandb", # Enable logging to wandb
)
# Trainer setup
trainer = Trainer(
model=model,
args=training_args,
train_dataset=train_dataset,
eval_dataset=test_dataset,
tokenizer=tokenizer,
data_collator=DataCollatorForTokenClassification(tokenizer=tokenizer),
compute_metrics=compute_metrics,
)
# Training
trainer.train()
# After training, save the model
timestamp = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
save_path = os.path.join("best_model_dir", f"final_best_model_{timestamp}")
trainer.save_model(save_path)
tokenizer.save_pretrained(save_path)
print(f"Best model saved at: {save_path}")
def main():
# Define the sweep configuration
sweep_config = {
"name": "lora-binding-sites-sweep",
"method": "bayes",
"metric": {
"goal": "minimize",
"name": "eval_loss"
},
"parameters": {
"learning_rate": {
"distribution": "uniform",
"min": 1e-5,
"max": 1e-3
},
"weight_decay": {
"values": [0.01, 0.03, 0.05]
},
"batch_size": {
"values": [2, 4, 8]
},
"num_epochs": {
"values": [3, 5, 7, 10]
}
}
}
# Initialize the sweep
sweep_id = wandb.sweep(sweep_config, project="lora-binding-sites-predictor")
# Start the sweep agent
wandb.agent(sweep_id, function=run_training, count=10) # Running 10 times
# After the sweep, retrieve the best run's hyperparameters
api = wandb.Api()
sweep = api.sweep(f"amelie-schreiber-math/lora-binding-sites-predictor/{sweep_id}")
# Insert the print statement here
print(sweep.runs[0].summary_metrics)
runs_with_eval_loss = [run for run in sweep.runs if 'eval/loss' in run.summary_metrics]
if runs_with_eval_loss:
best_run = sorted(runs_with_eval_loss, key=lambda run: run.summary_metrics['eval/loss'])[0]
else:
raise ValueError("No runs found with 'eval/loss' metric.")
best_hyperparameters = best_run.config
# Train with the best hyperparameters
train_with_best_hyperparameters(best_hyperparameters)
if __name__ == "__main__":
os.environ["CUDA_VISIBLE_DEVICES"] = "0" # Setting the GPU to be used
main()