-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRESCVE.py
More file actions
2629 lines (2527 loc) · 135 KB
/
RESCVE.py
File metadata and controls
2629 lines (2527 loc) · 135 KB
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Difference: Change RELU to GELU, add layer normalization to Transformer
# Difference 2: Add concat prediction to repr_attn, change forward to <mask> sequence
# Difference 3: remove residue layer because it does not incorporate with the new input
import sys
from typing import List, Tuple, Sequence, Optional, Dict
from typing_extensions import Literal
import pandas as pd
import numpy as np
import math
import time
import os
import matplotlib.pyplot as plt
import esm
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.optim import AdamW
from torch.utils.tensorboard import SummaryWriter
from torch.utils.data import DataLoader, Dataset, DistributedSampler
from torch.nn.parallel import DataParallel
from torch.nn.parallel import DistributedDataParallel as DDP
import torch.multiprocessing as mp
import torch.distributed as dist
import glob
import re
from sklearn import metrics
import argparse
from esm.modules import TransformerLayer, MultiheadAttention, ESM1bLayerNorm, ESM1LayerNorm, gelu
from multiprocessing import Pool
import seaborn as sns
import scipy
import pickle
sys.path.append('/share/terra/Users/gz2294/esm/')
from my_utils.dataset import DMSOneHotReprDataSet, SecStrucReprDataSet
from my_utils.optimizer import get_linear_schedule_with_warmup
from my_utils.TransformerLayers import GlobalCustomAttnTransformerLayer4, GlobalCustomAttnTransformerLayer5
from my_utils.plot import plot_aucs, plot_loss
WINDOW_SIZE = 500 * 2 + 1
os.environ['CUDA_LAUNCH_BLOCKING'] = '1'
def setup(rank, world_size):
os.environ['MASTER_ADDR'] = 'localhost'
os.environ['MASTER_PORT'] = '12355'
# initialize the process group
dist.init_process_group("gloo", rank=rank, world_size=world_size)
def cleanup():
dist.destroy_process_group()
class GELU(nn.Module):
"""
Apply ESM's GELU activation function.
"""
def __init__(self):
super().__init__()
def forward(self, x):
return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0)))
class SecStrucHead(nn.Module):
"""
Secondary Structure classification problem is two heads
Head 0 for secondary structure prediction
Head 1 for RSA prediction
"""
def __init__(self, task_in_dim: int, dropout: float):
super(SecStrucHead, self).__init__()
self.head = nn.ModuleList(
(nn.Sequential(
nn.Dropout(dropout),
nn.Linear(task_in_dim, 8),
nn.LogSoftmax(dim=-1)
), nn.Sequential(
nn.Dropout(dropout),
nn.Linear(task_in_dim, 1),
nn.Sigmoid()
)
)
)
def forward(self, x):
return self.head[0](x), self.head[1](x)
class VrtReprAgentBatchConverter(object):
"""
Converts a batch of sequences to a batch of tokens
"""
def __init__(self, alphabet, max_len=1001):
self.alphabet = alphabet
self.max_len = max_len
def __call__(self, raw_batch: Sequence[Tuple[str, str]]):
# RoBERTa uses an eos token, while ESM-1 does not.
batch_size = len(raw_batch)
batch_labels, seq_str_list = zip(*raw_batch)
seq_encoded_list = [self.alphabet.encode(seq_str) for seq_str in seq_str_list]
max_len = max(self.max_len, max(len(seq_encoded) for seq_encoded in seq_encoded_list))
tokens = torch.empty(
(
batch_size,
max_len + int(self.alphabet.prepend_bos) + int(self.alphabet.append_eos),
),
dtype=torch.int64,
)
tokens.fill_(self.alphabet.padding_idx)
labels = []
strs = []
for i, (label, seq_str, seq_encoded) in enumerate(
zip(batch_labels, seq_str_list, seq_encoded_list)
):
labels.append(label)
strs.append(seq_str)
if self.alphabet.prepend_bos:
tokens[i, 0] = self.alphabet.cls_idx
seq = torch.tensor(seq_encoded, dtype=torch.int64)
tokens[
i,
int(self.alphabet.prepend_bos): len(seq_encoded)
+ int(self.alphabet.prepend_bos),
] = seq
if self.alphabet.append_eos:
tokens[i, len(seq_encoded) + int(self.alphabet.prepend_bos)] = self.alphabet.eos_idx
return labels, strs, tokens
class GraphAttnVrtOneHotReprAgent(nn.Module):
"""
Fine tune ESM model to multi-task learning.
"""
def __init__(self, language_model, language_model_repr_layer,
hidden_layer: Literal['attn', 'res', 'pass'],
tasks: List[Literal['secondary_struct', 'DMS', 'GoF_LoF', 'ClinVar']],
repr_actions: List[Literal['hidden_whole', 'hidden_pos_diff', 'hidden_pos_concat',
'attn', 'attn_concat', 'attn_mask']],
task_out_dim=None,
repr_layer_type: Literal['Layer1', 'Layer2', 'Layer3', 'Layer4', 'Layer5'] = 'Layer5',
use_rotary_embeddings=True,
dropout: float = 0.1,
freeze_language_model=True):
super(GraphAttnVrtOneHotReprAgent, self).__init__()
self.language_model = language_model
self.language_model_repr_layer = language_model_repr_layer
embedding_dim = self.language_model.layers[self.language_model_repr_layer - 1].embed_dim
# First check tasks
assert len(tasks) == len(repr_actions), \
"tasks, repr_actions must have the same length"
if task_out_dim is None:
task_out_dim = []
for task in tasks:
if task == 'secondary_struct':
task_out_dim.append(None) # secondary structure does not require this
elif task == 'DMS':
raise ValueError("DMS task requires task_out_dim")
elif task == 'GoF_LoF':
task_out_dim.append(2)
elif task == 'ClinVar':
task_out_dim.append(1)
self.tasks = tasks
self.repr_actions = repr_actions
# Define hidden layer
if hidden_layer == "attn":
# ffn_embed_dim seems a magic number, find out if it is necessary
# Turns out it somehow works as secondary structure prediction goes very well
self.hidden_layer = TransformerLayer(embed_dim=embedding_dim,
ffn_embed_dim=5120, attention_heads=20, add_bias_kv=False,
use_rotary_embeddings=False)
elif hidden_layer == "res":
# TODO: implement res layer
raise NotImplementedError("Residual layer is not implemented")
elif hidden_layer == "pass":
self.hidden_layer = nn.Identity()
# Define task heads
self.task_heads = nn.ModuleList()
task_in_dim = []
for repr_action in repr_actions:
if repr_action.endswith("concat"):
if repr_action == "attn_concat":
assert repr_layer_type == "Layer3", "attn_concat only works with Layer3"
task_in_dim.append(embedding_dim * 2)
else:
task_in_dim.append(embedding_dim)
for i, task in enumerate(tasks):
if task == "secondary_struct":
assert repr_actions[i].endswith("whole"), "Only whole representation is supported for secondary_struct"
self.task_heads.append(
SecStrucHead(task_in_dim[i], dropout=dropout)
)
elif task == "DMS":
self.task_heads.append(
nn.Sequential(
nn.Dropout(dropout),
nn.Linear(task_in_dim[i], task_out_dim[i])
)
)
elif task == "GoF_LoF":
self.task_heads.append(
nn.Sequential(
nn.Dropout(dropout),
nn.Linear(task_in_dim[i], task_out_dim[i]),
nn.LogSoftmax(dim=-1)
)
)
elif task == "ClinVar":
self.task_heads.append(
nn.Sequential(
nn.Dropout(dropout),
nn.Linear(task_in_dim[i], task_out_dim[i])
)
)
else:
raise ValueError(f"Invalid task {task}")
# Then define attn layer, if required by repr_actions
# TODO: implement attn layer
# The original d_model in gMVP was 512, num_heads was 4
# I am using a large fc layer while 20 heads like esm model
if repr_layer_type == "Layer1":
raise NotImplementedError("Layer1 is not Supported")
elif repr_layer_type == "Layer2":
raise NotImplementedError("Layer2 is not Supported")
elif repr_layer_type == "Layer3":
raise NotImplementedError("Layer3 is not Supported")
elif repr_layer_type == "Layer4":
self.repr_attn = GlobalCustomAttnTransformerLayer4(d_model=1280, d_pw=442, num_heads=20,
use_rotary_embeddings=use_rotary_embeddings)
elif repr_layer_type == "Layer5":
self.repr_attn = GlobalCustomAttnTransformerLayer5(d_model=1280, d_pw=442, num_heads=20,
use_rotary_embeddings=use_rotary_embeddings)
else:
raise ValueError(f"Invalid repr_layer_type {repr_layer_type}")
# self.repr_attn = None
# Freeze the language model if necessary
self.freeze_language_model = freeze_language_model
if freeze_language_model:
for tag, value in self.language_model.named_parameters():
# freeze all the parameters in the language model
value.requires_grad = False
def forward(self, batch_tokens, wt_aa=None, vr_aa=None, pos=None, MSA_features=None, MSA_masks=None,
task_id=None):
"""
Feed input to repr model and the classifier to compute logits.
@param batch_tokens_wt: an input array
@param batch_tokens_vr: an input array
@param pos: an input array, indicate the position of the token
@param task_id: the index of the task to be computed
@param MSA_features: an input array, indicate the features of the MSA
@param MSA_masks: an input array, indicate the masks of the MSA
"""
# Feed input to esm
if task_id is None:
task_id = 0
elif isinstance(task_id, torch.Tensor):
task_id = int(task_id.cpu()[0])
hidden = self.get_hidden(batch_tokens)
if self.repr_actions[task_id].startswith("hidden"):
if self.repr_actions[task_id] == "hidden_whole":
# the hidden starts with <bos> and ends with <eos> so we need to remove them
logits = self.task_heads[task_id](hidden[:, 1: batch_tokens.shape[1] - 1])
return logits
elif self.repr_actions[task_id] == "hidden_pos_diff":
raise NotImplementedError("hidden_pos_diff is not implemented")
elif self.repr_actions[task_id] == "hidden_pos_concat":
raise NotImplementedError("hidden_pos_concat is not implemented")
elif self.repr_actions[task_id].startswith("attn"):
# TODO implement attn layer
wt_aa_token = self.language_model.embed_tokens(wt_aa)
vr_aa_token = self.language_model.embed_tokens(vr_aa)
variant_hidden = self.get_variant_hidden(hidden[:, 1: batch_tokens.shape[1] - 1],
wt_aa_token, vr_aa_token,
pos, MSA_features, MSA_masks)
variant_logits = self.task_heads[task_id](variant_hidden)
return variant_logits
def get_embedding(self, batch_tokens, wt_aa=None, vr_aa=None, pos=None,
MSA_features=None, MSA_masks=None, task_id=None):
hidden = self.get_hidden(batch_tokens)
if self.repr_actions[task_id].startswith("hidden"):
if self.repr_actions[task_id] == "hidden_whole":
raise NotImplementedError("hidden_whole is not implemented")
elif self.repr_actions[task_id] == "hidden_pos_diff":
raise NotImplementedError("hidden_pos_diff is not implemented")
elif self.repr_actions[task_id] == "hidden_pos_concat":
raise NotImplementedError("hidden_pos_concat is not implemented")
elif self.repr_actions[task_id].startswith("attn"):
# TODO implement attn layer
wt_aa_token = self.language_model.embed_tokens(wt_aa)
vr_aa_token = self.language_model.embed_tokens(vr_aa)
variant_hidden = self.get_variant_hidden(hidden[:, 1: batch_tokens.shape[1] - 1],
wt_aa_token, vr_aa_token,
pos, MSA_features, MSA_masks)
return variant_hidden
def get_hidden(self, batch_tokens):
"""
Get representations of the batch_tokens:
"""
with torch.no_grad():
repr = self.language_model(batch_tokens,
repr_layers=[self.language_model_repr_layer],
return_contacts=False)
# get B x L X H representation
repr = repr['representations'][self.language_model_repr_layer]
# TODO: implement attn and concat
# attn = repr['attentions']
# concat = repr['contacts']
if isinstance(self.hidden_layer, TransformerLayer):
# hidden_layer is a transformer layer
repr, attn = self.hidden_layer(repr)
else:
repr = self.hidden_layer(repr)
# Ignore the attn and concat for now
return repr
def get_variant_hidden(self, hidden, wt_aa, vr_aa, pos, MSA_features, MSA_masks=None):
var_repr = self.repr_attn(hidden, wt_aa, vr_aa, pos, MSA_features, MSA_masks)
return var_repr
def add_classifier(self, d_out, repr_action, activation):
"""
Add a new classifier to the model.
@param d_out: the dimension of the output
@param activation: the activation function
@param repr_action: the repr_action
"""
raise NotImplementedError("Not implemented yet")
class VrtReprAgentDataSet(Dataset):
"""
Dataset for the VRT representation agent.
"""
def __init__(self, data_path, batch_converter, batch_size, batch_number=None, shuffle=True, num_workers=32):
"""
@param data_path: the directory containing the data
@param batch_size: the batch size
@param batch_number: optional, the number of batches to load
@param shuffle: whether to shuffle the data
@param num_workers: the number of workers to use for data loading
"""
if isinstance(data_path, pd.DataFrame):
self.data = data_path
elif isinstance(data_path, str):
self.data = pd.read_csv(data_path, index_col=0)
else:
raise ValueError("data_path must be a string or a pandas.DataFrame")
if shuffle:
self.data = self.data.sample(frac=1, random_state=0)
if batch_size is None:
assert batch_number is not None, "batch_size and batch_number cannot both be None"
self.batch_size = int(np.ceil(self.data.shape[0] / batch_number))
self.batch_number = batch_number
else:
self.batch_size = batch_size
self.batch_number = int(np.ceil(self.data.shape[0] / self.batch_size))
self.batch_converter = batch_converter
self.num_workers = num_workers
data_wt = tuple(zip(self.data['VarID'].astype('str'), self.data['wt'].astype('str')))
# data_vr = tuple(zip(self.data['VarID'].astype('str'), self.data['sequence'].astype('str')))
_, _, batch_tokens_wt = self.batch_converter(data_wt)
# _, _, batch_tokens_vr = self.batch_converter(data_vr)
ref_aa = tuple(zip(self.data['VarID'].astype('str'), self.data['ref'].astype('str')))
alt_aa = tuple(zip(self.data['VarID'].astype('str'), self.data['alt'].astype('str')))
_, _, batch_tokens_ref = self.batch_converter(ref_aa)
_, _, batch_tokens_alt = self.batch_converter(alt_aa)
labels = torch.tensor(self.data['score'].to_numpy(), dtype=torch.long)
# note we use pos-1 as the variant position is 1-indexed
pos = torch.tensor(self.data['pos'].to_numpy() - 1, dtype=torch.long)
self.batch_tokens_wt = batch_tokens_wt
self.wt_aa = batch_tokens_ref[:, [1]]
self.vr_aa = batch_tokens_alt[:, [1]]
self.labels = labels
self.pos = pos
# process MSA sequences
with Pool(46) as pool:
res = pool.starmap(self.parse_one_seq, zip(self.data['ENST'],
self.data['wt.orig'],
self.data['seq.start'],
self.data['seq.end']))
mask = pool.starmap(self.parse_mask, zip(self.data['sequence.len']))
self.msa_features = torch.tensor(np.array(res), dtype=torch.float)
self.msa_masks = torch.tensor(np.array(mask), dtype=torch.float)
@staticmethod
def parse_one_seq(transcript, wt_orig, seq_start, seq_end, check_error=False):
msa_alphabet = np.array(list('ACDEFGHIKLMNPQRSTVWYU'))
if pd.isna(transcript) or \
not os.path.exists(f'data/MSA/{transcript}.pickle'):
matched_line = False
seq = ""
else:
with open(os.path.join('data/MSA/',
transcript + '.pickle'), 'rb') as f:
msa_mat = pickle.load(f)
seq = ''.join(msa_alphabet[msa_mat[:, 0].astype(int)])
matched_line = seq == wt_orig
if matched_line:
# crop the sequence to length of the data frame, and fill to 1001
# R file parse seq_start starting from 1, so we need to minus 1
msa_mat = msa_mat[seq_start - 1:seq_end, :221]
msa_mat_seq = np.pad(msa_mat[:, [0]], ((0, 1001 - msa_mat.shape[0]), (0, 0)),
'constant', constant_values=20)
msa_mat_prob = np.pad(msa_mat[:, 1:21], ((0, 1001 - msa_mat.shape[0]), (0, 0)),
'constant', constant_values=0)
msa_mat_msa = np.pad(msa_mat[:, 21:221], ((0, 1001 - msa_mat.shape[0]), (0, 0)),
'constant', constant_values=20)
msa_mat = np.concatenate((msa_mat_seq, msa_mat_prob, msa_mat_msa), axis=1)
else:
msa_mat = np.array([[msa_alphabet.tolist().index(i) for i in wt_orig]])
msa_mat = msa_mat[seq_start - 1:seq_end, [0]]
msa_mat_seq = np.pad(msa_mat[:, [0]], ((0, 1001 - msa_mat.shape[0]), (0, 0)),
'constant', constant_values=20)
msa_mat_other = np.zeros((1001, 220))
msa_mat = np.concatenate((msa_mat_seq, msa_mat_other), axis=1)
if check_error:
return msa_mat, matched_line, seq
else:
return msa_mat
@staticmethod
def parse_mask(seq_len):
mask = np.ones((1001,), dtype=np.float32)
seq_start = 0
seq_end = seq_len
# R file parse seq_start starting from 1, so we need to minus 1
mask[seq_start:seq_end] = 0.0
return mask
def __len__(self):
return self.data.shape[0]
def __getitem__(self, idx):
return self.batch_tokens_wt[idx], self.wt_aa[idx], self.vr_aa[idx], \
self.pos[idx], self.msa_features[idx], self.msa_masks[idx], \
self.labels[idx]
def count_labels(self):
return self.data['score'].value_counts().sort_index().values
def get_max_index(self):
return int(np.ceil(len(self) / self.batch_size))
def __iter__(self):
return VrtReprAgentDataIterator(self)
class VrtReprAgentDataIterator:
"""
Iterable class that returns batches of data.
"""
def __init__(self, data_set: VrtReprAgentDataSet):
"""
@param data_set: the data set to iterate over
"""
self._dataset = data_set
self._index = 0
self._max_index = int(np.ceil(len(self._dataset) / self._dataset.batch_size))
self._batch_size = self._dataset.batch_size
def __next__(self):
"""
Returns the next batch of data.
"""
if self._index < self._max_index:
batch_idx = np.arange(self._index * self._batch_size,
min((self._index + 1) * self._batch_size, len(self._dataset)))
self._index += 1
return self._dataset.batch_tokens_wt[batch_idx], \
self._dataset.wt_aa[batch_idx], self._dataset.vr_aa[batch_idx], \
self._dataset.pos[batch_idx], self._dataset.msa_features[batch_idx], \
self._dataset.msa_masks[batch_idx], self._dataset.labels[batch_idx]
# End of Iteration
raise StopIteration
class GraphAttnVrtReprAgentTrainer(object):
"""
Train a VrtReprAgent model.
"""
def __init__(self, language_model_name, language_model_repr_layer,
hidden_layer: Literal['attn', 'res', 'pass'],
tasks: List[Literal['secondary_struct', 'DMS', 'GoF_LoF', 'ClinVar']],
repr_actions: List[
Literal['hidden_whole', 'hidden_pos_diff', 'hidden_pos_concat', 'attn', 'attn_concat']],
train_data_files, test_data_files,
batch_sizes, batch_numbers=None,
task_out_dim=None,
build_datasets=True,
dropout: float = 0.1,
freeze_language_model=True,
lr=1e-5, min_lr_ratio=0.5,
save_dir=None, save_epochs=1, save_counters=None,
num_warmup_epochs=10, num_training_epochs=30,
device_id=None, data_distributed_parallel=True, seed=0):
self.batch_converter = None
if device_id is None:
self.device = torch.device('cpu')
self.device_id = device_id
self.multi_gpu = False
self.data_distributed_parallel = False
elif isinstance(device_id, int):
torch.cuda.set_per_process_memory_fraction(1.0, device_id)
self.device = f"cuda:{device_id}" if torch.cuda.is_available() else "cpu"
self.device_id = device_id
self.multi_gpu = False
self.data_distributed_parallel = False
else:
assert torch.cuda.is_available(), "No GPU available"
if not data_distributed_parallel:
for device in device_id:
torch.cuda.set_per_process_memory_fraction(1.0, device)
# use first device to store data and model
self.device = f"cuda:{device_id[0]}"
self.device_id = device_id
self.multi_gpu = True
self.data_distributed_parallel = data_distributed_parallel
torch.cuda.empty_cache()
self.seed = seed
torch.manual_seed(seed)
self.task_number = len(tasks)
if not isinstance(batch_sizes, list):
batch_sizes = [batch_sizes] * self.task_number
if not isinstance(batch_numbers, list):
batch_numbers = [batch_numbers] * self.task_number
for batch_size, batch_number in zip(batch_sizes, batch_numbers):
if batch_size is None:
assert batch_number is not None, "batch_size and batch_number cannot both be None"
self.train_data_sets = []
self.test_data_sets = []
self.batch_sizes = batch_sizes
self.batch_numbers = batch_numbers
self.loss_funcs = []
assert len(train_data_files) == len(test_data_files) == len(tasks), \
"Number of training, testing data files and tasks must be equal."
self.tasks = tasks
self.lr = lr
self.num_warmup_epochs = num_warmup_epochs
self.num_training_epochs = num_training_epochs
self.min_lr_ratio = min_lr_ratio
self.save_dir = save_dir
self.save_epochs = save_epochs
self.save_counters = save_counters
self.writer = SummaryWriter(log_dir=os.path.join(self.save_dir, "Log/"))
self.writer_counter = 0
self.epoch_counter = 0
# first build model
self.build_model(language_model_name, language_model_repr_layer,
hidden_layer, tasks, task_out_dim,
repr_actions, dropout, freeze_language_model)
# then build data loaders
if build_datasets:
self.build_datasets(train_data_files, test_data_files)
# then build loss functions
for i in range(self.task_number):
if self.tasks[i] == 'secondary_struct':
self.loss_funcs.append([nn.NLLLoss(), nn.MSELoss()])
elif self.tasks[i] == 'GoF_LoF':
# to account for the imbalance of the GoF and LoF labels
if self.train_data_sets[i] is not None:
weights = self.train_data_sets[i].count_labels()
weights = torch.tensor(np.max(weights) / weights, dtype=torch.float).to(self.device)
self.loss_funcs.append(nn.NLLLoss(weight=weights))
else:
self.loss_funcs.append(nn.NLLLoss())
elif self.tasks[i] == 'DMS':
self.loss_funcs.append(nn.MSELoss())
elif self.tasks[i] == 'ClinVar':
self.loss_funcs.append(nn.BCEWithLogitsLoss())
# then build optimizer and scheduler
self.optimizer = AdamW(filter(lambda p: p.requires_grad, self.model.parameters()),
lr=self.lr, # Default learning rate
eps=1e-8 # Default epsilon value
)
self.scheduler = get_linear_schedule_with_warmup(self.optimizer,
num_warmup_steps=num_warmup_epochs,
num_training_steps=num_training_epochs,
minlr=self.min_lr_ratio)
self.model.to(self.device)
if device_id is not None and not isinstance(device_id, int) and not self.data_distributed_parallel:
# if you use DDP, model should be defined here
self.model = DataParallel(self.model, device_ids=device_id, output_device=self.device)
def build_model(self,
language_model_name='esm1v',
language_model_repr_layer=33,
hidden_layer='attn',
tasks=None,
task_out_dim=None,
repr_actions=None,
dropout=0.1,
freeze_language_model=True):
"""
Build the model.
"""
if language_model_name == 'esm1v':
model, alphabet = esm.pretrained.esm1v_t33_650M_UR90S_5()
self.model = GraphAttnVrtOneHotReprAgent(model, language_model_repr_layer,
hidden_layer=hidden_layer,
tasks=tasks,
task_out_dim=task_out_dim,
repr_actions=repr_actions,
dropout=dropout,
freeze_language_model=freeze_language_model)
self.batch_converter = VrtReprAgentBatchConverter(alphabet)
elif language_model_name == 'esm1b':
model, alphabet = esm.pretrained.esm1b_t33_650M_UR50S()
self.model = GraphAttnVrtOneHotReprAgent(model, language_model_repr_layer,
hidden_layer=hidden_layer,
tasks=tasks,
task_out_dim=task_out_dim,
repr_actions=repr_actions,
dropout=dropout,
freeze_language_model=freeze_language_model)
self.batch_converter = VrtReprAgentBatchConverter(alphabet)
elif language_model_name == 'esm2':
model, alphabet = esm.pretrained.esm2_t33_650M_UR50D()
self.model = GraphAttnVrtOneHotReprAgent(model, language_model_repr_layer,
hidden_layer=hidden_layer,
tasks=tasks,
task_out_dim=task_out_dim,
repr_actions=repr_actions,
dropout=dropout,
freeze_language_model=freeze_language_model)
self.batch_converter = VrtReprAgentBatchConverter(alphabet)
elif language_model_name == 'esm1b.secstruc.CHPs':
model, alphabet = esm.pretrained.esm1b_t33_650M_UR50S()
self.model = GraphAttnVrtOneHotReprAgent(model, language_model_repr_layer,
hidden_layer=hidden_layer,
tasks=tasks,
task_out_dim=task_out_dim,
repr_actions=repr_actions,
dropout=dropout,
freeze_language_model=freeze_language_model)
self.model.to(self.device)
self.batch_converter = VrtReprAgentBatchConverter(alphabet)
self.model.hidden_layer.load_state_dict(torch.load(
os.path.join("model_checkpoints/"
"gMVP.style.esm1b.secstruc.CHPs.all.transformerLayer5.CHPs/model.best.hidden_layer.pt"),
map_location=self.device)
)
self.model.repr_attn.load_state_dict(
torch.load(
os.path.join("model_checkpoints/"
"gMVP.style.esm1b.secstruc.CHPs.all.transformerLayer5.CHPs/model.best.repr_attn.pt"),
map_location=self.device
)
)
if "secondary_struct" in tasks:
self.model.task_heads[np.where(np.array(tasks) == "secondary_struct")[0][0]].load_state_dict(
torch.load(
os.path.join("model_checkpoints/"
"gMVP.style.esm1b.secstruc.CHPs.all.transformerLayer5.CHPs/model.best.task_heads.secstruc.pt"),
map_location=self.device
)
)
if "ClinVar" in tasks:
self.model.task_heads[np.where(np.array(tasks) == "ClinVar")[0][0]].load_state_dict(
torch.load(
os.path.join("model_checkpoints/"
"gMVP.style.esm1b.secstruc.CHPs.all.transformerLayer5.CHPs/model.best.task_heads.CHPs.pt"),
map_location=self.device
)
)
elif language_model_name == 'esm1b.secstruc':
model, alphabet = esm.pretrained.esm1b_t33_650M_UR50S()
self.model = GraphAttnVrtOneHotReprAgent(model, language_model_repr_layer,
hidden_layer=hidden_layer,
tasks=tasks,
task_out_dim=task_out_dim,
repr_actions=repr_actions,
dropout=dropout,
freeze_language_model=freeze_language_model)
self.model.to(self.device)
self.batch_converter = VrtReprAgentBatchConverter(alphabet)
self.model.hidden_layer.load_state_dict(torch.load(
os.path.join("model_checkpoints/"
"gMVP.style.esm1b.secstruc.CHPs.all.transformerLayer5.CHPs/model.best.hidden_layer.pt"),
map_location=self.device)
)
else:
raise NotImplementedError
def build_datasets(self, train_data_files, test_data_files):
for i, (train_file, test_file) in enumerate(zip(train_data_files, test_data_files)):
if self.tasks[i] == 'secondary_struct':
self.train_data_sets.append(
SecStrucReprDataSet(train_file, batch_size=self.batch_sizes[i], batch_number=self.batch_numbers[i],
batch_converter=self.batch_converter)
if train_file is not None else None
)
self.test_data_sets.append(
SecStrucReprDataSet(test_file, batch_size=self.batch_sizes[i], batch_number=self.batch_numbers[i],
shuffle=False,
batch_converter=self.batch_converter)
if test_file is not None else None
)
elif self.tasks[i] == 'DMS':
self.train_data_sets.append(
DMSOneHotReprDataSet(train_file, batch_size=self.batch_sizes[i], batch_number=self.batch_numbers[i],
batch_converter=self.batch_converter)
if train_file is not None else None
)
self.test_data_sets.append(
DMSOneHotReprDataSet(test_file, batch_size=self.batch_sizes[i], batch_number=self.batch_numbers[i],
shuffle=False,
batch_converter=self.batch_converter)
if test_file is not None else None
)
else:
self.train_data_sets.append(
VrtReprAgentDataSet(train_file, batch_size=self.batch_sizes[i], batch_number=self.batch_numbers[i],
batch_converter=self.batch_converter)
if train_file is not None else None
)
self.test_data_sets.append(
VrtReprAgentDataSet(test_file, batch_size=self.batch_sizes[i], batch_number=self.batch_numbers[i],
shuffle=False,
batch_converter=self.batch_converter)
if test_file is not None else None
)
def build_loss_funcs(self):
for i in range(self.task_number):
if self.tasks[i] == 'secondary_struct':
self.loss_funcs.append([nn.NLLLoss(), nn.MSELoss()])
elif self.tasks[i] == 'GoF_LoF':
# to account for the imbalance of the GoF and LoF labels
weights = self.train_data_sets[i].count_labels()
weights = torch.tensor(np.max(weights) / weights, dtype=torch.float).to(self.device)
self.loss_funcs.append(nn.NLLLoss(weight=weights))
elif self.tasks[i] == 'DMS':
self.loss_funcs.append(nn.MSELoss())
elif self.tasks[i] == 'ClinVar':
# to account for the imbalance of the labels, BCEWithLogitsLoss recommended ratio of neg / pos
weights = self.train_data_sets[i].count_labels()
weights = torch.tensor(weights[0] / weights[1], dtype=torch.float).to(self.device)
self.loss_funcs.append(nn.BCEWithLogitsLoss(pos_weight=weights))
def build_train_datasets(self, train_data_files):
for i, train_file in enumerate(train_data_files):
if self.tasks[i] == 'secondary_struct':
self.train_data_sets.append(
SecStrucReprDataSet(train_file, batch_size=self.batch_sizes[i], batch_number=self.batch_numbers[i],
batch_converter=self.batch_converter))
elif self.tasks[i] == 'DMS':
self.train_data_sets.append(
DMSOneHotReprDataSet(train_file, batch_size=self.batch_sizes[i], batch_number=self.batch_numbers[i],
batch_converter=self.batch_converter))
else:
self.train_data_sets.append(
VrtReprAgentDataSet(train_file, batch_size=self.batch_sizes[i],
batch_number=self.batch_numbers[i],
batch_converter=self.batch_converter)
)
def build_test_datasets(self, test_data_files, batch_size, batch_number):
for i, test_file in enumerate(test_data_files):
if self.tasks[i] == 'secondary_struct':
self.test_data_sets.append(
SecStrucReprDataSet(test_file, batch_size=batch_size, batch_number=batch_number,
batch_converter=self.batch_converter))
else:
self.test_data_sets.append(
VrtReprAgentDataSet(test_file, batch_size=batch_size,
batch_number=batch_number,
shuffle=False,
batch_converter=self.batch_converter)
)
def single_gpu_one_epoch(self, task_ids=None):
# zero the gradients before each epoch
self.model.zero_grad()
self.model.train()
# for warm up epochs, do not update the repr model but just classifier
if task_ids is None:
task_ids = np.arange(self.task_number).tolist()
tasks = self.task_number
else:
tasks = len(task_ids)
losses = [[] for k in range(tasks)]
# TODO: Decide let all tasks run same batches or not
# Trick here is, for one batch, we wait until all tasks has finished to calculate the gradient,
# then we update the weights.
task_finished = [False for k in range(tasks)]
batch_count = 0
iter_data_loader = [iter(self.train_data_sets[i]) for i in task_ids]
while sum(task_finished) < tasks:
batch_start_time = time.time()
loss_sum = None
for i, task_id in enumerate(task_ids):
if task_finished[i]:
continue
if self.tasks[task_id] == 'secondary_struct':
try:
batch_tokens, labels_ss, labels_rsa = next(iter_data_loader[i])
except StopIteration:
task_finished[i] = True
continue
batch_tokens = batch_tokens.to(self.device)
labels_ss = labels_ss.to(self.device)
labels_rsa = labels_rsa.to(self.device)
logits = self.model(batch_tokens, task_id=task_id)
loss_ss = self.loss_funcs[task_id][0](
logits[0].reshape(-1, logits[0].shape[-1]), labels_ss.reshape(-1)
)
loss_rsa = self.loss_funcs[task_id][1](logits[1][:, :, 0], labels_rsa)
self.write_loss([loss_ss.item(), loss_rsa.item()], task_id)
loss = loss_ss + loss_rsa
else:
try:
batch_tokens_wt, wt_aa, vr_aa, pos, msa_features, masks, labels = next(iter_data_loader[i])
except StopIteration:
task_finished[i] = True
continue
batch_tokens_wt = batch_tokens_wt.to(self.device)
wt_aa = wt_aa.to(self.device)
vr_aa = vr_aa.to(self.device)
pos = pos.to(self.device)
msa_features = msa_features.to(self.device)
masks = masks.to(self.device)
labels = labels.to(self.device)
logits = self.model(batch_tokens_wt, wt_aa, vr_aa, pos, msa_features, masks, task_id)
if self.tasks[task_id] == 'ClinVar':
logits = logits[:, 0]
labels = labels.to(torch.float)
loss = self.loss_funcs[task_id](logits, labels)
self.write_loss(loss.item(), task_id)
if loss_sum is None:
loss_sum = loss
else:
loss_sum += loss
losses[i].append(loss.item())
# step optimizer after all tasks have finished
if loss_sum is None:
break
loss_sum.backward()
self.optimizer.step()
self.optimizer.zero_grad()
self.writer_counter += 1
batch_end_time = time.time()
if self.save_counters is not None and self.writer_counter % self.save_counters == 0:
self.save_model(whole_model=False, counter_id=self.writer_counter)
print(f"Batch {batch_count} time: {batch_end_time - batch_start_time}")
batch_count += 1
# step scheduler after all batches have finished
self.scheduler.step()
self.epoch_counter += 1
for i, task_id in enumerate(task_ids):
print(f"Task {task_id} finished {len(losses[i])} batches with ",
f"loss: {np.mean(losses[i]):.4f}")
if self.epoch_counter % self.save_epochs == 0:
self.save_model(whole_model=True)
losses = [np.mean(losses[i]) for i in range(tasks)]
return losses
def data_parallel_gpu_one_epoch(self, task_ids=None):
# zero the gradients before each epoch
self.model.zero_grad()
self.model.train()
# for warm up epochs, do not update the repr model but just classifier
if task_ids is None:
task_ids = np.arange(self.task_number).tolist()
tasks = self.task_number
else:
tasks = len(task_ids)
losses = [[] for k in range(tasks)]
# TODO: Decide let all tasks run same batches or not
# Trick here is, for one batch, we wait until all tasks has finished to calculate the gradient,
# then we update the weights.
task_finished = [False for k in range(tasks)]
batch_count = 0
iter_data_loader = [iter(self.train_data_sets[i]) for i in task_ids]
while sum(task_finished) < tasks:
batch_start_time = time.time()
loss_sum = None
for i, task_id in enumerate(task_ids):
if task_finished[i]:
continue
if self.tasks[task_id] == 'secondary_struct':
try:
batch_tokens, labels_ss, labels_rsa = next(iter_data_loader[i])
except StopIteration:
task_finished[i] = True
continue
labels_ss = labels_ss.to(self.device)
labels_rsa = labels_rsa.to(self.device)
task_id_tensor = torch.tensor([task_id] * batch_tokens.shape[0], dtype=torch.int)
logits = self.model(batch_tokens, task_id=task_id_tensor)
loss_ss = self.loss_funcs[task_id][0](
logits[0].reshape(-1, logits[0].shape[-1]), labels_ss.reshape(-1)
)
loss_rsa = self.loss_funcs[task_id][1](logits[1][:, :, 0], labels_rsa)
self.write_loss([loss_ss.item(), loss_rsa.item()], task_id)
loss = loss_ss + loss_rsa
else:
try:
batch_tokens_wt, wt_aa, vr_aa, pos, msa_features, masks, labels = next(iter_data_loader[i])
except StopIteration:
task_finished[i] = True
continue
task_id_tensor = torch.tensor([task_id] * batch_tokens_wt.shape[0], dtype=torch.int)
labels = labels.to(self.device)
logits = self.model(batch_tokens_wt, wt_aa, vr_aa, pos, msa_features, masks, task_id_tensor)
if self.tasks[task_id] == 'ClinVar':
logits = logits[:, 0]
labels = labels.to(torch.float)
loss = self.loss_funcs[task_id](logits, labels)
self.write_loss(loss.item(), task_id)
if loss_sum is None:
loss_sum = loss
else:
loss_sum += loss
losses[i].append(loss.item())
# step optimizer after all tasks have finished
if loss_sum is None:
break
loss_sum.backward()
self.optimizer.step()
self.optimizer.zero_grad()
self.writer_counter += 1
batch_end_time = time.time()
if self.save_counters is not None and self.writer_counter % self.save_counters == 0:
self.save_model(whole_model=False, counter_id=self.writer_counter)
print(f"Batch {batch_count} time: {batch_end_time - batch_start_time}")
batch_count += 1
# step scheduler after all batches have finished
self.scheduler.step()
self.epoch_counter += 1
for i, task_id in enumerate(task_ids):
print(f"Task {task_id} finished {len(losses[i])} batches with ",
f"loss: {np.mean(losses[i]):.4f}")
if self.epoch_counter % self.save_epochs == 0:
self.save_model(whole_model=True)
losses = [np.mean(losses[i]) for i in range(tasks)]
return losses
def data_distributed_parallel_gpu_one_epoch(self, rank, world_size, task_ids):
# zero the gradients before each epoch
self.model.zero_grad()
self.model.train()
# set up training processes
setup(rank, world_size)
device = f'cuda:{rank}'
# if task_ids is None, then train on all tasks
if task_ids is None:
task_ids = np.arange(self.task_number).tolist()
tasks = self.task_number
else:
tasks = len(task_ids)
# set up model to the correct device and set up ddp model
model = self.model.to(device)
ddp_model = DDP(model, device_ids=[rank], output_device=rank)
losses = [[] for k in range(tasks)]
# TODO: Decide let all tasks run same batches or not
# Trick here is, for one batch, we wait until all tasks has finished to calculate the gradient,
# then we update the weights.
task_finished = [False for k in range(tasks)]
batch_count = 0
# set up data sampler
sampler = [DistributedSampler(self.train_data_sets[i],
num_replicas=world_size,
rank=rank,
shuffle=True, # May be True
seed=0) for i in task_ids]
iter_data_loader = [iter(DataLoader(self.train_data_sets[i],
batch_size=self.train_data_sets[i].batch_size,
shuffle=False, # Must be False!
num_workers=10,
sampler=sampler[j],
pin_memory=True)) for j, i in enumerate(task_ids)]
while sum(task_finished) < tasks:
batch_start_time = time.time()
loss_sum = None
for i, task_id in enumerate(task_ids):
if task_finished[i]:
continue
if self.tasks[task_id] == 'secondary_struct':
try:
batch_tokens, labels_ss, labels_rsa = next(iter_data_loader[i])
except StopIteration: