-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodules.py
More file actions
2245 lines (1918 loc) · 76.2 KB
/
Copy pathmodules.py
File metadata and controls
2245 lines (1918 loc) · 76.2 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
import random
from types import FunctionType as function
import pytorch_lightning as L
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchmetrics
from attr import dataclass
@dataclass
class VESMOutputs:
S1Embeddings: dict[str, torch.Tensor]
S1Logits: dict[str, torch.Tensor]
S1Predicts_aa: dict[str, torch.Tensor]
S1Predicts: dict[str, dict[str, torch.Tensor]]
S2Embeddings: torch.Tensor | None
S2Reconstruct: dict[str, torch.Tensor] | None
S2Predicts: dict[str, torch.Tensor] | None
@dataclass
class VESMLosses:
S1PredictsLosses: dict[str, torch.Tensor] | None
S1PredictsAALosses: dict[str, torch.Tensor] | None
S1LogitsLosses: dict[str, torch.Tensor] | None
S2ReconstructLosses: dict[str, torch.Tensor] | None
S2PredictsLoss: torch.Tensor | None
@dataclass(frozen=True)
class VESMConfig:
prots: list[str]
# stage 1
esm_model_type: str
esm_model_channels: int
out_channels: int = 512
track: list[str] = None
# aa wise predicts
aa_counts: int = 33
aa_predict_classes: int = 3
# xiugai
regressor_version: str = "legacy" # 默认为"legacy"(旧版)
dropout_rate: float = 0.2
# protein wise predicts
stage1_predict_classes: int = 0
stage_1_transformer_layers: int = 5
stage_1_clf_hidden_dim: int = 512
teaching_force: float = 0.5
# stage 2
stage_2_clf_hidden_dim: int = 512
n_head: int = 16
stage_2_transformer_layers: int = 5
stage2_predict_classes: int = 0
# training params
lr: float = 1e-4
lr_backbone: float = 1e-5
weight_decay: float = 0.0
stage_1_masked_weight: float = 0.1
stage_2_masked_weight: float = 2.0
stage_1_regressor_weight: float = 1.0
stage_2_recosntruct_weight: float = 1.0
stage_2_regressor_weight: float = 1.0
stage_1_predict_loss: function | None = None
stage_2_predictLosses: function | None = None
def fixParameters(esm_model, unfix=["9", "10", "11"]):
for i, j in esm_model.named_parameters():
flag = 1
for k in unfix:
if k in i:
flag = 0
if flag == 1:
j.requires_grad = False
else:
j.requires_grad = True
return esm_model
class SelfAttention(nn.Module):
def __init__(self, channels, n_head):
super(SelfAttention, self).__init__()
self.channels = channels
# self.size = size
self.n_head = n_head
assert channels % n_head == 0
import torchtune
self.rope = torchtune.modules.RotaryPositionalEmbeddings(channels // n_head)
self.mha = nn.MultiheadAttention(channels, n_head, batch_first=True)
self.ln = nn.LayerNorm([channels])
self.ff_self = nn.Sequential(
nn.LayerNorm([channels]),
nn.Linear(channels, channels),
nn.GELU(),
nn.Linear(channels, channels),
)
def forward(self, x):
# x = x.swapaxes(1, 2)
batch, length, channel = x.shape
x = x.view(batch, length, self.n_head, self.channels // self.n_head)
# print(x.shape)
# print(self.rope(x).shape)
x = self.rope(x)
# print(x.shape)
x = x.view(batch, length, self.channels)
x_ln = self.ln(x)
attention_value, _ = self.mha(x_ln, x_ln, x_ln)
attention_value = attention_value + x
attention_value = self.ff_self(attention_value) + attention_value
return attention_value # .swapaxes(2, 1)
class DecoderBlock(nn.Module):
def __init__(
self, channels, n_head, aa_classes, predict_classes, transformer_layers=3
):
super(DecoderBlock, self).__init__()
self.channels = channels
self.n_head = n_head
self.aa_classes = aa_classes
self.predict_classes = predict_classes
self.transformer_blocks = nn.ModuleList(
[SelfAttention(channels, n_head) for i in range(transformer_layers)]
)
# self.T1 = SelfAttention(channels, n_head)
# self.T2 = SelfAttention(channels, n_head)
# self.T3 = SelfAttention(channels, n_head)
self.aa_clf = nn.Linear(channels, aa_classes)
self.clf = nn.Linear(channels, predict_classes)
def forward(self, x):
for block in self.transformer_blocks:
x = block(x)
aa_1 = self.clf(x)
aa_2 = self.aa_clf(x)
return {"predict_logits": aa_1, "aa_logits": aa_2} # .swapaxes(2, 1)
class Linearlayer(nn.Module):
def __init__(self, in_dim, out_dim, dropout=0.2, layer_norm=False, activate="gelu"):
super().__init__()
self.linear = nn.Linear(in_dim, out_dim)
if layer_norm is not None:
self.ln = nn.LayerNorm(out_dim)
else:
self.ln = None
if dropout > 0 and dropout < 1:
self.dropout = nn.Dropout(p=dropout)
else:
self.dropout = None
if activate == "gelu":
self.activate = nn.GELU()
elif activate == "relu":
self.activate = nn.ReLU()
elif activate == "leakyrelu":
self.activate = nn.LeakyReLU()
else:
self.activate = nn.Identity()
# raise ValueError("activate %s not supported" % acivate)
# self.activate = activate
def forward(self, x):
x = self.linear(x)
if self.ln is not None:
x = self.ln(x)
x = self.activate(x)
if self.dropout is not None:
x = self.dropout(x)
return x
class Linearcls(nn.Module):
"""simple linear classifier
Args:
nn (_type_): _description_
"""
def __init__(
self,
input_dim=256,
take_embed="first",
dropout=-1,
p0=None,
output_dim=1,
hidden_dim=256,
hidden_layer=-1,
activate="gelu",
layer_norm=True,
):
super().__init__()
assert take_embed in ["first", "mean", "max"]
self.embed_dim = input_dim
self.dropout = dropout
self.take_embed = take_embed
self.output_dim = output_dim
self.hidden_dim = hidden_dim
if hidden_layer == -1:
self.l1 = nn.Linear(self.embed_dim, self.embed_dim // 2)
self.l2 = nn.Linear(self.embed_dim // 2, self.embed_dim // 4)
self.l3 = nn.Linear(self.embed_dim // 4, output_dim)
self.ln1 = nn.LayerNorm(self.embed_dim // 2)
self.ln2 = nn.LayerNorm(self.embed_dim // 4)
if dropout > 0 and dropout < 1:
self.dropout1 = nn.Dropout(p=self.dropout)
self.dropout2 = nn.Dropout(p=self.dropout)
else:
self.dropout1 = None
self.dropout2 = None
self.layers = None
else:
in_dims = [input_dim] + [hidden_dim] * (hidden_layer)
output_dims = [hidden_dim] * (hidden_layer + 1)
self.layers = nn.ModuleList(
[
Linearlayer(
in_dims[i],
output_dims[i],
dropout=dropout,
layer_norm=layer_norm,
activate=activate,
)
for i in range(len(in_dims))
]
)
self.output = nn.Linear(hidden_dim, output_dim)
if p0 is None:
self.p0 = None
else:
self.p0 = nn.Dropout(p0)
def forward(self, x: torch.Tensor):
if self.take_embed == "first":
x = x[:, 0]
elif self.take_embed == "mean":
x = torch.mean(x, dim=1)
elif self.take_embed == "max":
x = x.transpose(1, 2)
x = F.adaptive_max_pool1d(x, 1)
if self.p0 is not None:
x = self.p0(x)
if self.layers is None:
x = self.l1(x)
x = self.ln1(x)
if self.dropout1 is not None:
x = self.dropout1(x)
x = F.gelu(x)
x = self.l2(x)
x = self.ln2(x)
if self.dropout2 is not None:
x = self.dropout2(x)
x = F.gelu(x)
x = self.l3(x)
return x
for layer in self.layers:
x = layer(x)
# print("lin", x.shape)
x = self.output(x)
return x
if self.output_dim == 1:
return x
else:
return x[:, 0], x[:, 1:]
class Regressors(nn.Module):
def __init__(self, out_channels, hidden_dim, predict_classes, dropout=True):
super().__init__()
if dropout:
self.dropout = nn.Dropout(p=0.2)
else:
self.dropout = None
# self.clf = nn.Sequential(
# nn.Linear(out_channels, hidden_dim),
# nn.GELU(),
# nn.LayerNorm(hidden_dim),
# nn.Dropout(p=0.2),
# nn.Linear(hidden_dim, hidden_dim),
# nn.GELU(),
# nn.LayerNorm(hidden_dim),
# nn.Linear(hidden_dim, predict_classes),
# )
# self.time_series = nn.Sequential(
# nn.Linear(out_channels, hidden_dim),
# nn.GELU(),
# nn.LayerNorm(hidden_dim),
# nn.Dropout(p=0.2),
# nn.Linear(hidden_dim, hidden_dim),
# nn.GELU(),
# nn.LayerNorm(hidden_dim),
# nn.Linear(hidden_dim, 1),
# )
self.clf = nn.Sequential(
nn.Linear(out_channels, hidden_dim),
nn.GELU(),
nn.LayerNorm(hidden_dim),
nn.Linear(hidden_dim, predict_classes),
)
# CovidFit
# self.clf = nn.Sequential(
# nn.Linear(out_channels, hidden_dim),
# nn.ReLU(),
# nn.Linear(hidden_dim, hidden_dim),
# nn.ReLU(),
# nn.Linear(hidden_dim, predict_classes),
# )
self.time_series = nn.Sequential(
nn.Linear(out_channels, hidden_dim),
nn.GELU(),
nn.LayerNorm(hidden_dim),
nn.Linear(hidden_dim, 1),
)
def forward(self, x):
if self.dropout is not None:
x = self.dropout(x)
return {"predictions": self.clf(x), "time_series": self.time_series(x)}
class RegressorsMCDropout(nn.Module):
def __init__(self, out_channels, hidden_dim, predict_classes, dropout_rate=0.2):
super().__init__()
self.clf = nn.Sequential(
nn.Linear(out_channels, hidden_dim),
nn.GELU(),
nn.LayerNorm(hidden_dim),
nn.Dropout(p=dropout_rate),
nn.Linear(hidden_dim, hidden_dim),
nn.GELU(),
nn.LayerNorm(hidden_dim),
nn.Dropout(p=dropout_rate),
nn.Linear(hidden_dim, predict_classes),
)
self.time_series = nn.Sequential(
nn.Linear(out_channels, hidden_dim),
nn.GELU(),
nn.LayerNorm(hidden_dim),
nn.Linear(hidden_dim, 1),
)
def forward(self, x):
return {"predictions": self.clf(x), "time_series": self.time_series(x)}
class VESM(L.LightningModule):
def __init__(self, esm_model, stage, config: VESMConfig):
super().__init__()
assert stage in [
"pretraining stage 1",
"training stage 1",
"training stage 2",
"training stage 1 + stage 2",
"training stage 1 finetune",
"training stage 2 from embedding",
"inference",
]
self.stage = stage
print("model at stage:", stage)
self.config = config
self.prots = config.prots
self.esm_model = ESMModule(esm_model, config.esm_model_type)
# stage 1 modules
self.stage_1_bottleneck = nn.Linear(
config.esm_model_channels, config.out_channels
)
self.stage_1_reconstructor = DecoderBlock(
config.out_channels,
config.n_head,
config.aa_counts,
config.aa_predict_classes,
config.stage_1_transformer_layers,
)
self.stage_1_embed = nn.Embedding(config.aa_counts, config.out_channels)
if config.regressor_version == "mc_dropout":
print("INFO: Using Regressors with MC Dropout for new model.")
self.stage_1_regressors = RegressorsMCDropout(
config.out_channels,
config.stage_1_clf_hidden_dim,
config.stage1_predict_classes,
dropout_rate=config.dropout_rate,
)
# 同样为stage 2也进行替换
self.stage_2_regressors = RegressorsMCDropout(
config.out_channels,
config.stage_2_clf_hidden_dim,
config.stage2_predict_classes,
dropout_rate=config.dropout_rate,
)
else:
# 如果config中没有指定版本,或指定为legacy,则使用原始类
print("INFO: Using original Regressors for backward compatibility.")
self.stage_1_regressors = Regressors(
config.out_channels,
config.stage_1_clf_hidden_dim,
config.stage1_predict_classes,
)
self.stage_2_regressors = Regressors(
config.out_channels,
config.stage_2_clf_hidden_dim,
config.stage2_predict_classes,
)
# self.stage_1_regressors = Regressors(
# config.out_channels,
# config.stage_1_clf_hidden_dim,
# config.stage1_predict_classes,
# )
# stage 2 modules
self.stage_2_encoder_blocks = nn.ModuleList(
[
SelfAttention(config.out_channels, config.n_head)
for i in range(config.stage_2_transformer_layers)
]
)
# self.stage_2_encoder_blocks = nn.TransformerEncoder(
# nn.TransformerEncoderLayer(
# d_model=config.out_channels,
# nhead=config.n_head,
# dim_feedforward=config.out_channels*2,
# dropout=0.1,
# activation="gelu",
# ),
# num_layers=config.stage_2_transformer_layers,
# )
self.stage_2_decoder_blocks = nn.ModuleList(
[
SelfAttention(config.out_channels, config.n_head)
for i in range(config.stage_2_transformer_layers)
]
)
# self.stage_2_decoder_blocks = nn.TransformerEncoder(
# nn.TransformerEncoderLayer(
# d_model=config.out_channels,
# nhead=config.n_head,
# dim_feedforward=config.out_channels*2,
# dropout=0.1,
# activation="gelu",
# ),
# num_layers=config.stage_2_transformer_layers,
# )
# self.stage_2_regressors = Regressors(
# config.out_channels,
# config.stage_2_clf_hidden_dim,
# config.stage2_predict_classes,
# )
# training utils
self.mse = nn.MSELoss()
self.bce = nn.BCEWithLogitsLoss()
self.kl = nn.KLDivLoss(reduction="none")
self.cross_entropy = nn.CrossEntropyLoss(reduction="none")
self.cross_entropy_mutation = nn.CrossEntropyLoss(
weight=torch.tensor([0.1, 1.0, 1.0])
)
self.training_step_outputs = []
self.validation_step_outputs = []
self.last_train_step = 0
self.pearson = torchmetrics.PearsonCorrCoef()
# deprecated
def stage1_forward_old(self, input_dict, masks=None):
stage_1_embeds = {}
stage_1_logits = {}
stage_1_predicts = {}
stage_1_aa_clf = {}
for i in input_dict:
if i not in self.prots:
continue
# print(input_dict[i])
x = self.esm_model(input_dict[i])
embed = self.stage_1_bottleneck(x)
batchsize, length, channels = embed.shape
embed = embed[:, 0]
stage_1_embeds[i] = embed
predicts = self.stage_1_regressors(embed)
if self.stage == "inference":
# predicts.pop("time_series")
predicts.pop("fabricated")
stage_1_predicts[i] = predicts
x = embed[:, None].repeat(1, length, 1)
if (
self.config.teaching_force > 0.0
and random.random() < self.config.teaching_force
):
if "aligned_" + i in input_dict:
q = input_dict["aligned_" + i]["seq_t"]
if q.dim() == 1:
q = q[None, :].repeat(batchsize, 1)
q = self.stage_1_embed(q)
x += q
# print(x.shape, stage_1_ori_embeds[i].shape)
x = self.stage_1_reconstructor(x)
stage_1_logits[i] = x["aa_logits"]
stage_1_aa_clf[i] = x["predict_logits"]
return stage_1_embeds, stage_1_logits, stage_1_predicts, stage_1_aa_clf
def stage1_forward(self, input_dict, masks=None):
stage_1_embeds = {}
stage_1_logits = {}
stage_1_predicts = {}
stage_1_aa_clf = {}
for i in input_dict:
if i not in self.prots:
continue
x = self.esm_model(input_dict[i])
embed = self.stage_1_bottleneck(x)
batchsize, length, channels = embed.shape
# [CLS] token embedding for protein-wise prediction
protein_embed = embed[:, 0]
stage_1_embeds[i] = protein_embed
predicts = self.stage_1_regressors(protein_embed)
if self.stage == "inference":
# predicts.pop("time_series")
predicts.pop("fabricated")
stage_1_predicts[i] = predicts
x_recon = protein_embed[:, None].repeat(1, length, 1)
if (
self.config.teaching_force > 0.0
and random.random() < self.config.teaching_force
):
if "aligned_" + i in input_dict:
aligned_data = input_dict["aligned_" + i]
# 判断其是字典还是张量
if isinstance(aligned_data, dict):
# 如果是esm3的多模态字典, 则从字典中提取 'seq_t' 张量
seq_tensor = aligned_data["seq_t"]
else:
seq_tensor = aligned_data
if seq_tensor.dim() == 1:
# unsqueeze and repeat to match batch size
seq_tensor = seq_tensor.unsqueeze(0).repeat(batchsize, 1)
seq_embedded = self.stage_1_embed(seq_tensor)
# 确保维度匹配后相加
if seq_embedded.shape == x_recon.shape:
x_recon += seq_embedded
x_output = self.stage_1_reconstructor(x_recon)
stage_1_logits[i] = x_output["aa_logits"]
stage_1_aa_clf[i] = x_output["predict_logits"]
return stage_1_embeds, stage_1_logits, stage_1_predicts, stage_1_aa_clf
def stage2_forward(self, stage_1_embeds, masks=None):
if masks is None:
masks = []
inputs = []
batch_size = 1
for i in self.prots:
if i in stage_1_embeds:
batch_size = stage_1_embeds[i].shape[0]
break
masked = torch.zeros(batch_size, self.config.out_channels).to(self.device)
# placeholder for global embedding
inputs.append(masked)
for i in self.prots:
if i in stage_1_embeds and i not in masks:
inputs.append(stage_1_embeds[i])
else:
inputs.append(masked)
inputs.append(masked)
inputs = torch.stack(inputs, dim=1)
for block in self.stage_2_encoder_blocks:
inputs = block(inputs)
embed = inputs[:, 0, :]
stage_2_embeddings = embed
stage_2_reconstruct = {}
embeded = embed[:, None].repeat(1, len(self.prots), 1)
for block in self.stage_2_decoder_blocks:
embeded = block(embeded)
for i, s in zip(range(len(self.prots)), self.prots):
stage_2_reconstruct[s] = embeded[:, i]
stage_2_predicts = self.stage_2_regressors(embed)
return stage_2_embeddings, stage_2_reconstruct, stage_2_predicts
def forward(
self,
input_dict=None,
stage_1_masks=None,
stage_2_masks=None,
only_stage_1=False,
stage_1_embeds=None,
):
# if stage_1_embeds is None:
if "stage 1" in self.stage:
stage_1_embeds, stage_1_logits, stage_1_predicts, stage_1_aa_clf = (
self.stage1_forward(input_dict, stage_1_masks)
)
if self.stage == "training stage 1" or self.stage == "pretraining stage 1":
return VESMOutputs(
S1Embeddings=stage_1_embeds,
S1Logits=stage_1_logits,
S1Predicts=stage_1_predicts,
S1Predicts_aa=stage_1_aa_clf,
S2Embeddings=None,
S2Reconstruct=None,
S2Predicts=None,
)
else:
if "from embedding" in self.stage:
stage_1_logits, stage_1_predicts, stage_1_aa_clf = None, None, None
else:
with torch.no_grad():
stage_1_embeds, stage_1_logits, stage_1_predicts, stage_1_aa_clf = (
self.stage1_forward(input_dict, stage_1_masks)
)
# else: # 如果 stage_1_embeds 不为 None, 则 stage_1_logits 等为 None
# stage_1_logits, stage_1_predicts, stage_1_aa_clf = None, None, None
if only_stage_1:
return VESMOutputs(
S1Embeddings=stage_1_embeds,
S1Logits=stage_1_logits,
S1Predicts=stage_1_predicts,
S1Predicts_aa=stage_1_aa_clf,
S2Embeddings=None,
S2Reconstruct=None,
S2Predicts=None,
)
if "stage 2" in self.stage:
(
stage_2_embeddings,
stage_2_reconstruct,
stage_2_predicts,
) = self.stage2_forward(stage_1_embeds, stage_2_masks)
else:
with torch.no_grad():
(
stage_2_embeddings,
stage_2_reconstruct,
stage_2_predicts,
) = self.stage2_forward(stage_1_embeds, stage_2_masks)
return VESMOutputs(
S1Embeddings=stage_1_embeds,
S1Logits=stage_1_logits,
S1Predicts=stage_1_predicts,
S1Predicts_aa=stage_1_aa_clf,
S2Embeddings=stage_2_embeddings,
S2Reconstruct=stage_2_reconstruct,
S2Predicts=stage_2_predicts,
)
def stage1_time_series_loss(self, output1: VESMOutputs, output2: VESMOutputs):
stage_1_time_series_loss = {}
for i in output1.S1Predicts:
t1 = output1.S1Predicts[i]["time_series"]
t2 = output2.S1Predicts[i]["time_series"]
t = t2 - t1
stage_1_time_series_loss[i] = self.bce(t, torch.ones_like(t))
return stage_1_time_series_loss
def stage1_prediction_loss(self, output: VESMOutputs, input_dict):
prediction_losses = {}
if "label" not in input_dict or self.config.stage1_predict_classes == 0:
return prediction_losses
for protein_name in output.S1Predicts:
if "predictions" not in output.S1Predicts[protein_name]:
# raise RuntimeError(
# f"output.S1Predicts中无predictions, 只有:'{output.S1Predicts}'"
# )
continue
predicted_vector = output.S1Predicts[protein_name]["predictions"][0]
true_vector = torch.cat(list(input_dict["label"].values()))
true_vector = true_vector.to(dtype=predicted_vector.dtype)
if true_vector.shape != predicted_vector.shape:
raise RuntimeError(
f"无法匹配蛋白质'{protein_name}'的标签和预测形状。"
f"标签形状: {true_vector.shape}, 预测形状: {predicted_vector.shape}"
)
loss = self.mse(predicted_vector, true_vector)
# print(true_vector)
# loss = self.mse(predicted_vector, torch.zeros_like(predicted_vector))
prediction_losses[protein_name] = loss
# print(prediction_losses)
return prediction_losses
def fitness_losses(self, output: VESMOutputs, input_dict):
fitness_losses = {}
# print("\ninput dict label:",input_dict["label"])
# print("\noutput:",output.S1Predicts)
# 检查 'label' 是否存在于输入数据中
if "label" not in input_dict:
return fitness_losses
# 遍历每个蛋白质的预测结果
for i in output.S1Predicts:
if (
isinstance(input_dict["label"], dict)
and "fitness_score" in input_dict["label"]
and "predictions" in output.S1Predicts[i]
):
# 提取真实值和预测值
true_score = input_dict["label"]["fitness_score"].float()
predicted_score = output.S1Predicts[i]["predictions"]
# 假设 true_score 是一个标量或只有一个元素的张量
if not isinstance(true_score, torch.Tensor):
true_score = torch.tensor(
true_score,
device=predicted_score.device,
dtype=predicted_score.dtype,
)
# 确保 true_score 和 predicted_score 形状可以计算MSE
if true_score.dim() == 0:
true_score = true_score.unsqueeze(0)
if true_score.shape != predicted_score.shape:
true_score = true_score.view_as(predicted_score)
# 计算MSE损失
loss = self.mse(predicted_score, true_score)
fitness_losses[i] = loss
# print("fitness_losses:",fitness_losses)
return fitness_losses
def stage1_prediction_loss_old(self, output: VESMOutputs, input_dict):
stage_1_prediction_loss = {}
if "label" not in input_dict or self.config.stage1_predict_classes == 0:
return stage_1_prediction_loss
# xiugai
# input_dict you labels, cong zhong du qu gai zhi,
# output zhong you S1Predicts 中有predictions中有预测的值, 两者算一个mse返回
for i in output.S1Predicts:
t = input_dict["label"][i][0].float()
if t.dim() == 1:
t = t.unsqueeze(0)
if self.config.stage_1_predict_loss is not None:
loss = self.config.stage_1_predict_loss(
output.S1Predicts[i]["predictions"], t
)
else:
loss = self.bce(
output.S1Predicts[i]["predictions"],
t,
)
stage_1_prediction_loss[i] = loss
return stage_1_prediction_loss
def stage1_logit_loss_old(self, output: VESMOutputs, input_dict):
stage_1_logitLosses = {}
if "ori_seq" not in input_dict:
return stage_1_logitLosses
for i in output.S1Logits:
s1 = output.S1Logits[i]
if "ori_seq_kl" in input_dict:
# use soft labels
s1 = s1.log_softmax(dim=-1)
l1 = input_dict["ori_seq_kl"][i]
loss = self.kl(s1, l1).sum(-1)
else:
s1 = s1.view(-1, s1.shape[-1])
l1 = input_dict["ori_seq"][i]["seq_t"].flatten()
loss = self.cross_entropy(s1, l1)
if (
"stage_1_masks" in input_dict
and input_dict["stage_1_masks"] is not None
):
mask = input_dict["stage_1_masks"][i].flatten().float()
mask = 1 - mask
mask[mask < 0] = -self.config.stage_1_masked_weight
mask += self.config.stage_1_masked_weight
else:
mask = torch.ones_like(loss)
loss = loss * mask
loss = loss.sum() / mask.sum()
stage_1_logitLosses[i] = loss
return stage_1_logitLosses
def stage1_logit_loss(self, output: VESMOutputs, input_dict):
stage_1_logitLosses = {}
if "ori_seq" not in input_dict:
return stage_1_logitLosses
for i in output.S1Logits: # i 是蛋白质名称,如 'S'
s1 = output.S1Logits[i]
s1 = s1.view(-1, s1.shape[-1])
ori_seq_data = input_dict["ori_seq"][i]
# 判断其是字典还是张量
if isinstance(ori_seq_data, dict):
# 如果是esm3的多模态字典, 则从字典中提取 'seq_t' 张量
l1_tensor = ori_seq_data["seq_t"]
else:
l1_tensor = ori_seq_data
l1 = l1_tensor.flatten()
loss = self.cross_entropy(s1, l1)
if (
"stage_1_masks" in input_dict
and input_dict["stage_1_masks"] is not None
):
mask = input_dict["stage_1_masks"][i].flatten().float()
mask = 1 - mask
mask[mask < 0] = -self.config.stage_1_masked_weight
mask += self.config.stage_1_masked_weight
else:
mask = torch.ones_like(loss)
loss = loss * mask
# 避免除以零的错误
if mask.sum() > 0:
loss = loss.sum() / mask.sum()
else:
loss = loss.sum() # 如果没有可计算损失的token,则不进行平均
stage_1_logitLosses[i] = loss
return stage_1_logitLosses
def stage1_aa_prediction_loss(self, output: VESMOutputs, input_dict):
stage_1_aa_logitLosses = {}
if "mutation_label" not in input_dict:
return stage_1_aa_logitLosses
for i in output.S1Predicts_aa:
s1 = output.S1Predicts_aa[i]
s1 = s1.view(-1, s1.shape[-1])
l1 = input_dict["mutation_label"][i].flatten()
# print(s1, l1)
# print(s1.shape, l1.shape)
loss = self.cross_entropy_mutation(s1, l1)
stage_1_aa_logitLosses[i] = loss
return stage_1_aa_logitLosses
def stage2_time_series_loss(self, output1: VESMOutputs, output2: VESMOutputs):
t1 = output1.S2Predicts["time_series"]
t2 = output2.S2Predicts["time_series"]
t = t2 - t1
return self.bce(t, torch.ones_like(t))
def stage2_reconstruct_loss(self, output: VESMOutputs, input_dict):
stage_2_reconstruct_loss = {}
for i in output.S2Reconstruct:
loss = self.mse(
output.S2Reconstruct[i].flatten(),
output.S1Embeddings[i].flatten(),
)
if i in input_dict["stage_2_masks"]:
loss *= self.config.stage_2_masekd_weight
stage_2_reconstruct_loss[i] = loss
return stage_2_reconstruct_loss
def stage2_prediction_loss(self, output: VESMOutputs, input_dict):
prediction_losses = None
if "label" not in input_dict or "predictions" not in output.S2Predicts:
return prediction_losses
predicted_vector = output.S2Predicts["predictions"][0]
true_vector = torch.cat(list(input_dict["label"].values()))
true_vector = true_vector.to(dtype=predicted_vector.dtype)
if true_vector.shape != predicted_vector.shape:
raise RuntimeError(
f"无法匹配stage2嵌入的标签和预测形状。"
f"标签形状: {true_vector.shape}, 预测形状: {predicted_vector.shape}"
)
loss = self.mse(predicted_vector, true_vector)
return loss
def stage2_prediction_loss_old(self, output: VESMOutputs, input_dict):
stage_2_prediction_loss = None
if "label" not in input_dict:
return stage_2_prediction_loss
t = input_dict["label"]["stage2"].float()
if t.dim() == 1:
t = t.unsqueeze(0)
if self.config.stage_2_predictLosses is not None:
loss = self.config.stage_2_predictLosses(
output.S2Predicts["predictions"], t
)
else:
loss = self.bce(
output.S2Predicts["predictions"],
t,
)
return loss
def getLoss(self, input_dict1, input_dict2=None):
if "from embedding" in self.stage:
output1 = self.forward(
stage_1_embeds=input_dict1["input"],
stage_2_masks=input_dict1.get("stage_2_masks", None),
)
else:
output1 = self.forward(
input_dict1["input"],
input_dict1.get("stage_1_masks", None),
input_dict1.get("stage_2_masks", None),
)
if input_dict2 is not None:
if "from embedding" in self.stage:
output2 = self.forward(
stage_1_embeds=input_dict2["input"],
stage_2_masks=input_dict2.get("stage_2_masks", None),
)
else:
output2 = self.forward(
input_dict2["input"],
input_dict2.get("stage_1_masks", None),
input_dict2.get("stage_2_masks", None),
)
else:
output2 = None
# print(input_dict1)
# output1 = self.forward(
# input_dict1["input"],
# input_dict1.get("stage_1_masks", None),
# input_dict1.get("stage_2_masks", None),
# )
# if input_dict2 is not None:
# output2 = self.forward(
# input_dict2["input"],
# input_dict2.get("stage_1_masks", None),
# input_dict2.get("stage_2_masks", None),
# )
# else: